Observations
demo-kit/ est ce qui simule l’appareil pour la démo sur la page de démarrage. L’appareil lui-même n’en a pas besoin.
demo-kit/ est ce qui simule l’appareil pour la démo sur la page de démarrage. L’appareil lui-même n’en a pas besoin.
// The pretend field log for the demo (../../demo-kit/README.md): the same answers the device's server gives
// (../server.mjs), with four sightings to start with. What the page saves is kept in the demo's memory, photos
// and voice notes as the Blobs the page sent, and is gone when the page is closed. The swallowtail's photo is
// drawn here (a butterfly on a flower in a meadow) and the robin's voice note is synthesised (a short song as
// WAV), so that the demo shows both without a camera or a microphone.
(function () {
var ctx = czDemo.context;
var routes = {};
var LIMITS = { maxEntries: 30, maxNoteChars: 1000, maxSpeciesChars: 80, maxCount: 999, maxPhotoBytes: 1500000, maxAudioBytes: 1000000, keepHours: 24 };
var PHOTO_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
var AUDIO_TYPES = ['audio/webm', 'audio/ogg', 'audio/mp4', 'audio/mpeg', 'audio/wav'];
var startedAt = Date.now();
var entries = []; // newest first, as the server keeps them
function newId() {
var id = '';
for (var i = 0; i < 12; i++) id += Math.floor(ctx.rand() * 16).toString(16);
return id;
}
function minutesAgo(minutes) {
return new Date(startedAt - minutes * 60000).toISOString();
}
/** Yesterday at hours:minutes, local time. */
function yesterdayAt(hours, minutes) {
var d = new Date(startedAt);
d.setDate(d.getDate() - 1);
d.setHours(hours, minutes, 0, 0);
return d.toISOString();
}
/** A picture drawn on a canvas, as a JPEG Blob: a swallowtail on a flower head in a meadow, the sky soft behind. */
function drawnPhoto() {
var canvas = document.createElement('canvas');
canvas.width = 960;
canvas.height = 720;
var g = canvas.getContext('2d');
var sky = g.createLinearGradient(0, 0, 0, 720);
sky.addColorStop(0, '#b9d3c4');
sky.addColorStop(0.55, '#9fbf86');
sky.addColorStop(1, '#5d7d3e');
g.fillStyle = sky;
g.fillRect(0, 0, 960, 720);
// Out-of-focus meadow: soft blobs of green and a few flowers.
for (var b = 0; b < 46; b++) {
var bx = ctx.rand() * 960;
var by = 260 + ctx.rand() * 460;
var r = 20 + ctx.rand() * 60;
var blob = g.createRadialGradient(bx, by, 0, bx, by, r);
var flower = b % 9 === 0;
blob.addColorStop(0, flower ? 'rgba(240,240,250,0.7)' : 'rgba(70,110,50,0.45)');
blob.addColorStop(1, 'rgba(70,110,50,0)');
g.fillStyle = blob;
g.fillRect(bx - r, by - r, r * 2, r * 2);
}
// Stems and the flower head (wild carrot: a flat white umbel).
g.strokeStyle = '#4c6a2e';
g.lineWidth = 8;
g.beginPath();
g.moveTo(470, 720);
g.bezierCurveTo(480, 620, 460, 540, 480, 470);
g.stroke();
g.lineWidth = 3;
for (var s = -6; s <= 6; s++) {
g.beginPath();
g.moveTo(480, 470);
g.lineTo(480 + s * 26, 430 - Math.abs(s) * 2);
g.stroke();
}
for (var f = 0; f < 140; f++) {
var a = ctx.rand() * Math.PI;
var d = ctx.rand() * 175;
g.fillStyle = f % 5 ? '#f6f4ea' : '#e6e2cf';
g.beginPath();
g.arc(480 + Math.cos(a) * d, 428 - Math.sin(a) * d * 0.16, 7 + ctx.rand() * 5, 0, Math.PI * 2);
g.fill();
}
// The swallowtail, wings open, seen from above.
g.save();
g.translate(480, 236);
g.scale(0.9, 0.9);
function wing(side) {
g.save();
g.scale(side, 1);
// Hind wing with its tail.
g.fillStyle = '#f2d24b';
g.beginPath();
g.moveTo(6, 10);
g.bezierCurveTo(70, 20, 150, 60, 120, 120);
g.bezierCurveTo(110, 140, 96, 150, 92, 196);
g.lineTo(80, 196);
g.bezierCurveTo(78, 160, 60, 140, 30, 120);
g.bezierCurveTo(14, 90, 6, 50, 6, 10);
g.fill();
// Fore wing.
g.beginPath();
g.moveTo(6, 0);
g.bezierCurveTo(60, -120, 210, -160, 250, -120);
g.bezierCurveTo(240, -60, 170, 10, 6, 14);
g.fill();
// Black veins and margins.
g.strokeStyle = '#1d1b16';
g.lineWidth = 5;
g.beginPath();
g.moveTo(6, 0);
g.bezierCurveTo(60, -120, 210, -160, 250, -120);
g.bezierCurveTo(240, -60, 170, 10, 6, 14);
g.stroke();
g.lineWidth = 14;
g.beginPath();
g.moveTo(232, -128);
g.bezierCurveTo(226, -70, 170, -10, 120, 8);
g.stroke();
g.lineWidth = 3;
for (var v = 0; v < 5; v++) {
g.beginPath();
g.moveTo(10, 4);
g.lineTo(90 + v * 32, -110 + v * 26);
g.stroke();
}
g.lineWidth = 7;
g.beginPath();
g.moveTo(52, -96);
g.lineTo(60, -34);
g.moveTo(104, -128);
g.lineTo(100, -40);
g.stroke();
g.lineWidth = 12;
g.beginPath();
g.moveTo(118, 118);
g.bezierCurveTo(100, 136, 92, 150, 88, 192);
g.stroke();
// Blue crescents and the red eye spot on the hind wing.
g.fillStyle = '#4c79c9';
for (var c = 0; c < 4; c++) {
g.beginPath();
g.arc(44 + c * 22, 112 + c * 4, 7, 0, Math.PI * 2);
g.fill();
}
g.fillStyle = '#d4462a';
g.beginPath();
g.arc(30, 122, 9, 0, Math.PI * 2);
g.fill();
g.restore();
}
wing(1);
wing(-1);
g.fillStyle = '#1d1b16';
g.beginPath();
g.ellipse(0, 20, 9, 70, 0, 0, Math.PI * 2);
g.fill();
g.strokeStyle = '#1d1b16';
g.lineWidth = 3;
g.beginPath();
g.moveTo(-3, -46);
g.quadraticCurveTo(-20, -90, -34, -104);
g.moveTo(3, -46);
g.quadraticCurveTo(20, -90, 34, -104);
g.stroke();
g.restore();
var bytes = atob(canvas.toDataURL('image/jpeg', 0.82).split(',')[1]);
var data = new Uint8Array(bytes.length);
for (var j = 0; j < bytes.length; j++) data[j] = bytes.charCodeAt(j);
return new Blob([data], { type: 'image/jpeg' });
}
/** About two seconds of a robin-like song, as a WAV Blob: falling and rising whistles with short gaps. */
function synthSong() {
var rate = 22050;
var notes = [
[0.0, 0.16, 5200, 3900], [0.2, 0.1, 4300, 4800], [0.34, 0.22, 3600, 2900], [0.62, 0.08, 6100, 5600], [0.73, 0.08, 6000, 5400],
[0.86, 0.3, 3100, 4100], [1.24, 0.12, 4800, 3600], [1.4, 0.18, 5500, 4500], [1.64, 0.26, 3400, 2700],
];
var length = Math.round(rate * 2.05);
var samples = new Int16Array(length);
notes.forEach(function (note) {
var start = Math.round(note[0] * rate);
var count = Math.round(note[1] * rate);
var phase = 0;
for (var i = 0; i < count && start + i < length; i++) {
var t = i / count;
var freq = note[2] + (note[3] - note[2]) * t + Math.sin(i / 90) * 160;
phase += (2 * Math.PI * freq) / rate;
var env = Math.sin(Math.PI * t) * (0.75 + 0.25 * Math.sin(i / 40));
samples[start + i] += Math.round(Math.sin(phase) * env * 9000);
}
});
var buffer = new ArrayBuffer(44 + length * 2);
var view = new DataView(buffer);
function text(offset, value) {
for (var k = 0; k < value.length; k++) view.setUint8(offset + k, value.charCodeAt(k));
}
text(0, 'RIFF');
view.setUint32(4, 36 + length * 2, true);
text(8, 'WAVE');
text(12, 'fmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, 1, true);
view.setUint32(24, rate, true);
view.setUint32(28, rate * 2, true);
view.setUint16(32, 2, true);
view.setUint16(34, 16, true);
text(36, 'data');
view.setUint32(40, length * 2, true);
for (var s = 0; s < length; s++) view.setInt16(44 + s * 2, samples[s], true);
return new Blob([buffer], { type: 'audio/wav' });
}
function describe(entry) {
var photo = entry.photo || (entry.drawnPhoto ? { type: 'image/jpeg', size: 52000 } : null);
var audio = entry.audio || (entry.song ? { type: 'audio/wav', size: 90244 } : null);
return {
id: entry.id,
createdAt: entry.createdAt,
note: entry.note,
species: entry.species || '',
count: entry.count == null ? null : entry.count,
location: entry.location,
photo: photo && { type: photo.type, size: photo.size },
audio: audio && { type: audio.type, size: audio.size },
sample: entry.sample || undefined,
};
}
function find(id) {
for (var i = 0; i < entries.length; i++) if (entries[i].id === id) return entries[i];
return null;
}
var gone = 'There is no such entry; it may have been deleted or pushed out by newer ones.';
/** species, count and note as the server reads them: a refusal (a string) or the value. */
function readWords(value, into) {
if ('note' in value) {
if (value.note != null && typeof value.note !== 'string') return 'The note has to be text.';
var note = (value.note || '').trim();
if (Array.from(note).length > LIMITS.maxNoteChars) return 'The note is longer than ' + LIMITS.maxNoteChars + ' characters.';
into.note = note;
}
if ('species' in value) {
if (value.species != null && typeof value.species !== 'string') return 'The species has to be text.';
var species = (value.species || '').replace(/\s+/g, ' ').trim();
if (Array.from(species).length > LIMITS.maxSpeciesChars) return 'The species is longer than ' + LIMITS.maxSpeciesChars + ' characters.';
into.species = species;
}
if ('count' in value) {
var count = value.count;
if (count != null && (typeof count !== 'number' || count % 1 !== 0 || count < 1 || count > LIMITS.maxCount)) return 'The count has to be a whole number from 1 to ' + LIMITS.maxCount + '.';
into.count = count == null ? null : count;
}
if ('location' in value) {
into.location = value.location && typeof value.location === 'object' ? { lat: value.location.lat, lon: value.location.lon, accuracy: value.location.accuracy == null ? null : Math.round(value.location.accuracy) } : null;
}
return null;
}
/** The addresses of one entry, as the server has them for every entry. */
function addRoutes(entry) {
var path = '/entries/' + entry.id;
routes['GET ' + path] = function () {
return find(entry.id) ? describe(entry) : ctx.respond(404, gone);
};
routes['PUT ' + path] = function (request) {
if (!find(entry.id)) return ctx.respond(404, gone);
var value = request.json();
if (!value || typeof value !== 'object' || Array.isArray(value)) return ctx.respond(400, 'The entry has to be a JSON object.');
var change = {};
var problem = readWords(value, change);
if (problem) return ctx.respond(problem.indexOf('note is longer') >= 0 ? 413 : 400, problem);
Object.keys(change).forEach(function (key) {
entry[key] = change[key];
});
return describe(entry);
};
routes['DELETE ' + path] = function () {
if (!find(entry.id)) return ctx.respond(404, gone);
remove(entry);
return null;
};
['photo', 'audio'].forEach(function (part) {
var isPhoto = part === 'photo';
routes['GET ' + path + '/' + part] = function () {
if (!find(entry.id)) return ctx.respond(404, gone);
if (isPhoto && !entry.photo && entry.drawnPhoto) {
var picture = drawnPhoto();
entry.photo = { type: 'image/jpeg', size: picture.size, data: picture };
}
if (!isPhoto && !entry.audio && entry.song) {
var song = synthSong();
entry.audio = { type: 'audio/wav', size: song.size, data: song };
}
var media = entry[part];
if (!media) return ctx.respond(404, isPhoto ? 'This entry has no photo.' : 'This entry has no voice note.');
return media.data;
};
routes['PUT ' + path + '/' + part] = function (request) {
if (!find(entry.id)) return ctx.respond(404, gone);
var type = String(request.headers.get('Content-Type') || '').split(';')[0].trim().toLowerCase();
if (!isPhoto && type === 'video/webm') type = 'audio/webm';
var known = isPhoto ? PHOTO_TYPES : AUDIO_TYPES;
if (known.indexOf(type) < 0) {
return ctx.respond(415, isPhoto ? 'A photo has to be a JPEG, PNG or WebP picture.' : 'A voice note has to be WebM, Ogg, MP4, MP3 or WAV audio.');
}
var body = request.body instanceof Blob ? request.body : new Blob([request.body || '']);
var limit = isPhoto ? LIMITS.maxPhotoBytes : LIMITS.maxAudioBytes;
if (body.size > limit) {
return ctx.respond(413, (isPhoto ? 'The photo is larger than ' : 'The voice note is larger than ') + (limit / 1000000).toFixed(1) + ' MB.');
}
entry[part] = { type: type, size: body.size, data: body };
return describe(entry);
};
routes['DELETE ' + path + '/' + part] = function () {
if (!find(entry.id)) return ctx.respond(404, gone);
entry[part] = null;
if (isPhoto) entry.drawnPhoto = false;
else entry.song = false;
return describe(entry);
};
});
}
function remove(entry) {
entries = entries.filter(function (candidate) {
return candidate !== entry;
});
var path = '/entries/' + entry.id;
Object.keys(routes).forEach(function (key) {
if (key.split(' ')[1].indexOf(path) === 0) delete routes[key];
});
}
function add(entry, atEnd) {
entry.id = newId();
if (atEnd) entries.push(entry);
else entries.unshift(entry);
addRoutes(entry);
// The oldest go first, the example entry among them.
while (entries.length > LIMITS.maxEntries) remove(entries[entries.length - 1]);
return entry;
}
add({ createdAt: minutesAgo(22), species: 'Swallowtail', count: 1, note: 'On the wild carrot at the edge of the meadow, wings open in the sun for a good minute before it drifted off over the hedge.', location: { lat: 52.51702, lon: 13.37955, accuracy: 6 }, photo: null, drawnPhoto: true, audio: null }, true);
add({ createdAt: minutesAgo(74), species: 'Goldfinch', count: 4, note: 'A small flock working the thistle heads along the path, twittering the whole time.', location: { lat: 52.51834, lon: 13.37612, accuracy: 9 }, photo: null, audio: null }, true);
add({ createdAt: yesterdayAt(19, 5), species: 'Robin', count: 1, note: 'Singing from the top of the hawthorn at dusk.', location: { lat: 52.51577, lon: 13.36518, accuracy: 12 }, photo: null, audio: null, song: true }, true);
add({ createdAt: yesterdayAt(16, 40), species: 'Blackbird', count: 1, note: 'Example entry: a blackbird singing from the top of a lime tree in the Tiergarten, Berlin. Add your own sightings above, and delete this one whenever you like.', location: { lat: 52.514548, lon: 13.350095, accuracy: 15 }, photo: null, audio: null, sample: true }, true);
routes['GET /info'] = function () {
return {
name: 'Sightings',
entries: entries.length,
uptimeSeconds: Math.floor(5 * 3600 + 21 * 60 + ctx.seconds()),
limits: LIMITS,
appsConnected: 1,
};
};
routes['GET /entries'] = function () {
return entries.map(describe);
};
routes['POST /entries'] = function (request) {
var value = request.json();
if (!value || typeof value !== 'object' || Array.isArray(value)) return ctx.respond(400, 'The entry has to be a JSON object.');
var words = { note: '', species: '', count: null, location: null };
var problem = readWords(value, words);
if (problem) return ctx.respond(problem.indexOf('note is longer') >= 0 ? 413 : 400, problem);
words.createdAt = new Date().toISOString();
words.photo = null;
words.audio = null;
var entry = add(words);
return ctx.respond(201, describe(entry));
};
czDemo.define({ device: { name: 'field-log', title: 'Sightings' }, routes: routes });
})();