Duas lâmpadas, ESP32
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">
<meta name="color-scheme" content="dark">
<title>Lamp</title>
<style>
:root {
--bg: #15100d; --cream: #f6eadb; --soft: rgba(246,234,219,.68); --faint: rgba(246,234,219,.5); --line: rgba(246,234,219,.1);
--card: rgba(255,236,214,.045); --pick: #ffb45e; --good: #b9e08a; --bad: #ff9a8a;
--serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, "Noto Serif", serif;
--sans: 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; color: var(--cream); font: 14px/1.45 var(--sans); overflow-x: hidden; background: var(--bg);
background-image: radial-gradient(130% 62% at 50% 0%, #2a1b13 0%, #15100d 58%, #0f0b09 100%); background-repeat: no-repeat; background-size: 100% 100vh;
-webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: transparent; font-variant-numeric: tabular-nums; }
button { font: inherit; color: inherit; border: 0; background: none; padding: 0; cursor: pointer; }
:focus-visible { outline: 2px solid var(--pick); outline-offset: 3px; }
main { max-width: 520px; margin: 0 auto; padding: calc(18px + env(safe-area-inset-top)) calc(16px + env(safe-area-inset-right)) calc(22px + env(safe-area-inset-bottom)) calc(16px + env(safe-area-inset-left)); }
header { text-align: center; }
.eyebrow { font-size: 11px; letter-spacing: .22em; text-transform: uppercase; color: var(--faint); }
h1 { margin: 4px 0 0; font: italic 400 27px/1.2 var(--serif); letter-spacing: .01em; }
h1 small { font-size: 17px; color: var(--faint); margin: 0 6px; }
/* ---------- the two rings ---------- */
.pair { position: relative; display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: 18px; }
.lamp { position: relative; text-align: center; min-width: 0; }
.ring { position: relative; display: block; width: min(100%, 176px); aspect-ratio: 1; margin: 0 auto; border-radius: 50%; }
.ring .halo { position: absolute; inset: -14%; border-radius: 50%; background: radial-gradient(circle, var(--c, #ffb45e) 0%, rgba(0,0,0,0) 66%); opacity: 0; pointer-events: none; }
.ring svg { position: relative; display: block; width: 100%; height: 100%; overflow: visible; }
.ring .board { fill: #1d1612; stroke: rgba(246,234,219,.14); stroke-width: 1; }
.ring .pad { fill: #261c16; stroke: rgba(246,234,219,.22); stroke-width: 1; transition: fill .2s; }
.ring .led { fill: #3a2d25; }
.ring .lit { fill: var(--c, #ffb45e); }
.ring text { fill: var(--faint); font: 600 8px var(--sans); letter-spacing: .16em; text-anchor: middle; }
button.ring:active .pad { fill: #3a2a20; }
button.ring:disabled { cursor: default; }
.name { margin: 10px 0 0; font: italic 400 19px/1.2 var(--serif); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.where { display: inline-flex; align-items: center; gap: 7px; margin-top: 3px; font-size: 12.5px; color: var(--soft); white-space: nowrap; }
.where i { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); flex: none; }
.where.yes i { background: var(--good); box-shadow: 0 0 8px var(--good); } .where.no i { background: var(--bad); }
.spark { position: absolute; left: 50%; top: 34%; width: 9px; height: 9px; margin: -4px; border-radius: 50%; background: var(--c, #ffb45e); box-shadow: 0 0 14px 3px var(--c, #ffb45e); opacity: 0; pointer-events: none; }
.spark.out { animation: out 1s cubic-bezier(.4,0,.2,1); } .spark.in { animation: in 1s cubic-bezier(.4,0,.2,1); }
@keyframes out { 0% { transform: translateX(-24vw); opacity: 0 } 15% { opacity: 1 } 85% { opacity: 1 } 100% { transform: translateX(24vw); opacity: 0 } }
@keyframes in { 0% { transform: translateX(24vw); opacity: 0 } 15% { opacity: 1 } 85% { opacity: 1 } 100% { transform: translateX(-24vw); opacity: 0 } }
@media (min-width: 520px) { @keyframes out { 0% { transform: translateX(-125px); opacity: 0 } 15%, 85% { opacity: 1 } 100% { transform: translateX(125px); opacity: 0 } }
@keyframes in { 0% { transform: translateX(125px); opacity: 0 } 15%, 85% { opacity: 1 } 100% { transform: translateX(-125px); opacity: 0 } } }
/* ---------- sending ---------- */
.card { margin-top: 20px; padding: 16px; border-radius: 26px; background: var(--card); border: 1px solid var(--line); }
.colors { display: flex; justify-content: space-between; gap: 4px; }
.colors button { width: 44px; height: 44px; border-radius: 50%; display: grid; place-items: center; border: 1.5px solid transparent; transition: border-color .2s; }
.colors button::before { content: ""; width: 30px; height: 30px; border-radius: 50%; background: var(--s); box-shadow: 0 0 12px -2px var(--s); }
.colors button[aria-checked="true"] { border-color: var(--s); }
.patterns { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-top: 12px; }
.patterns button { padding: 9px 2px 8px; border-radius: 14px; border: 1px solid transparent; color: var(--soft); font-size: 12.5px; display: flex; flex-direction: column; align-items: center; gap: 4px; }
.patterns svg { width: 34px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
.patterns button[aria-checked="true"] { background: rgba(255,236,214,.07); border-color: var(--line); color: var(--pick); }
#send { display: block; width: 100%; margin-top: 14px; padding: 15px 12px; border-radius: 99px; background: var(--pick); color: #2a1706; font: italic 400 20px/1.2 var(--serif);
box-shadow: 0 10px 26px -12px var(--pick), inset 0 1px 0 rgba(255,255,255,.4); transition: transform .15s, opacity .3s, background .3s; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#send:active { transform: scale(.98); }
#send:disabled { opacity: .55; cursor: default; }
#say { min-height: 21px; margin: 14px 0 0; text-align: center; color: var(--soft); }
/* ---------- history ---------- */
.sum { margin: 16px 8px 0; text-align: center; font: italic 400 16.5px/1.5 var(--serif); color: var(--soft); }
.sum b { font-weight: 400; color: var(--cream); }
ol { list-style: none; margin: 14px 0 0; padding: 0; border-top: 1px solid var(--line); }
li { display: flex; align-items: center; gap: 10px; padding: 10px 2px; border-bottom: 1px solid var(--line); color: var(--soft); font-size: 13.5px; white-space: nowrap; }
li time { min-width: 62px; font-size: 12.5px; color: var(--faint); flex: none; }
li i { width: 10px; height: 10px; border-radius: 50%; background: var(--s); box-shadow: 0 0 8px var(--s); flex: none; }
li span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
li em { font-style: normal; color: var(--faint); font-size: 12.5px; }
li em.no { color: var(--bad); }
.empty { padding: 14px 2px; color: var(--faint); text-align: center; border-bottom: 1px solid var(--line); }
.note { margin: 12px 4px 0; font-size: 12px; color: var(--faint); text-align: center; }
footer { display: flex; justify-content: center; gap: 6px 16px; flex-wrap: wrap; margin-top: 16px; color: var(--faint); font-size: 12px; }
footer span { white-space: nowrap; }
#sim { color: var(--pick); }
@media (max-width: 359px) { h1 { font-size: 23px; } .colors button { width: 40px; height: 40px; } #send { font-size: 18px; } }
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
</style>
</head>
<body>
<main>
<header>
<div class="eyebrow">Two lamps</div>
<h1><span id="hN">–</span><small>&</small><span id="oN">–</span></h1>
</header>
<section class="pair" aria-label="The two lamps">
<div class="lamp" id="hL">
<button class="ring" id="hR" type="button" disabled aria-label="Touch this lamp: send a glow"><span class="halo"></span></button>
<p class="name" id="hName">–</p>
<span class="where"><i></i><span>this lamp</span></span>
</div>
<div class="lamp" id="oL">
<div class="ring" id="oR" role="img" aria-label="The other lamp"><span class="halo"></span></div>
<p class="name" id="oName">–</p>
<span class="where" id="oW"><i></i><span id="oWT">not called yet</span></span>
</div>
<span class="spark" id="spark"></span>
</section>
<section class="card" aria-label="Send a glow">
<div class="colors" id="colors" role="radiogroup" aria-label="Colour"></div>
<div class="patterns" id="patterns" role="radiogroup" aria-label="Pattern"></div>
<button id="send" type="button" disabled>Send a glow</button>
</section>
<p id="say" role="status">Asking the lamp</p>
<p class="sum" id="sum"></p>
<ol id="list" aria-label="The last glows"></ol>
<p class="note">The lamp keeps this list in memory: it starts again when the lamp restarts.</p>
<footer>
<span id="rssi">Wi-Fi</span>
<span id="up"></span>
<span id="sim" hidden>Simulated hardware</span>
</footer>
</main>
<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 LEDS = 16;
var SWATCHES = ['#ffb45e', '#ff8fa3', '#ff7a59', '#b9a0ff', '#8fb8ff', '#86e0c2'];
var SHAPES = { glow: 'M3 8h28', pulse: 'M3 10c5 0 5-6 9-6s5 8 10 8 5-6 9-6', heartbeat: 'M2 9h9l3-6 4 11 3-5h11', wave: 'M2 12c8 0 9-8 15-8s7 8 15 8' };
var LABELS = { glow: 'Glow', pulse: 'Pulse', heartbeat: 'Heartbeat', wave: 'Wave' };
var state = null, picked = null, pattern = 'glow', busy = false, seenChanges = -1, entries = [], counts = null;
var glows = { here: null, other: null }; // { color, pattern, start, end } in the clock of this page
var rings = {};
function text(node, value) { if (node.textContent !== value) node.textContent = value; }
function svg(name, attrs, parent) {
var e = document.createElementNS(NS, name);
for (var k in attrs) e.setAttribute(k, attrs[k]);
parent.appendChild(e);
return e;
}
// One ring as the lamp has it: sixteen LEDs around a touch pad.
function buildRing(host, withPad) {
var s = svg('svg', { viewBox: '0 0 160 160', 'aria-hidden': 'true' }, host);
svg('circle', { cx: 80, cy: 80, r: 74, 'class': 'board' }, s);
svg('circle', { cx: 80, cy: 80, r: 38, 'class': 'pad' }, s);
if (withPad) svg('text', { x: 80, y: 83 }, s).textContent = 'TOUCH';
var leds = [];
for (var i = 0; i < LEDS; i++) {
var a = (i / LEDS) * 2 * Math.PI - Math.PI / 2;
var x = 80 + 58 * Math.cos(a), y = 80 + 58 * Math.sin(a);
svg('circle', { cx: x.toFixed(1), cy: y.toFixed(1), r: 7.5, 'class': 'led' }, s);
leds.push(svg('circle', { cx: x.toFixed(1), cy: y.toFixed(1), r: 7.5, 'class': 'lit', opacity: 0 }, s));
}
return { host: host, halo: host.querySelector('.halo'), leds: leds };
}
rings.here = buildRing($('hR'), true);
rings.other = buildRing($('oR'), false);
// How bright one LED is, 0 to 1, at `t` seconds into a glow that lasts `total` seconds. The sketch uses
// the same formulas for the real ring.
function level(kind, t, total, index) {
var envelope = Math.min(1, t / 0.6, (total - t) / 3);
if (envelope <= 0) return 0;
var v = 1;
if (kind === 'pulse') v = 0.35 + 0.65 * (0.5 - 0.5 * Math.cos((2 * Math.PI * t) / 2.4));
else if (kind === 'heartbeat') {
var x = (t / 1.2) % 1, a = (x - 0.08) / 0.05, b = (x - 0.30) / 0.06;
v = 0.18 + 0.82 * Math.max(Math.exp(-a * a), 0.7 * Math.exp(-b * b));
} else if (kind === 'wave') v = 0.25 + 0.75 * (0.5 + 0.5 * Math.cos(2 * Math.PI * (index / LEDS - t / 3)));
return v * envelope;
}
function paint(which, now) {
var ring = rings[which], glow = glows[which], sum = 0;
if (glow && now >= glow.end) glow = glows[which] = null;
for (var i = 0; i < LEDS; i++) {
// Without motion the ring is a still picture: lit evenly while the lamp glows.
var v = !glow ? 0 : RM ? 0.85 : level(glow.pattern, (now - glow.start) / 1000, (glow.end - glow.start) / 1000, i);
sum += v;
ring.leds[i].setAttribute('opacity', v.toFixed(3));
}
ring.halo.style.opacity = ((sum / LEDS) * 0.55).toFixed(3);
if (glow) ring.host.style.setProperty('--c', glow.color);
}
function frame() {
var now = Date.now();
paint('here', now);
paint('other', now);
if (!RM) requestAnimationFrame(frame);
}
if (RM) setInterval(frame, 500); else requestAnimationFrame(frame);
function take(which, glow) {
if (!glow) { glows[which] = null; return; }
var end = Date.now() + glow.remainingSeconds * 1000;
var old = glows[which];
// The same glow as before keeps its start, so that its pattern does not jump with every answer.
if (old && old.color === glow.color && old.pattern === glow.pattern && Math.abs(old.end - end) < 2500) return;
glows[which] = { color: glow.color, pattern: glow.pattern, start: end - glow.seconds * 1000, end: end };
}
// ---------- 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 from the lamp')); }, 7000); });
return Promise.race([fetch(path, init), late]).then(function (r) {
return r.text().then(function (raw) {
var data = null;
try { data = JSON.parse(raw); } catch (e) { /* not JSON */ }
if (!r.ok || data === null) throw new Error((data && data.error) || 'The lamp answered ' + r.status);
return data;
});
});
}
function ago(seconds) {
if (seconds < 60) return 'just now';
if (seconds < 3600) return Math.floor(seconds / 60) + ' min ago';
return Math.floor(seconds / 3600) + ' h ago';
}
// The time of day, with the day of the week in front when it was not today.
var DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
function clock(secondsAgo) {
var d = new Date(Date.now() - secondsAgo * 1000), h = d.getHours(), m = d.getMinutes();
var time = (h < 10 ? '0' : '') + h + ':' + (m < 10 ? '0' : '') + m;
return d.toDateString() === new Date().toDateString() ? time : DAYS[d.getDay()] + ' ' + time;
}
function span(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';
}
function show(s) {
var first = state === null;
state = s;
text($('hN'), s.here.name); text($('oN'), s.other.name);
text($('hName'), s.here.name); text($('oName'), s.other.name);
document.title = s.here.name;
if (first) {
picked = SWATCHES.indexOf(s.here.color) >= 0 ? s.here.color : SWATCHES[0];
choices();
rings.here.host.style.setProperty('--c', s.here.color);
}
take('here', s.here.glow);
take('other', s.other.glow);
if (RM) frame();
var w = $('oW');
w.className = 'where' + (s.other.reachable === true ? ' yes' : s.other.reachable === false ? ' no' : '');
text($('oWT'), s.other.reachable === true ? 'answered ' + ago(s.other.lastAnswerSecondsAgo) : s.other.reachable === false ? 'did not answer' : 'not called yet');
busy = s.sending === true;
$('send').disabled = busy;
$('hR').disabled = busy;
text($('send'), busy ? 'On its way' : 'Send a glow to ' + s.other.name);
if (!says.until || Date.now() > says.until) {
text($('say'), busy ? 'Calling ' + s.other.name + '.' : s.here.glow ? 'A glow from ' + s.other.name + '.' : s.other.glow ? s.other.name + ' is glowing.' : 'Touch the ring, here or on the lamp.');
}
text($('rssi'), typeof s.rssi === 'number' ? 'Wi-Fi ' + Math.round(s.rssi) + ' dBm' : 'Wi-Fi');
text($('up'), typeof s.uptimeSeconds === 'number' ? 'running ' + span(s.uptimeSeconds) : '');
$('sim').hidden = s.simulated !== true;
if (s.changes !== seenChanges) { seenChanges = s.changes; loadHistory(); }
}
var says = { until: 0 };
function say(message, ms) { text($('say'), message); says.until = Date.now() + (ms || 4000); }
function spark(direction, color) {
if (RM) return;
var node = $('spark');
node.className = 'spark';
node.style.setProperty('--c', color);
void node.offsetWidth; // starts the animation again
node.className = 'spark ' + direction;
}
function showHistory(h) {
// What changed since the last answer: a spark for a glow that arrived here, and for one that arrived there.
var known = {};
entries.forEach(function (e) { known[e.id] = e; });
if (counts !== null) h.entries.forEach(function (e) {
var before = known[e.id];
if (e.direction === 'received' && !before) spark('in', e.color);
if (e.direction === 'sent' && e.delivered === true && (!before || before.delivered !== true)) { spark('out', e.color); say('It arrived: ' + state.other.name + ' is glowing.'); }
if (e.direction === 'sent' && e.delivered === false && (!before || before.delivered !== false)) say(state.other.name + ' could not be reached. The glow did not arrive.', 6000);
});
entries = h.entries;
counts = { received: h.received, sent: h.sent };
var sum = $('sum');
sum.textContent = '';
var parts = ['This lamp glowed ', [h.received === 1 ? 'once' : h.received + ' times'], ' since it started. You sent ', [h.sent === 1 ? 'one glow' : h.sent + ' glows'], '.'];
parts.forEach(function (part) {
if (typeof part === 'string') sum.appendChild(document.createTextNode(part));
else { var b = document.createElement('b'); b.textContent = part[0]; sum.appendChild(b); }
});
var list = $('list');
list.textContent = '';
if (h.entries.length === 0) {
var none = document.createElement('li');
none.className = 'empty';
none.textContent = 'No glows yet.';
list.appendChild(none);
}
h.entries.forEach(function (e) {
var li = document.createElement('li');
var t = document.createElement('time'); t.textContent = clock(e.secondsAgo);
var dot = document.createElement('i'); dot.style.setProperty('--s', e.color);
var what = document.createElement('span');
what.textContent = (e.direction === 'received' ? 'from ' : 'to ') + state.other.name + ', ' + (LABELS[e.pattern] || e.pattern).toLowerCase();
var how = document.createElement('em');
if (e.direction === 'sent' && e.delivered === false) { how.className = 'no'; how.textContent = 'did not arrive'; }
else if (e.direction === 'sent' && e.delivered === null) how.textContent = 'on its way';
else how.textContent = e.via === 'touch' ? 'touch' : 'phone';
li.appendChild(t); li.appendChild(dot); li.appendChild(what); li.appendChild(how);
list.appendChild(li);
});
}
function loadHistory() {
if (!state) return;
api('/history').then(showHistory).catch(function () { seenChanges = -1; });
}
// ---------- choosing and sending ----------
function choices() {
var colors = $('colors'), patterns = $('patterns');
colors.textContent = ''; patterns.textContent = '';
SWATCHES.forEach(function (c) {
var b = document.createElement('button');
b.type = 'button'; b.setAttribute('role', 'radio'); b.setAttribute('aria-label', 'Colour ' + c); b.style.setProperty('--s', c);
b.setAttribute('aria-checked', String(c === picked));
b.onclick = function () { picked = c; choices(); };
colors.appendChild(b);
});
(state.patterns || []).forEach(function (p) {
var b = document.createElement('button');
b.type = 'button'; b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', String(p === pattern));
var s = document.createElementNS(NS, 'svg'); s.setAttribute('viewBox', '0 0 34 16'); s.setAttribute('aria-hidden', 'true');
svg('path', { d: SHAPES[p] || SHAPES.glow }, s);
b.appendChild(s); b.appendChild(document.createTextNode(LABELS[p] || p));
b.onclick = function () { pattern = p; choices(); };
patterns.appendChild(b);
});
$('send').style.background = picked;
$('send').style.boxShadow = '0 10px 26px -12px ' + picked + ', inset 0 1px 0 rgba(255,255,255,.4)';
}
function send() {
if (!state || busy) return;
busy = true;
$('send').disabled = true; $('hR').disabled = true;
say('Calling ' + state.other.name + '.', 2500);
api('/glow', { color: picked, pattern: pattern }).then(function () { return api('/state').then(show); }).catch(function (error) {
say(error.message + '.', 6000);
busy = false;
$('send').disabled = false; $('hR').disabled = false;
});
}
$('send').onclick = send;
$('hR').onclick = send;
var failures = 0;
function poll() {
api('/state').then(function (s) { failures = 0; show(s); }).catch(function () {
if (++failures >= 3) { text($('say'), 'The lamp does not answer.'); $('send').disabled = true; $('hR').disabled = true; }
}).then(function () { setTimeout(poll, 1200); });
}
poll();
})();
</script>
</body>
</html>