3D printer
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.
// The pretend printer for the demo of the printer example (../../demo-kit/README.md): the same answers the
// program on the Raspberry Pi gives in simulator mode (../pi/printer_companion.py), only faster, so that a
// whole print passes in about three and a half minutes. Every file name in here is made up.
(function () {
var ctx = czDemo.context;
var PRINT_SECONDS = 210; // one whole print
var RESTART_SECONDS = 6; // a new print starts this long after one is done or cancelled
var AMBIENT = 23;
var HISTORY_STEP = 5; // seconds between two entries of the temperature history
var HISTORY_LENGTH = 120; // ten minutes
var PARTS = [
{ file: 'twisted-vase.gcode', shape: 'vase', layers: 96, height: 1.25, filamentMm: 14200, nozzle: 215, bed: 60 },
{ file: 'spiral-tower.gcode', shape: 'tower', layers: 110, height: 1.4, filamentMm: 17800, nozzle: 215, bed: 60 },
{ file: 'drive-gear.gcode', shape: 'gear', layers: 44, height: 0.42, filamentMm: 9600, nozzle: 240, bed: 80 },
];
// --- The parts: the outline of every layer comes from a formula (the same ones as in printer_companion.py). ---
function round3(value) {
return Math.round(value * 1000) / 1000;
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
// A closed line around (cx, cy): `count` points, the radius for each angle from `radiusAt`.
function loop(count, radiusAt, cx, cy) {
var points = [];
for (var i = 0; i <= count; i++) {
var angle = ((i % count) / count) * 2 * Math.PI;
var radius = radiusAt(angle);
points.push(round3((cx === undefined ? 0.5 : cx) + radius * Math.cos(angle)), round3((cy === undefined ? 0.5 : cy) + radius * Math.sin(angle)));
}
return points;
}
function outline(part, layer) {
var u = part.layers > 1 ? (layer - 1) / (part.layers - 1) : 0; // 0 at the bed, 1 at the top
if (part.shape === 'vase') {
var belly = 0.3 + 0.11 * Math.sin(u * 5.2 + 0.6) - 0.05 * u;
return [loop(60, function (a) { return belly * (1 + 0.09 * Math.cos(5 * a + u * 3.2)); })];
}
if (part.shape === 'tower') {
var side = 0.3 - 0.11 * u + 0.015 * Math.sin(u * 9.4);
return [loop(64, function (a) {
var phi = a - u * 2.6;
return side / Math.pow(Math.pow(Math.abs(Math.cos(phi)), 4) + Math.pow(Math.abs(Math.sin(phi)), 4), 0.25);
})];
}
// The gear: a toothed disc with a bore and five holes, and a plain hub on top of it.
var bore = loop(20, function () { return 0.085; });
if (u >= 0.62) return [loop(28, function () { return 0.16; }), bore];
var lines = [loop(140, function (a) { return 0.37 + 0.045 * clamp(2.4 * Math.cos(14 * a), -1, 1); }), bore];
for (var hole = 0; hole < 5; hole++) {
var at = (hole / 5) * 2 * Math.PI + 0.3;
lines.push(loop(14, function () { return 0.055; }, 0.5 + 0.215 * Math.cos(at), 0.5 + 0.215 * Math.sin(at)));
}
return lines;
}
// --- The print job and the heaters. ---
var sim = {
index: 0,
state: 'printing',
printed: 0.35 * PRINT_SECONDS, // seconds of printing done; the demo starts with the part already visible
clock: 0, // the simulation's own seconds: it stands still while the demo is paused
endedAt: 0,
nozzle: { actual: PARTS[0].nozzle, target: PARTS[0].nozzle },
bed: { actual: PARTS[0].bed, target: PARTS[0].bed },
history: [],
sampledAt: 0,
lastReal: Date.now(),
};
var sockets = [];
function part() {
return PARTS[sim.index];
}
function wobble(heater, swing, seconds) {
if (heater.target <= 0) return heater.actual;
return heater.actual + swing * (Math.sin(seconds / 3.1) + 0.45 * Math.sin(seconds / 0.9 + 1) + (ctx.rand() - 0.5) * 0.5);
}
function reading(heater, swing) {
return { actual: Math.round(wobble(heater, swing, sim.clock) * 10) / 10, target: heater.target };
}
function job() {
var current = part();
var progress = sim.state === 'done' ? 1 : clamp(sim.printed / PRINT_SECONDS, 0, 1);
var layer = Math.min(current.layers, Math.floor(progress * current.layers) + 1);
return {
state: sim.state,
file: current.file,
progress: Math.round(progress * 10000) / 10000,
layer: layer,
layers: current.layers,
elapsedSeconds: Math.round(sim.printed),
remainingSeconds: Math.max(0, Math.round(PRINT_SECONDS - sim.printed)),
filamentUsedMm: Math.round(progress * current.filamentMm * 10) / 10,
speedPercent: layer <= 2 ? 50 : 100, // the first layers go down slowly
};
}
function temps() {
return { t: Math.round(Date.now() / 1000), nozzle: reading(sim.nozzle, 1.1), bed: reading(sim.bed, 0.3) };
}
function broadcast(message) {
sockets.forEach(function (socket) {
socket.send(message);
});
}
function setState(state) {
sim.state = state;
var heating = state === 'printing' || state === 'paused';
sim.nozzle.target = heating ? part().nozzle : 0;
sim.bed.target = heating ? part().bed : 0;
if (state === 'done' || state === 'cancelled') sim.endedAt = sim.clock;
broadcast({ type: 'state', state: state, job: job() });
}
function approach(heater, seconds, heatTau, coolTau) {
var goal = heater.target > 0 ? heater.target : AMBIENT;
var tau = goal > heater.actual ? heatTau : coolTau;
heater.actual += (goal - heater.actual) * (1 - Math.exp(-seconds / tau));
}
function tick() {
var now = Date.now();
// Not more than a second and a half at once: when the demo was paused off screen, the print does not jump.
var seconds = clamp((now - sim.lastReal) / 1000, 0, 1.5);
sim.lastReal = now;
sim.clock += seconds;
if (sim.state === 'printing') {
sim.printed += seconds;
if (sim.printed >= PRINT_SECONDS) {
sim.printed = PRINT_SECONDS;
setState('done');
}
} else if ((sim.state === 'done' || sim.state === 'cancelled') && sim.clock - sim.endedAt >= RESTART_SECONDS) {
sim.index = (sim.index + 1) % PARTS.length;
sim.printed = 0;
setState('printing');
}
approach(sim.nozzle, seconds, 6, 30);
approach(sim.bed, seconds, 10, 70);
if (sim.clock - sim.sampledAt >= HISTORY_STEP) {
sim.sampledAt = sim.clock;
var now2 = temps();
sim.history.push({ t: now2.t, nozzle: now2.nozzle.actual, bed: now2.bed.actual });
while (sim.history.length > HISTORY_LENGTH) sim.history.shift();
}
}
// The ten minutes before the demo opened: the end of an earlier print cooling down, then this print heating up.
(function prefill() {
var now = Math.round(Date.now() / 1000);
for (var back = HISTORY_LENGTH - 1; back >= 0; back--) {
var age = back * HISTORY_STEP; // seconds ago
var nozzle;
var bed;
if (age > 150) {
var cooling = 570 - age; // the earlier print ended 570 s ago
nozzle = cooling < 0 ? 215 : AMBIENT + (215 - AMBIENT) * Math.exp(-cooling / 110);
bed = cooling < 0 ? 60 : AMBIENT + (60 - AMBIENT) * Math.exp(-cooling / 200);
} else {
var heating = 150 - age;
nozzle = 215 - (215 - 27) * Math.exp(-heating / 14);
bed = 60 - (60 - 28) * Math.exp(-heating / 25);
}
var settled = age <= 110 || age > 570 ? 1 : 0;
sim.history.push({
t: now - age,
nozzle: Math.round((nozzle + settled * 1.1 * (Math.sin(age / 3.1) + (ctx.rand() - 0.5) * 0.6)) * 10) / 10,
bed: Math.round((bed + settled * 0.3 * Math.sin(age / 4.3)) * 10) / 10,
});
}
})();
function change(from, to) {
return function () {
tick();
if (from.indexOf(sim.state) < 0) return ctx.respond(409, { error: 'The job is ' + sim.state + '.', job: job() });
setState(to);
return job();
};
}
czDemo.define({
device: { name: 'printer-pi', title: 'Printer' },
routes: {
'GET /job': function () {
tick();
return job();
},
'GET /temps': function () {
tick();
var now = temps();
return { t: now.t, nozzle: now.nozzle, bed: now.bed, history: sim.history };
},
'GET /toolpath': function (request) {
tick();
var current = part();
var layer = request.query.has('layer') ? Number(request.query.get('layer')) : job().layer;
if (!Number.isInteger(layer) || layer < 1 || layer > current.layers) {
return ctx.respond(404, { error: 'This job has the layers 1 to ' + current.layers + '.' });
}
return { layer: layer, layers: current.layers, z: round3((layer / current.layers) * current.height), polylines: outline(current, layer) };
},
'POST /job/pause': change(['printing'], 'paused'),
'POST /job/resume': change(['paused'], 'printing'),
'POST /job/cancel': change(['printing', 'paused'], 'cancelled'),
},
sockets: {
'/events': function (socket) {
sockets.push(socket);
tick();
socket.send({ type: 'state', state: sim.state, job: job() });
var timer = setInterval(function () {
tick();
var now = temps();
socket.send({ type: 'progress', t: now.t, job: job(), temps: { nozzle: now.nozzle, bed: now.bed } });
}, 1000);
socket.onclose = function () {
clearInterval(timer);
sockets.splice(sockets.indexOf(socket), 1);
};
},
},
});
})();