create-rulecad 0.3.26 → 0.3.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +1 -1
- package/machines/arm/projects/arm/STREAMER.md +108 -35
- package/machines/arm/projects/arm/firmware/arm/arm.ino +76 -35
- package/machines/arm/projects/arm/send.mjs +51 -28
- package/machines/leg/projects/leg/STREAMER.md +209 -0
- package/machines/leg/projects/leg/firmware/leg/leg.ino +256 -0
- package/machines/leg/projects/leg/send.mjs +157 -0
- package/machines/leg/rules/leg.json +1 -1
- package/package.json +1 -1
- package/template/AGENTS.md +2 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Sends a step file (rulecad.steps/1, from cad plot: an arm's drawing or a leg's gait) to the streamer, line by line, each
|
|
3
|
+
// after the last was answered. The streamer runs on an Uno under a CNC Shield V3 (three axes) or a Mega 2560 (eight): the
|
|
4
|
+
// machine description's controller says which.
|
|
5
|
+
// node send.mjs <file.steps.json> --port /dev/tty.usbmodem101 [--machine arm.machine.json] [--no-home]
|
|
6
|
+
// node send.mjs <file.steps.json> --dry-run [--machine arm.machine.json] [--quiet]
|
|
7
|
+
// echoes each line it would send with the answer the streamer would give,
|
|
8
|
+
// checked against the protocol, the streamer's MAX_RATE and the machine's rates
|
|
9
|
+
// The protocol is written up in STREAMER.md, beside this file.
|
|
10
|
+
// No dependencies: a serial port is a file, set up with stty.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import { spawnSync } from 'node:child_process';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
|
|
15
|
+
/** The fastest block the streamer takes, steps/s on its major axis: arm.ino's RATE_LIMIT (a test holds the two equal). */
|
|
16
|
+
export const MAX_RATE = 8000;
|
|
17
|
+
|
|
18
|
+
/** The boards the streamer is built for: its axes (a block line has a signed step count for each) and the longest line it
|
|
19
|
+
* reads (its LINE_MAX), as arm.ino has them. */
|
|
20
|
+
export const STREAMERS = { uno: { board: 'Uno under a CNC Shield V3', axes: 3, lineMax: 95 }, mega: { board: 'Mega 2560', axes: 8, lineMax: 127 } };
|
|
21
|
+
/** The streamer a machine's files go to: its controller's board (cad machine writes it), the Uno where it names none.
|
|
22
|
+
* @param {object} [machine] @returns {{ name: string, board: string, axes: number, lineMax: number }} */
|
|
23
|
+
export function streamerOf(machine) {
|
|
24
|
+
const name = machine?.controller?.board ?? 'uno';
|
|
25
|
+
if (!STREAMERS[name]) throw new Error(`the machine's controller.board is "${name}", and the streamer runs on ${Object.keys(STREAMERS).join(' or ')}`);
|
|
26
|
+
return { name, ...STREAMERS[name] };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The serial line's time for one byte, s: 115200 baud, 10 bits a byte (a start bit, 8 data bits, a stop bit). */
|
|
30
|
+
export const BYTE_TIME = 10 / 115200;
|
|
31
|
+
/** The bytes of the streamer's answer to a block: "ok", then CR and LF (Serial.println). */
|
|
32
|
+
export const ANSWER_BYTES = 4;
|
|
33
|
+
/** The time a line and its answer wait in the USB link, past their own bytes on the wire, s: an estimate. The Uno's
|
|
34
|
+
* USB chip (an ATmega16U2 running Arduino-usbserial) passes the streamer's answer on to the computer when its timer 0
|
|
35
|
+
* overflows, every 256 x 256 / 16 MHz = 4.1 ms (Arduino-usbserial.c in ArduinoCore-avr, "TCCR0B = (1 << CS02)" and the
|
|
36
|
+
* TOV0 flush, read 2026-11-23), and the computer sends the next line in a USB frame, every 1 ms at full speed. A board
|
|
37
|
+
* with another USB chip (a CH340 on many copies) differs: the bench test times it. */
|
|
38
|
+
export const TURNAROUND = 0.0051;
|
|
39
|
+
|
|
40
|
+
/** The least time a block must last for the streamer to keep up, s: its line's bytes and newline, then the answer, on the
|
|
41
|
+
* wire, and the turnaround. The sender sends a line only after the last was answered, so a run of shorter blocks empties
|
|
42
|
+
* the queue and the motors stop between blocks. On a simulated Uno the streamer answers a line as soon as its last byte
|
|
43
|
+
* is in (it parses each character as it arrives), so the line and its answer are the whole of its cost there.
|
|
44
|
+
* @param {string} line @param {{ turnaround?: number }} [o] turnaround 0 for a board with no USB link (the simulation) */
|
|
45
|
+
export function leastBlockTime(line, { turnaround = TURNAROUND } = {}) {
|
|
46
|
+
return (line.length + 1 + ANSWER_BYTES) * BYTE_TIME + turnaround;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** One step file as the protocol's lines, in order. @param {object} file
|
|
50
|
+
* @param {{ pen?: { up: number, down: number }, axes?: number, names?: string[] }} [o] axes: the streamer's (3 on the Uno,
|
|
51
|
+
* 8 on the Mega), a number for each in a block's line; names: the machine's axes in order (cad machine's description),
|
|
52
|
+
* which the file's must match, so a file written for one machine never drives another's motors */
|
|
53
|
+
export function linesOf(file, { pen = { up: 90, down: 30 }, axes = 3, names } = {}) {
|
|
54
|
+
if (file?.format !== 'rulecad.steps/1') throw new Error(`not a step file (format is ${JSON.stringify(file?.format)}, wanted rulecad.steps/1)`);
|
|
55
|
+
const own = (file.axes || []).map((a) => a?.name);
|
|
56
|
+
if (names && own.every(Boolean) && (own.length > names.length || own.some((n, k) => n !== names[k]))) throw new Error(`the file's axes are ${own.join(', ')}, and the machine's are ${names.join(', ')}: this file was written for another machine (cad plot it for this one)`);
|
|
57
|
+
if (file.axes.length > axes) throw new Error(`${file.axes.length} axes in the file, and the streamer has ${axes}${axes < STREAMERS.mega.axes ? ` (on an Uno; give --machine with a Mega 2560 as its controller for up to ${STREAMERS.mega.axes})` : ''}`);
|
|
58
|
+
const lines = [];
|
|
59
|
+
for (const b of file.blocks) {
|
|
60
|
+
if (b.type === 'pen') lines.push(`p ${b.state === 'down' ? pen.down : pen.up} ${Math.round(b.dwell * 1000)}`);
|
|
61
|
+
else if (b.type === 'dwell') lines.push(`w ${Math.round(b.time * 1000)}`);
|
|
62
|
+
else if (b.type === 'move') {
|
|
63
|
+
const s = Array.from({ length: axes }, (_, k) => b.steps[k] ?? 0), r = b.rate;
|
|
64
|
+
lines.push(`m ${s.join(' ')} ${Math.round(r.entry)} ${Math.max(1, Math.round(r.peak))} ${Math.round(r.exit)} ${Math.max(1, Math.round(r.accel))} ${b.accelSteps} ${b.decelSteps}`);
|
|
65
|
+
} else throw new Error(`a block of type ${JSON.stringify(b.type)}`);
|
|
66
|
+
}
|
|
67
|
+
return lines;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The lines to home a machine, from cad machine's description. @param {object} machine */
|
|
71
|
+
export function homeLines(machine) {
|
|
72
|
+
return machine.axes.flatMap((a, i) => (a.homing ? [`h ${i} ${a.homing.direction} ${a.homing.rate} ${a.homing.back}`] : []));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** What the streamer would answer to each line, so the protocol can be tested with no board. Throws at the first line it
|
|
76
|
+
* would refuse, naming it, and at a block too short for the streamer to keep up with (leastBlockTime). With a machine
|
|
77
|
+
* (cad machine's description), each axis's share of a block's rate is held to that axis's maxRate too, and the streamer is
|
|
78
|
+
* its controller's (streamerOf: the Uno's three axes where it names none). A dry run has no clock, so it takes each block as
|
|
79
|
+
* finished before the next line: `?` answers the positions summed from the blocks so far (a home sets its axis to 0) with
|
|
80
|
+
* 0 blocks queued, and `!` answers `ok`.
|
|
81
|
+
* @param {string[]} lines @param {{ machine?: object, turnaround?: number }} [o] turnaround as leastBlockTime takes it
|
|
82
|
+
* @returns {{ lines: number, m: number, p: number, w: number, h: number, e: number, d: number, '?': number, '!': number, peakRate: number, axisPeaks: number[], position: number[], said: string[] }} */
|
|
83
|
+
export function dryRun(lines, { machine, turnaround = TURNAROUND } = {}) {
|
|
84
|
+
const st = streamerOf(machine), n = st.axes, all = Array.from({ length: n }, (_, k) => k);
|
|
85
|
+
const seen = { m: 0, p: 0, w: 0, h: 0, e: 0, d: 0, '?': 0, '!': 0 }, axisPeaks = all.map(() => 0), position = all.map(() => 0), said = [];
|
|
86
|
+
let peak = 0;
|
|
87
|
+
for (const [i, l] of lines.entries()) {
|
|
88
|
+
const [c, ...args] = l.split(' '), x = args.map(Number), at = `line ${i + 1} ("${l}")`;
|
|
89
|
+
if (l.length > st.lineMax) throw new Error(`${at}: longer than the streamer's ${st.lineMax} characters`);
|
|
90
|
+
if (!(c in seen)) throw new Error(`${at}: no such command (the streamer takes e, d, h, p, w, m, ? and !)`);
|
|
91
|
+
if (x.some((v) => !Number.isInteger(v))) throw new Error(`${at}: its numbers are whole`);
|
|
92
|
+
if (c === 'h' && (x.length !== 4 || x[0] < 0 || x[0] >= n || x[2] <= 0)) throw new Error(`${at}: a home is an axis ${n === 3 ? '0, 1 or 2' : `0 to ${n - 1}`}, a direction, a rate over 0 and the steps back`);
|
|
93
|
+
if (c === 'm') {
|
|
94
|
+
if (x.length !== n + 6) throw new Error(`${at}: a block is ${n + 6} numbers (a step count for each of the streamer's ${n} axes, then six rates and counts)`);
|
|
95
|
+
const major = Math.max(...x.slice(0, n).map(Math.abs)), [entry, top, exit, accel] = x.slice(n, n + 4);
|
|
96
|
+
if (!major) throw new Error(`${at}: a block that moves nothing`);
|
|
97
|
+
if (top <= 0 || accel <= 0) throw new Error(`${at}: a block's peak rate and acceleration are over 0`);
|
|
98
|
+
const fastest = Math.max(entry, top, exit);
|
|
99
|
+
if (fastest > MAX_RATE) throw new Error(`${at}: ${fastest} steps/s is past the streamer's MAX_RATE of ${MAX_RATE} (it would answer "error: rate")`);
|
|
100
|
+
for (const k of all) {
|
|
101
|
+
const r = (fastest * Math.abs(x[k])) / major, axis = machine?.axes?.[k];
|
|
102
|
+
axisPeaks[k] = Math.max(axisPeaks[k], r);
|
|
103
|
+
if (axis?.maxRate && r > axis.maxRate * (1 + 1e-6) + 0.5) throw new Error(`${at}: axis ${axis.name ?? k} at ${Math.round(r)} steps/s, past the machine's ${axis.maxRate} for it`);
|
|
104
|
+
}
|
|
105
|
+
// the block is over in major / fastest seconds at the soonest
|
|
106
|
+
const least = leastBlockTime(l, { turnaround });
|
|
107
|
+
if (major / fastest < least) throw new Error(`${at}: ${major} steps at up to ${fastest} steps/s can be over in ${(major / fastest * 1000).toFixed(2)} ms, and the streamer needs ${(least * 1000).toFixed(2)} ms for each block's line and answer: it would fall behind and stop between blocks (plan with a least block time, task.blockTime for cad plot, or a lower speed)`);
|
|
108
|
+
peak = Math.max(peak, fastest);
|
|
109
|
+
for (const k of all) position[k] += x[k];
|
|
110
|
+
}
|
|
111
|
+
if (c === 'h') position[x[0]] = 0;
|
|
112
|
+
seen[c]++;
|
|
113
|
+
said.push(`${l} ${c === '?' ? `q ${position.join(' ')} 0` : 'ok'}`);
|
|
114
|
+
}
|
|
115
|
+
return { lines: lines.length, ...seen, peakRate: peak, axisPeaks, position, said };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** What a gait's step file is, for the summary: its cycles, time and start pose (nothing for a drawing). @param {object} file */
|
|
119
|
+
export const gait = (file) => (file?.kind === 'gait' ? `, ${file.cycles} cycle${file.cycles === 1 ? '' : 's'} of a gait, ${Number(file.time).toFixed(1)} s${file.pose ? ` from the pose "${file.pose}" and back` : ''}` : '');
|
|
120
|
+
|
|
121
|
+
async function send(port, lines, say, axes = 3) {
|
|
122
|
+
const r = spawnSync('stty', [process.platform === 'darwin' ? '-f' : '-F', port, '115200', 'raw', '-echo', '-hupcl'], { encoding: 'utf8' });
|
|
123
|
+
if (r.status) throw new Error(`stty ${port}: ${r.stderr}`);
|
|
124
|
+
const rd = fs.createReadStream(port), wr = fs.createWriteStream(port);
|
|
125
|
+
let buffer = '', answer = null;
|
|
126
|
+
let greeting = null;
|
|
127
|
+
rd.on('data', (d) => { buffer += d; let i; while ((i = buffer.indexOf('\n')) >= 0) { const l = buffer.slice(0, i).trim(); buffer = buffer.slice(i + 1); if (answer && /^(ok|error)/.test(l)) { const a = answer; answer = null; a(l); } else if (l) { greeting = /^streamer ready, (\d+) axes$/.exec(l)?.[1] ?? greeting; say(l); } } });
|
|
128
|
+
await new Promise((res) => setTimeout(res, 2500)); // the board resets when the port opens
|
|
129
|
+
// the streamer says how many axes it was built for: lines written for another board would be misread
|
|
130
|
+
if (greeting != null && +greeting !== axes) { rd.destroy(); wr.end(); throw new Error(`the board's streamer has ${greeting} axes, and the lines are written for ${axes}: flash the streamer built for this machine's controller`); }
|
|
131
|
+
for (const [i, l] of lines.entries()) {
|
|
132
|
+
const reply = await new Promise((res) => { answer = res; wr.write(`${l}\n`); });
|
|
133
|
+
if (reply !== 'ok') { wr.write('!\n'); throw new Error(`line ${i + 1} ("${l}"): ${reply}`); }
|
|
134
|
+
if (i % 100 === 0) say(`${i} of ${lines.length}`);
|
|
135
|
+
}
|
|
136
|
+
rd.destroy(); wr.end();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
140
|
+
const args = process.argv.slice(2), opt = (k) => { const i = args.indexOf(`--${k}`); return i < 0 ? undefined : args[i + 1]; }, has = (k) => args.includes(`--${k}`);
|
|
141
|
+
const fileName = args.find((a, i) => !a.startsWith('--') && !['--port', '--machine'].includes(args[i - 1]));
|
|
142
|
+
if (!fileName) { console.error('usage: node send.mjs <file.steps.json> --port <device> [--machine <file>] [--no-home] | --dry-run'); process.exit(2); }
|
|
143
|
+
const file = JSON.parse(fs.readFileSync(fileName, 'utf8')), machine = opt('machine') ? JSON.parse(fs.readFileSync(opt('machine'), 'utf8')) : null;
|
|
144
|
+
// the whole file is checked before anything moves: a block refused halfway through a drawing would spoil it
|
|
145
|
+
let r, lines, st;
|
|
146
|
+
try { st = streamerOf(machine); lines = ['e', ...(machine && !has('no-home') ? homeLines(machine) : []), ...linesOf(file, { ...(machine?.pen ? { pen: machine.pen } : {}), axes: st.axes, ...(machine ? { names: machine.axes.map((a) => a.name) } : {}) }), 'd']; } catch (e) { console.error(`${has('dry-run') ? 'dry run' : 'not sent'}: ${e.message}`); process.exit(1); }
|
|
147
|
+
try { r = dryRun(lines, { machine }); } catch (e) { console.error(`${has('dry-run') ? 'dry run' : 'not sent'}: ${e.message}`); process.exit(1); }
|
|
148
|
+
if (has('dry-run')) {
|
|
149
|
+
if (!has('quiet')) for (const s of r.said) console.log(s);
|
|
150
|
+
console.log(`dry run: ${r.lines} lines, ${r.m} blocks, ${r.p} pen moves, ${r.h} homes, peak ${r.peakRate} steps/s (the streamer on ${st.name === 'uno' ? 'an' : 'a'} ${st.board} takes ${MAX_RATE})${machine ? `, axes at most ${r.axisPeaks.slice(0, machine.axes.length).map((x, k) => `${Math.round(x)} of ${machine.axes[k].maxRate}`).join(', ')} steps/s` : ''}${gait(file)}`);
|
|
151
|
+
process.exit(0);
|
|
152
|
+
}
|
|
153
|
+
if (!opt('port')) { console.error('--port <device>, or --dry-run'); process.exit(2); }
|
|
154
|
+
// a gait has no home: the streamer counts from where the motors stand when it starts, so the leg must be in its pose
|
|
155
|
+
if (file.kind === 'gait') console.log(`a gait${gait(file)}: the streamer counts from where the motors stand now, so the leg must be in ${file.pose ? `its pose "${file.pose}"` : "the cycle's first frame"}`);
|
|
156
|
+
send(opt('port'), lines, console.log, st.axes).then(() => console.log('done')).catch((e) => { console.error(e.message); process.exit(1); });
|
|
157
|
+
}
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"body_half": {"value": 75, "unit": "mm", "rule": "Hip to hip along the body, halved: the side plate, 242 mm long, fits on a 256 mm bed, and the knees point outward so they stay apart", "kind": "default", "source": "EXAMPLES chapter 14", "checked": "2026-11-09"},
|
|
39
39
|
"body_w": {"value": 50, "unit": "mm", "rule": "The body's half-width, to the hips' plates: two hip motors back to back fit inside", "kind": "default", "source": "EXAMPLES chapter 14", "checked": "2026-11-09"},
|
|
40
40
|
"side_t": {"value": 6, "unit": "mm", "rule": "The side plate's thickness", "kind": "default", "source": "EXAMPLES chapter 14", "checked": "2026-11-09"},
|
|
41
|
-
"robot_mass": {"value": 4.2, "unit": "kg", "rule": "The quadruped as drawn: 3.83 kg of prints, eight 17HS4401s, bearings and screws from cad list, and about 0.4 kg for its
|
|
41
|
+
"robot_mass": {"value": 4.2, "unit": "kg", "rule": "The quadruped as drawn: 3.83 kg of prints, eight 17HS4401s, bearings and screws from cad list, and about 0.4 kg for its electronics (a Mega 2560, eight DRV8825s on their breakouts, none weighed), a battery and the wires, an estimate until built", "kind": "estimate", "source": "cad list leg/quadruped (3834 g, the knees 17HS4401s at 280 g each) and a guess at the electronics", "checked": "2026-11-23"},
|
|
42
42
|
"foot_socket": {"value": 12, "unit": "mm", "rule": "How far each rod goes into a foot block", "kind": "default", "source": "EXAMPLES chapter 14", "checked": "2026-11-09"}
|
|
43
43
|
}
|
|
44
44
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-rulecad",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.28",
|
|
4
4
|
"description": "Start a rulecad project: npm create rulecad my-designs. A workspace with a soap tray to start from, ready to check, preview, export and share.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/template/AGENTS.md
CHANGED
|
@@ -256,6 +256,8 @@ variable says which rule it comes from. Follow these steps; they're what makes a
|
|
|
256
256
|
factor, and where the peak stress is.
|
|
257
257
|
- For a part that must not break (a lever, a pedal), give its problem a `"stress"` limit (the material's strength
|
|
258
258
|
over a safety factor) instead of a `"volume"`: the lightest layout under it. Then verify it on finer cells.
|
|
259
|
+
Add `"robust": true` so it holds made a little thin and a little thick too (`cad optimise` prints both copies'
|
|
260
|
+
peaks); a mechanism with `"robust": true` and a `"strain"` limit is optimised under the limit.
|
|
259
261
|
- Mark a problem `"critical": true` if the part could hurt someone if it broke. Say plainly that the analysis is a
|
|
260
262
|
design aid and the material values are data-sheet figures: such a part needs testing, recorded under
|
|
261
263
|
`"verification"`, not just a check.
|