create-rulecad 0.3.28 → 0.4.0

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 CHANGED
@@ -5,13 +5,59 @@ print (a hole's diameter, a seat's depth, a part's outline). Each release lists
5
5
  it makes, with its reason. A **fasten** is an entry in an assembly's `"fasten"` list: one screwed joint, naming the
6
6
  screw by thread and head, the parts it passes through and the part it ends in.
7
7
 
8
+ ## 0.4.0: the template's notes for agents say frame sizing checks what it writes; --machine frame offers only boxes that stand; needs Node 22.13 or later, the version the kit is tested on
9
+
10
+ ### Changed
11
+
12
+ - The template's AGENTS.md (a copy of cad's) now says that `cad frame --size --write` checks the design it would write and writes nothing that fails, naming the checks: fix what they say, or leave out the profile that breaks them. Only the notes change: new workspaces are made as before. No printed size changes.
13
+
14
+ - `--machine frame` refuses, by name, a box that would tip over under a 20 N push at its top (cad's new
15
+ `frame.tip`): its height may be at most twice its narrower side less 120 mm in 2020 (both profiles) and less 50 mm
16
+ in 3030. A 2020 box 50 x 50 x 600 was offered and tipped at about 1 N; a 3030 box 100 x 100 x 300 at 13.5 N. The
17
+ least 2020 box that stands is 85 x 85 x 50. Sizes inside the new bound are made as before.
18
+ - The box's 5 kg load is now shared over the top: 2.5 kg on the middle of the front beam (x3) and 2.5 kg on the back
19
+ beam (x4), in place of all 5 kg on the front beam, over the front feet, where the default 300 x 300 x 350 box tipped
20
+ forward at 8 N. The front beam's sag under its load halves; no printed size moves.
21
+ - The README's table of sizes says what limits each end, as measured, the tipping bound among them.
22
+
23
+ - A new workspace gets `@rulecad/cad` `^0.9.0`, this release's cad (it was `^0.8.0`). Workspaces made before keep
24
+ the cad they have: to take up the new one, set `"@rulecad/cad": "^0.9.0"` in the workspace's package.json and run
25
+ `npm install`.
26
+
27
+ - create-rulecad now states Node 22.13 or later in its `engines`, the same lowest Node as every rulecad package, and the
28
+ tests run on exactly Node 22.13.0 as well as the newest Node 24. Node 20 reached the end of its support on 30 April
29
+ 2026, and the kit's packages stated five different lowest versions, some of them too low: on Node 20.6 to 20.9 `cad`
30
+ stopped at start-up with "Unexpected token 'with'", and on Node 22.0 to 22.12 every `cad` command that runs a design
31
+ stops, because the sandbox designs run in cannot start there. npm gave no warning at install for either.
32
+
33
+ Upgrading: on a Node older than 22.13, npm now warns at install that this package needs Node 22.13; install Node 22.13
34
+ or later (24 recommended). Nothing else changes, and no printed size moves.
35
+
36
+ ## 0.3.29: new workspaces get cad 0.8; the template's notes for agents say board designs run in the sandbox; the drivers stay on until the last move has run
37
+
38
+ ### Changed
39
+
40
+ - A new workspace now depends on `@rulecad/cad` `^0.8.0`, the release with this round's security fixes (before 1.0 a caret covers one minor version only, so `^0.7.0` would have kept new workspaces on cad 0.7). To move an existing workspace, set `"@rulecad/cad": "^0.8.0"` in its package.json and run `npm install`. No printed size changes.
41
+ - The template's AGENTS.md (a copy of cad's) now says that a board design runs in the design sandbox like any other, reaching the board engine only through `v.pcb`, and that a workspace with boards asks for no trust. Only the notes change: new workspaces are made as before. No printed size changes.
42
+
43
+ ### Fixed
44
+
45
+ - The arm and leg templates' streamer (`firmware/arm/arm.ino`, `firmware/leg/leg.ino`) and sender (`send.mjs`) keep the
46
+ motor drivers on until the last move has run. The streamer answers a move as soon as it is queued, and the sender used
47
+ to send `d` (drivers off) straight after the last answer, which the streamer obeyed at once: the last moves ran with
48
+ the motors slack, so a short job never moved, the arm lost the end of its last stroke and the leg dropped instead of
49
+ coming back to its pose. Now the streamer's `d` waits, like `h`, until everything queued has run, and the sender asks
50
+ the board where it is (`?`) until nothing is queued and nothing moves before it sends `d`.
51
+ - Upgrading: copy the new `send.mjs` and firmware into your project and reflash every board already loaded with the
52
+ streamer. A board left on the old firmware is kept safe by the new sender alone. A job's last answer now comes when
53
+ the machine has stopped, so `send.mjs` finishes a few seconds later than before. No printed size moves.
54
+
8
55
  ## 0.3.28: the agents' guide follows cad 0.7.87
9
56
 
10
57
  ### Changed
11
58
 
12
59
  - The template's AGENTS.md follows cad 0.7.87's: `robust: true` on an optimisation problem. No printed size changes.
13
60
 
14
-
15
61
  ## 0.3.27: the leg's streamer and sender, eight axes on a Mega (#199)
16
62
  - The sender refuses a step file whose axes are not the machine's, by name and in order, so a file written for one machine never drives another's motors.
17
63
  - STREAMER.md: set each driver breakout's switches to 1/8 (M0 and M1 on, M2 off) before streaming; they come set to 1/32.
package/README.md CHANGED
@@ -43,24 +43,40 @@ npx cad kit frame/box
43
43
  `--machine frame` makes a box frame of aluminium extrusion in `projects/frame`, asked for by its inside size
44
44
  (`--size`, width x depth x height in mm; default 300x300x350) in one profile (`--profile`). Its
45
45
  beams, joins, feet and end caps are generated from that each time it is built (`"frame": { "kind": "box" }` in
46
- `projects/frame/assemblies/box.json`), with a 5 kg load on its top front beam to change to what it carries. Each
47
- profile offered comes with the join and feet its box checks clean with, on a fresh install, and the sizes it checks
48
- clean in:
46
+ `projects/frame/assemblies/box.json`), with a 5 kg load on its top, half on the middle of the front beam and half on
47
+ the back's, to change to what it carries. Each profile offered comes with the join and feet its box checks clean with,
48
+ on a fresh install, and the sizes it checks clean in:
49
49
 
50
- | `--profile` | Joins | Feet | Width and depth | Height |
51
- |---|---|---|---|---|
52
- | `2020-misumi-hfs5` (the default) | blind: a screw in each butting beam's end, its head in the upright's slot | printed levelling feet | 50 to 1400 mm | 50 to 600 mm |
53
- | `2020-openbuilds` | blind | printed levelling feet | 50 to 1400 mm | 50 to 600 mm |
54
- | `3030-misumi-hfs6` | printed corner brackets on drop-in slot nuts | printed feet | 100 to 800 mm | 100 to 300 mm |
50
+ | `--profile` | Joins | Feet | Width and depth | Height | And stands up to |
51
+ |---|---|---|---|---|---|
52
+ | `2020-misumi-hfs5` (the default) | blind: a screw in each butting beam's end, its head in the upright's slot | printed levelling feet | 50 to 1400 mm | 50 to 600 mm | twice the narrower side less 120 mm |
53
+ | `2020-openbuilds` | blind | printed levelling feet | 50 to 1400 mm | 50 to 600 mm | twice the narrower side less 120 mm |
54
+ | `3030-misumi-hfs6` | printed corner brackets on drop-in slot nuts | printed feet | 100 to 800 mm | 100 to 300 mm | twice the narrower side less 50 mm |
55
55
 
56
- The largest sizes are where its checks stop passing: wider, the top front beam sags past its width over 360 under
57
- the 5 kg load; taller, a 20 N push at the top sways it past its height over 400 (the printed brackets of the 3030 box
58
- give more than the blind joins of the 2020 ones, so it is clean only up to 300 mm tall). Under 100 mm the 3030
59
- brackets crowd each other. Inside the ranges, a size whose beams' cut lengths lie under 1 mm apart (and are not one
60
- length) is refused too: two cuts at ±0.5 mm cannot hold them apart. A 2020 box's uprights are its height and 58.5 mm
56
+ What limits each end, as measured by `cad check`:
57
+
58
+ - **Too narrow for its height, it tips over.** A box stands free on its four feet, and a 20 N push at its top (a hand
59
+ steadying it) tips it over two of them once the push's turn passes its weight's (`frame.tip`). So its height may be
60
+ at most twice its narrower side less the figure in the last column: a 300 x 300 box of 2020 up to 480 mm, a 2020
61
+ box 100 mm wide up to 80 mm. At the bound a 2020 box 200 x 200 x 280 tips at 21 N; a 50 x 50 x 600 box tips
62
+ at 1 N empty, and a 3030 box 100 x 100 x 300 at 13.5 N with its load. The narrowest 2020 box is 85 mm a side, which
63
+ stands only at the least height, 50 mm. The 5 kg sits over the middle of the top for this: on the front beam alone,
64
+ a 300 x 300 x 350 box tips forward at 8 N. Move it where your box carries its load, and `cad check` says whether it
65
+ still stands.
66
+ - **Taller, it sways.** A 20 N push at the top sways it past its height over 400 (`frame.rack`): the most offered,
67
+ 2020 at 1400 x 1400 x 600, sways 1.33 mm against 1.62, and 3030 at 800 x 800 x 300 sways 0.81 mm against 0.86 (the
68
+ printed brackets of the 3030 box give more than the blind joins of the 2020 ones: at 600 x 600 x 350 it sways 1.04 mm
69
+ against 0.99). A 2020 box 1400 x 1400 x 700 still sways within its limit (1.82 mm against 1.87), so 600 mm is the
70
+ most offered rather than where its checks stop.
71
+ - **Wider, its top beams sag.** A top beam may sag by its width over 360 under its load (`frame.deflection`): at
72
+ 1400 mm, with its 2.5 kg, it is well within that. Wider boxes are not offered, as they have not been checked with the
73
+ load shared this way (with all 5 kg on the front beam, a 2020 box 1600 mm wide sagged 4.83 mm against 4.44 and failed).
74
+ - **Smaller, the fittings crowd.** Under 100 mm the 3030 brackets crowd each other.
75
+
76
+ Inside the ranges, a size whose beams' cut lengths lie under 1 mm apart (and are not one length) is refused too: two cuts at ±0.5 mm cannot hold them apart. A 2020 box's uprights are its height and 58.5 mm
61
77
  (two widths and the 18.5 mm its bottom ring rises over the feet's taps), a 3030 box's its height and 60 mm, so 358 x
62
- 300 x 300 in 2020 (358 mm beams, 358.5 mm uprights) is refused, and 357.5 x 300 x 300 is made. Another profile, or a
63
- size outside these, is refused by name, before anything is written:
78
+ 300 x 300 in 2020 (358 mm beams, 358.5 mm uprights) is refused, and 357.5 x 300 x 300 is made. Another profile, a
79
+ size outside these, or one that would tip over, is refused by name, before anything is written:
64
80
  make the box in range and change its `"inside"`, `"profile"`, `"join"` or `"feet"` by hand, and `cad check` says
65
81
  what that needs. `npx cad kit frame/box` writes the
66
82
  folder to build it from without the model: the build page, the shopping list, the plates to print, the jigs and each
@@ -0,0 +1,106 @@
1
+ // The sizes `npm create rulecad --machine frame` makes a box in: each profile with the join and feet its box checks
2
+ // clean with on a fresh install, the inside sizes it checks clean in, and what refuses a size outside them. index.mjs
3
+ // reads it, and test/sizes-stand.test.mjs checks every corner of the sizes offered against frame.tip.
4
+ //
5
+ // A box is asked for by its inside width, depth and height. Each profile offers width and depth (sides) and height
6
+ // from its least to its most, and one bound more: the box must stand. It stands on four feet under its uprights, and
7
+ // a side push at its top (frame.push, 20 N: a hand steadying it) tips it over two of them where the push's moment
8
+ // passes its weight's (frame.tip): the narrower the box and the taller, the less tips it. So the height may be at most
9
+ // twice the narrower side, less `stand` mm. Found by the frame solve with the box's 5 kg load (2.5 kg on the middle of
10
+ // each of the top's front and back beams), each push solved: a 2020 box 200 x 200 x 280 tips at 21.4 N, 300 x 300 x 480
11
+ // at 21.7, 100 x 100 x 80 at 26.2; a 3030 box on printed brackets 100 x 100 x 150 at 22.2, 175 x 175 x 300 at 22.9. Just
12
+ // over the bound, 2020 at 200 x 200 x 303 tips at 20.1 N and 3030 at 100 x 100 x 174 at 20.0.
13
+ //
14
+ // A box only gets worse elsewhere as a side grows (the top front beam sags with the width, and the push racks it more
15
+ // as it gets taller), so the largest sizes offered are the largest checked clean, by the create-rulecad test: 2020 at
16
+ // 1400 x 1400 x 600 sways 1.33 mm against 1.62 (its height, 648.5 mm, over 400), 3030 at 800 x 800 x 300 sways 0.81
17
+ // against 0.86. The least are set by the fittings (a 3030 box under 100 mm crowds its brackets) and by standing.
18
+ // rise: how much longer an upright is than the inside height (two profile widths, and with blind joins the 18.5 mm
19
+ // the bottom ring rises to clear the feet's tapped ends); its cut length beside the width's and the depth's must be one
20
+ // length or 1 mm apart or more (two cuts at the profile's ±0.5 mm, cad check's frame.cut)
21
+
22
+ /** Each profile a box is made in: its join, feet, the sides and height it takes (mm), the stand bound and the rise. */
23
+ export const FRAME_PROFILES = {
24
+ '2020-misumi-hfs5': {
25
+ join: 'blind',
26
+ feet: 'levelling',
27
+ sides: [50, 1400],
28
+ height: [50, 600],
29
+ stand: 120,
30
+ rise: 58.5,
31
+ why: "blind joins (a screw in each end, its head in the other beam's slot), printed levelling feet",
32
+ },
33
+ '2020-openbuilds': {
34
+ join: 'blind',
35
+ feet: 'levelling',
36
+ sides: [50, 1400],
37
+ height: [50, 600],
38
+ stand: 120,
39
+ rise: 58.5,
40
+ why: 'blind joins, printed levelling feet',
41
+ },
42
+ '3030-misumi-hfs6': {
43
+ join: { kind: 'bracket', fitting: 'printed' },
44
+ feet: 'foot',
45
+ sides: [100, 800],
46
+ height: [100, 300],
47
+ stand: 50,
48
+ rise: 60,
49
+ why: 'printed corner brackets on drop-in nuts, printed feet',
50
+ },
51
+ };
52
+ export const CUT_APART = 1; // mm: two cuts at ±0.5 mm (the profiles' cut_tolerance, MISUMI's "L Dimension Tolerance ±0.5mm")
53
+
54
+ /** The tallest inside height a box of this profile stands at, for its narrower side. @param {{ stand: number }} p @param {number} side mm */
55
+ export const tallest = (p, side) => 2 * side - p.stand;
56
+
57
+ /**
58
+ * Why a box of this inside size is not made in this profile, in words, or null where it is. @param {number[]} inside
59
+ * width, depth and height in mm @param {string} profile @param {string} size as asked, for the message
60
+ * @returns {string | null}
61
+ */
62
+ export function refusal([w, d, h], profile, size = `${w}x${d}x${h}`) {
63
+ const p = FRAME_PROFILES[profile];
64
+ if (!p)
65
+ return `--profile is ${Object.keys(FRAME_PROFILES).join(', ')}: the profiles this box checks clean in (got "${profile}"; for another, make the box and change its "profile", "join" and "feet" by hand)`;
66
+ const within = ([lo, hi], x) => x >= lo && x <= hi;
67
+ if (!within(p.sides, w) || !within(p.sides, d) || !within(p.height, h))
68
+ return `--size in ${profile} is width and depth ${p.sides.join(' to ')} mm, height ${p.height.join(' to ')} mm, and the height at most twice the narrower side less ${p.stand} mm: the sizes its box checks clean in (got "${size}"; for another size, make one in range and change its "inside" by hand: cad check says what it needs)`;
69
+ const narrow = Math.min(w, d);
70
+ if (h > tallest(p, narrow) + 1e-9)
71
+ return `--size ${size} in ${profile} would tip over: ${h} mm tall on a ${narrow} mm side, a 20 N push at its top tips it over its feet (cad check fails frame.tip). Its height may be at most twice the narrower side less ${p.stand} mm, ${tallest(p, narrow) >= p.height[0] ? `here ${tallest(p, narrow)} mm` : `so no height offered stands on a ${narrow} mm side`}; or make the narrower side at least ${(h + p.stand) / 2} mm`;
72
+ // the beams' cut lengths: the width's and the depth's beams are the inside, the uprights the height and the rise
73
+ const cuts = [
74
+ ['width', w],
75
+ ['depth', d],
76
+ ['upright', +(h + p.rise).toFixed(3)],
77
+ ];
78
+ for (const [i, [n1, a]] of cuts.entries())
79
+ for (const [n2, b] of cuts.slice(i + 1)) {
80
+ const gap = Math.abs(a - b);
81
+ if (gap > 1e-6 && gap < CUT_APART - 1e-9)
82
+ return `--size ${size} in ${profile} cuts the ${n1}'s beams at ${a} mm and the ${n2}'s at ${b} mm, ${+gap.toFixed(3)} mm apart: two cuts at ±0.5 mm cannot hold them apart (cad check warns frame.cut). Make them one length or ${CUT_APART} mm apart or more${n2 === 'upright' ? ` (the uprights are the height and ${p.rise} mm)` : ''}`;
83
+ }
84
+ return null;
85
+ }
86
+
87
+ /**
88
+ * The corners of the sizes a profile offers, each [width, depth, height]: the least and the largest box, and along
89
+ * the standing bound the tallest at the least side that stands at the least height and at the most height, each
90
+ * square and with one side the largest. @param {string} profile @returns {number[][]}
91
+ */
92
+ export function corners(profile) {
93
+ const p = FRAME_PROFILES[profile],
94
+ [slo, shi] = p.sides,
95
+ [hlo, hhi] = p.height;
96
+ const least = Math.max(slo, (hlo + p.stand) / 2), // the narrowest side that stands at the least height
97
+ atTop = Math.max(slo, (hhi + p.stand) / 2), // and at the most
98
+ tall = (s) => Math.min(hhi, tallest(p, s));
99
+ return [
100
+ [least, least, hlo],
101
+ [least, least, tall(least)],
102
+ [least, shi, tall(least)],
103
+ [atTop, atTop, hhi],
104
+ [shi, shi, hhi],
105
+ ];
106
+ }
package/index.mjs CHANGED
@@ -16,49 +16,59 @@ import path from 'node:path';
16
16
  import { execSync, execFileSync } from 'node:child_process';
17
17
  import readline from 'node:readline/promises';
18
18
  import { fileURLToPath } from 'node:url';
19
+ import { FRAME_PROFILES, refusal } from './frame-sizes.mjs';
19
20
 
20
- const args = process.argv.slice(2), install = !args.includes('--no-install');
21
+ const args = process.argv.slice(2),
22
+ install = !args.includes('--no-install');
21
23
  const VALUED = new Set(['--share', '--machine', '--sheet', '--accuracy', '--robot', '--size', '--profile']);
22
- const optionValue = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] ?? '' : null);
24
+ const optionValue = (name) => (args.includes(name) ? (args[args.indexOf(name) + 1] ?? '') : null);
23
25
  // The folder is the argument that isn't an option, or an option's value
24
- const dir = path.resolve(args.find((a, i) => !a.startsWith('--') && !VALUED.has(args[i - 1])) || 'my-designs'), name = path.basename(dir);
25
- const machine = optionValue('--machine'), MACHINES = ['arm', 'leg', 'frame'];
26
- if (machine !== null && !MACHINES.includes(machine)) { console.error(`--machine is ${MACHINES.slice(0, -1).join(', ')} or ${MACHINES.at(-1)} (got "${machine}")`); process.exit(1); }
27
- for (const [flag, only] of [['--size', 'frame'], ['--profile', 'frame'], ['--sheet', 'arm'], ['--accuracy', 'arm'], ['--robot', 'leg']]) if (optionValue(flag) !== null && machine !== only) { console.error(`${flag} is for --machine ${only}`); process.exit(1); }
28
- // The profiles a generated box is made in, each with the join and feet its box checks clean with on a fresh install,
29
- // and the inside sizes it checks clean in: width and depth (sides) and height, each from its least to its most, in mm.
30
- // A box grows worse as any side grows (the top front beam sags with the width, and a side push at the top racks it
31
- // more as it gets taller and wider), so the box is clean wherever its largest corner is; the smallest is set by the
32
- // fittings (a 3030 box under 100 mm crowds its brackets). The create-rulecad test checks both corners of every one.
33
- // Found by cad check: 2020 boxes 1400 x 1400 x 700 sway 1.82 mm against 1.87 (blind joins), the top beam at 1600 wide
34
- // sags 4.38 mm against 4.44; a 3030 box on printed brackets 600 x 600 x 350 sways 1.04 mm against 0.99, 800 x 800 x 300
35
- // 0.81 against 0.86. Another profile, or a size outside these, is the frame's to make by hand: cad check says what it needs.
36
- // rise: how much longer an upright is than the inside height (two profile widths, and with blind joins the 18.5 mm
37
- // the bottom ring rises to clear the feet's tapped ends); its cut length beside the width's and the depth's must be one
38
- // length or 1 mm apart or more (two cuts at the profile's ±0.5 mm, cad check's frame.cut)
39
- const FRAME_PROFILES = {
40
- '2020-misumi-hfs5': { join: 'blind', feet: 'levelling', sides: [50, 1400], height: [50, 600], rise: 58.5, why: 'blind joins (a screw in each end, its head in the other beam\'s slot), printed levelling feet' },
41
- '2020-openbuilds': { join: 'blind', feet: 'levelling', sides: [50, 1400], height: [50, 600], rise: 58.5, why: 'blind joins, printed levelling feet' },
42
- '3030-misumi-hfs6': { join: { kind: 'bracket', fitting: 'printed' }, feet: 'foot', sides: [100, 800], height: [100, 300], rise: 60, why: 'printed corner brackets on drop-in nuts, printed feet' },
43
- };
44
- const CUT_APART = 1; // mm: two cuts at ±0.5 mm (the profiles' cut_tolerance, MISUMI's "L Dimension Tolerance ±0.5mm")
45
- // --machine frame's size and profile, refused by name before anything is written
46
- const frameAsk = machine === 'frame' ? (() => {
47
- const size = optionValue('--size') ?? '300x300x350', profile = optionValue('--profile') ?? '2020-misumi-hfs5', p = FRAME_PROFILES[profile];
48
- const inside = /^\d+(\.\d+)?x\d+(\.\d+)?x\d+(\.\d+)?$/i.test(size) ? size.toLowerCase().split('x').map(Number) : null;
49
- if (!inside) { console.error(`--size is the inside width x depth x height in mm, as 300x300x350 (got "${size}")`); process.exit(1); }
50
- if (!p) { console.error(`--profile is ${Object.keys(FRAME_PROFILES).join(', ')}: the profiles this box checks clean in (got "${profile}"; for another, make the box and change its "profile", "join" and "feet" by hand)`); process.exit(1); }
51
- const [w, d, h] = inside, within = ([lo, hi], x) => x >= lo && x <= hi;
52
- if (!within(p.sides, w) || !within(p.sides, d) || !within(p.height, h)) { console.error(`--size in ${profile} is width and depth ${p.sides.join(' to ')} mm, height ${p.height.join(' to ')} mm: the sizes its box checks clean in (got "${size}"; for another size, make one in range and change its "inside" by hand: cad check says what it needs)`); process.exit(1); }
53
- // the beams' cut lengths: the width's and the depth's beams are the inside, the uprights the height and the rise
54
- const cuts = [['width', w], ['depth', d], ['upright', +(h + p.rise).toFixed(3)]];
55
- for (const [i, [n1, a]] of cuts.entries()) for (const [n2, b] of cuts.slice(i + 1)) {
56
- const gap = Math.abs(a - b);
57
- if (gap > 1e-6 && gap < CUT_APART - 1e-9) { console.error(`--size ${size} in ${profile} cuts the ${n1}'s beams at ${a} mm and the ${n2}'s at ${b} mm, ${+gap.toFixed(3)} mm apart: two cuts at ±0.5 mm cannot hold them apart (cad check warns frame.cut). Make them one length or ${CUT_APART} mm apart or more${n2 === 'upright' ? ` (the uprights are the height and ${p.rise} mm)` : ''}`); process.exit(1); }
26
+ const dir = path.resolve(args.find((a, i) => !a.startsWith('--') && !VALUED.has(args[i - 1])) || 'my-designs'),
27
+ name = path.basename(dir);
28
+ const machine = optionValue('--machine'),
29
+ MACHINES = ['arm', 'leg', 'frame'];
30
+ if (machine !== null && !MACHINES.includes(machine)) {
31
+ console.error(`--machine is ${MACHINES.slice(0, -1).join(', ')} or ${MACHINES.at(-1)} (got "${machine}")`);
32
+ process.exit(1);
33
+ }
34
+ for (const [flag, only] of [
35
+ ['--size', 'frame'],
36
+ ['--profile', 'frame'],
37
+ ['--sheet', 'arm'],
38
+ ['--accuracy', 'arm'],
39
+ ['--robot', 'leg'],
40
+ ])
41
+ if (optionValue(flag) !== null && machine !== only) {
42
+ console.error(`${flag} is for --machine ${only}`);
43
+ process.exit(1);
58
44
  }
59
- return { inside, profile, ...p };
60
- })() : null;
61
- if (fs.existsSync(dir) && fs.readdirSync(dir).length) { console.error(`${dir} isn't empty: name a new folder (npm create rulecad my-designs)`); process.exit(1); }
45
+ // The profiles a generated box is made in, the sizes each takes and why others are refused: frame-sizes.mjs
46
+ // --machine frame's size and profile, refused by name before anything is written
47
+ const frameAsk =
48
+ machine === 'frame'
49
+ ? (() => {
50
+ const size = optionValue('--size') ?? '300x300x350',
51
+ profile = optionValue('--profile') ?? '2020-misumi-hfs5',
52
+ p = FRAME_PROFILES[profile];
53
+ const inside = /^\d+(\.\d+)?x\d+(\.\d+)?x\d+(\.\d+)?$/i.test(size)
54
+ ? size.toLowerCase().split('x').map(Number)
55
+ : null;
56
+ if (!inside) {
57
+ console.error(`--size is the inside width x depth x height in mm, as 300x300x350 (got "${size}")`);
58
+ process.exit(1);
59
+ }
60
+ const why = refusal(inside, profile, size);
61
+ if (why) {
62
+ console.error(why);
63
+ process.exit(1);
64
+ }
65
+ return { inside, profile, ...p };
66
+ })()
67
+ : null;
68
+ if (fs.existsSync(dir) && fs.readdirSync(dir).length) {
69
+ console.error(`${dir} isn't empty: name a new folder (npm create rulecad my-designs)`);
70
+ process.exit(1);
71
+ }
62
72
 
63
73
  const TEMPLATE = fileURLToPath(new URL('./template/', import.meta.url));
64
74
  fs.cpSync(TEMPLATE, dir, { recursive: true });
@@ -66,93 +76,183 @@ fs.renameSync(path.join(dir, 'gitignore'), path.join(dir, '.gitignore')); // npm
66
76
  const readme = path.join(dir, 'README.md');
67
77
  fs.writeFileSync(readme, fs.readFileSync(readme, 'utf8').replaceAll('NAME', name));
68
78
  // The cad command a new workspace gets. Before 1.0 a caret covers one minor version only, so this follows
69
- // @rulecad/cad's minor (the test fails when it falls behind, and a new workspace would get an old cad).
70
- const CAD = '^0.7.0';
79
+ // @rulecad/cad's minor (test/create-rulecad-cad.test.mjs fails when it falls behind, and a new workspace would get an old cad).
80
+ const CAD = '^0.9.0';
71
81
  // $RULECAD_LOCAL: a rulecad checkout to use instead of npm (to try unpublished changes)
72
- const from = (pkg) => (process.env.RULECAD_LOCAL ? `file:${path.join(path.resolve(process.env.RULECAD_LOCAL), 'packages', pkg)}` : CAD);
73
- fs.writeFileSync(path.join(dir, 'package.json'), `${JSON.stringify({
74
- name: name.toLowerCase().replace(/[^a-z0-9._~-]+/g, '-').replace(/^[._-]+|-+$/g, '') || 'my-designs', // a name npm takes, whatever the folder is called
75
- private: true, type: 'module',
76
- scripts: { check: 'cad check home/soap-tray' },
77
- dependencies: { '@rulecad/cad': from('cad'), '@jscad/modeling': '^2.12.0' },
78
- }, null, 2)}\n`);
82
+ const from = (pkg) =>
83
+ process.env.RULECAD_LOCAL ? `file:${path.join(path.resolve(process.env.RULECAD_LOCAL), 'packages', pkg)}` : CAD;
84
+ fs.writeFileSync(
85
+ path.join(dir, 'package.json'),
86
+ `${JSON.stringify(
87
+ {
88
+ name:
89
+ name
90
+ .toLowerCase()
91
+ .replace(/[^a-z0-9._~-]+/g, '-')
92
+ .replace(/^[._-]+|-+$/g, '') || 'my-designs', // a name npm takes, whatever the folder is called
93
+ private: true,
94
+ type: 'module',
95
+ scripts: { check: 'cad check home/soap-tray' },
96
+ dependencies: { '@rulecad/cad': from('cad'), '@jscad/modeling': '^2.12.0' },
97
+ },
98
+ null,
99
+ 2,
100
+ )}\n`,
101
+ );
79
102
 
80
- console.log(`made ${path.relative(process.cwd(), dir) || '.'}: a soap tray and a box with a screwed lid to start from, in projects/home`);
103
+ console.log(
104
+ `made ${path.relative(process.cwd(), dir) || '.'}: a soap tray and a box with a screwed lid to start from, in projects/home`,
105
+ );
81
106
 
82
107
  // A machine: copy it in, and size it to what was asked
83
108
  const SHEETS = { a6: [148, 105], a5: [210, 148], a4: [297, 210] };
84
109
  function frameSized() {
85
110
  const { inside, profile, join, feet, why } = frameAsk;
86
111
  fs.cpSync(fileURLToPath(new URL('./machines/frame/', import.meta.url)), dir, { recursive: true });
87
- const file = path.join(dir, 'projects/frame/assemblies/box.json'), a = JSON.parse(fs.readFileSync(file, 'utf8'));
88
- a.title = `Box frame ${inside.join(' x ')}`; Object.assign(a.frame, { inside, profile, join, feet });
112
+ const file = path.join(dir, 'projects/frame/assemblies/box.json'),
113
+ a = JSON.parse(fs.readFileSync(file, 'utf8'));
114
+ a.title = `Box frame ${inside.join(' x ')}`;
115
+ Object.assign(a.frame, { inside, profile, join, feet });
89
116
  fs.writeFileSync(file, `${JSON.stringify(a, null, 2)}\n`);
90
- console.log(` a box frame round ${inside.join(' x ')} mm inside, in ${profile}: ${why}: projects/frame/assemblies/box.json`);
117
+ console.log(
118
+ ` a box frame round ${inside.join(' x ')} mm inside, in ${profile}: ${why}: projects/frame/assemblies/box.json`,
119
+ );
91
120
  }
92
121
  async function sized() {
93
122
  if (machine === 'frame') return frameSized();
94
- const arm = machine === 'arm', o = { sheet: optionValue('--sheet'), accuracy: optionValue('--accuracy'), robot: optionValue('--robot') };
95
- const asking = process.stdin.isTTY && process.stdout.isTTY && o.sheet === null && o.accuracy === null && o.robot === null;
123
+ const arm = machine === 'arm',
124
+ o = { sheet: optionValue('--sheet'), accuracy: optionValue('--accuracy'), robot: optionValue('--robot') };
125
+ const asking =
126
+ process.stdin.isTTY && process.stdout.isTTY && o.sheet === null && o.accuracy === null && o.robot === null;
96
127
  if (asking) {
97
128
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
98
- if (arm) { o.sheet = (await rl.question('Sheet to draw on (a6, a5, a4) [a5]: ')).trim() || null; o.accuracy = (await rl.question('Accuracy at the pen, in mm [0.3]: ')).trim() || null; } else o.robot = (await rl.question('Robot this leg is for, in kg [1.5]: ')).trim() || null;
129
+ if (arm) {
130
+ o.sheet = (await rl.question('Sheet to draw on (a6, a5, a4) [a5]: ')).trim() || null;
131
+ o.accuracy = (await rl.question('Accuracy at the pen, in mm [0.3]: ')).trim() || null;
132
+ } else o.robot = (await rl.question('Robot this leg is for, in kg [1.5]: ')).trim() || null;
99
133
  rl.close();
100
134
  }
101
- const sheet = (o.sheet || 'a5').toLowerCase(), accuracy = o.accuracy == null ? 0.3 : Number(o.accuracy), robot = o.robot == null ? 1.5 : Number(o.robot);
135
+ const sheet = (o.sheet || 'a5').toLowerCase(),
136
+ accuracy = o.accuracy == null ? 0.3 : Number(o.accuracy),
137
+ robot = o.robot == null ? 1.5 : Number(o.robot);
102
138
  fs.cpSync(fileURLToPath(new URL(`./machines/${machine}/`, import.meta.url)), dir, { recursive: true });
103
139
  if (machine === 'leg') {
104
- if (!(robot > 0)) { console.error(`--robot is a mass in kg (got "${o.robot}")`); process.exit(1); }
105
- const file = path.join(dir, 'rules/leg.json'), rules = JSON.parse(fs.readFileSync(file, 'utf8'));
140
+ if (!(robot > 0)) {
141
+ console.error(`--robot is a mass in kg (got "${o.robot}")`);
142
+ process.exit(1);
143
+ }
144
+ const file = path.join(dir, 'rules/leg.json'),
145
+ rules = JSON.parse(fs.readFileSync(file, 'utf8'));
106
146
  rules.rules.robot = { ...rules.rules.robot, value: robot };
107
147
  fs.writeFileSync(file, `${JSON.stringify(rules, null, 2)}\n`);
108
148
  // The stand steps under the robot's share, or under what rides its rods (the leg and its carriage) if that is more
109
- const riding = rules.rules.riding.value, load = Math.max(robot / 2, riding);
110
- return console.log(` a leg on its stand, for a ${robot} kg robot; its share of the weight is ${robot / 2} kg, and the stand steps under ${load} kg${load > robot / 2 ? ', what the leg and its carriage weigh' : ''}: rules/leg.json`);
149
+ const riding = rules.rules.riding.value,
150
+ load = Math.max(robot / 2, riding);
151
+ return console.log(
152
+ ` a leg on its stand, for a ${robot} kg robot; its share of the weight is ${robot / 2} kg, and the stand steps under ${load} kg${load > robot / 2 ? ', what the leg and its carriage weigh' : ''}: rules/leg.json`,
153
+ );
154
+ }
155
+ if (!SHEETS[sheet]) {
156
+ console.error(
157
+ `--sheet is ${Object.keys(SHEETS).join(', ')} (got "${o.sheet}"; a larger sheet's links wouldn't fit a 256 mm bed)`,
158
+ );
159
+ process.exit(1);
111
160
  }
112
- if (!SHEETS[sheet]) { console.error(`--sheet is ${Object.keys(SHEETS).join(', ')} (got "${o.sheet}"; a larger sheet's links wouldn't fit a 256 mm bed)`); process.exit(1); }
113
- if (!(accuracy > 0)) { console.error(`--accuracy is above 0 mm (got "${o.accuracy}")`); process.exit(1); }
114
- const [w, h] = SHEETS[sheet], near = 70;
161
+ if (!(accuracy > 0)) {
162
+ console.error(`--accuracy is above 0 mm (got "${o.accuracy}")`);
163
+ process.exit(1);
164
+ }
165
+ const [w, h] = SHEETS[sheet],
166
+ near = 70;
115
167
  // Reach from the sheet: the far corner at 88% of the links' stretch, the shortest forearm that folds to the near edge (EXAMPLES chapter 12)
116
- const far = Math.hypot(near + h, w / 2), reach = Math.round(far / 0.88);
117
- let fore = 60; for (; fore < reach; fore += 5) { const upper = reach - fore; if (Math.sqrt(upper ** 2 + fore ** 2 - 2 * upper * fore * Math.cos((20 * Math.PI) / 180)) <= near) break; }
168
+ const far = Math.hypot(near + h, w / 2),
169
+ reach = Math.round(far / 0.88);
170
+ let fore = 60;
171
+ for (; fore < reach; fore += 5) {
172
+ const upper = reach - fore;
173
+ if (Math.sqrt(upper ** 2 + fore ** 2 - 2 * upper * fore * Math.cos((20 * Math.PI) / 180)) <= near) break;
174
+ }
118
175
  const upper = reach - fore;
119
- const rulesFile = path.join(dir, 'rules/arm.json'), set = JSON.parse(fs.readFileSync(rulesFile, 'utf8')), label = sheet.toUpperCase();
176
+ const rulesFile = path.join(dir, 'rules/arm.json'),
177
+ set = JSON.parse(fs.readFileSync(rulesFile, 'utf8')),
178
+ label = sheet.toUpperCase();
120
179
  Object.assign(set.rules.sheet_w, { value: w, rule: `A ${label} sheet's long side, across the arm's front` });
121
180
  Object.assign(set.rules.sheet_h, { value: h, rule: `A ${label} sheet's short side, away from the arm` });
122
- Object.assign(set.rules.upper, { value: upper }); Object.assign(set.rules.fore, { value: fore });
181
+ Object.assign(set.rules.upper, { value: upper });
182
+ Object.assign(set.rules.fore, { value: fore });
123
183
  fs.writeFileSync(rulesFile, `${JSON.stringify(set, null, 2)}\n`);
124
184
  const file = path.join(dir, 'projects/arm/assemblies/arm.json');
125
- fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('"size": "a5"', `"size": "${sheet}"`).replace('"accuracy": 0.3', `"accuracy": ${accuracy}`));
185
+ fs.writeFileSync(
186
+ file,
187
+ fs
188
+ .readFileSync(file, 'utf8')
189
+ .replace('"size": "a5"', `"size": "${sheet}"`)
190
+ .replace('"accuracy": 0.3', `"accuracy": ${accuracy}`),
191
+ );
126
192
  // A test drawing that fits the sheet: a square, and a circle in it
127
- const side = Math.round(Math.min(w, h) * 0.675), svg = path.join(dir, 'projects/arm/drawings/test.svg');
128
- fs.writeFileSync(svg, `<svg xmlns="http://www.w3.org/2000/svg" width="${w}mm" height="${h}mm" viewBox="0 0 ${w} ${h}"><rect id="square" x="${(w - side) / 2}" y="${(h - side) / 2}" width="${side}" height="${side}" fill="none"/><circle id="circle" cx="${w / 2}" cy="${h / 2}" r="${Math.round(side * 0.35)}" fill="none"/></svg>\n`);
129
- console.log(` an arm for a landscape ${label} sheet at ${accuracy} mm: upper arm ${upper} mm, forearm ${fore} mm: rules/arm.json`);
193
+ const side = Math.round(Math.min(w, h) * 0.675),
194
+ svg = path.join(dir, 'projects/arm/drawings/test.svg');
195
+ fs.writeFileSync(
196
+ svg,
197
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${w}mm" height="${h}mm" viewBox="0 0 ${w} ${h}"><rect id="square" x="${(w - side) / 2}" y="${(h - side) / 2}" width="${side}" height="${side}" fill="none"/><circle id="circle" cx="${w / 2}" cy="${h / 2}" r="${Math.round(side * 0.35)}" fill="none"/></svg>\n`,
198
+ );
199
+ console.log(
200
+ ` an arm for a landscape ${label} sheet at ${accuracy} mm: upper arm ${upper} mm, forearm ${fore} mm: rules/arm.json`,
201
+ );
130
202
  }
131
203
  if (machine) {
132
204
  await sized();
133
- fs.appendFileSync(readme, machine === 'frame'
134
- ? '\n## The frame\n\nA box frame of aluminium extrusion in `projects/frame`, made by `--machine frame`. Its assembly, `projects/frame/assemblies/box.json`, asks for it by its inside size (`"frame": { "kind": "box", "inside": [...] }`): the beams, joins, feet and end caps are generated from that when it is built, and a load on its top says what it carries. `npx cad check frame/box` checks it (the joins, the screws, the feet, the cut list, its sag, stress, buckling, racking and lowest mode); `npx cad frame frame/box` says what it expands into; `npx cad kit frame/box` writes the folder to build it from (the plates to print, the cut list and each beam\'s sheet, the screws and bought parts, the build steps).\n'
135
- : `\n## The machine\n\nA ${machine === 'arm' ? 'two-link arm that draws' : 'leg on a test stand'}, in \`projects/${machine}\`, made by \`--machine ${machine}\`: its task, bought parts, wires and firmware are in the assembly (EXAMPLES chapters 12 and 14 explain every part). \`npx cad check ${machine === 'arm' ? 'arm/arm' : 'leg/stand'}\` first.\n`);
205
+ fs.appendFileSync(
206
+ readme,
207
+ machine === 'frame'
208
+ ? '\n## The frame\n\nA box frame of aluminium extrusion in `projects/frame`, made by `--machine frame`. Its assembly, `projects/frame/assemblies/box.json`, asks for it by its inside size (`"frame": { "kind": "box", "inside": [...] }`): the beams, joins, feet and end caps are generated from that when it is built, and a load on its top says what it carries. `npx cad check frame/box` checks it (the joins, the screws, the feet, the cut list, its sag, stress, buckling, racking and lowest mode); `npx cad frame frame/box` says what it expands into; `npx cad kit frame/box` writes the folder to build it from (the plates to print, the cut list and each beam\'s sheet, the screws and bought parts, the build steps).\n'
209
+ : `\n## The machine\n\nA ${machine === 'arm' ? 'two-link arm that draws' : 'leg on a test stand'}, in \`projects/${machine}\`, made by \`--machine ${machine}\`: its task, bought parts, wires and firmware are in the assembly (EXAMPLES chapters 12 and 14 explain every part). \`npx cad check ${machine === 'arm' ? 'arm/arm' : 'leg/stand'}\` first.\n`,
210
+ );
136
211
  }
137
212
 
138
213
  // How models are shared: short links need somewhere to keep the model (a secret Gist); long links carry it
139
214
  let share = args.includes('--share') ? args[args.indexOf('--share') + 1] || '' : null;
140
- if (share !== null && !['gist', 'long'].includes(share)) { console.error(`--share is gist or long (got "${share}")`); process.exit(1); }
215
+ if (share !== null && !['gist', 'long'].includes(share)) {
216
+ console.error(`--share is gist or long (got "${share}")`);
217
+ process.exit(1);
218
+ }
141
219
  if (!share && process.stdin.isTTY && process.stdout.isTTY) {
142
220
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
143
- const a = await rl.question('\nModel links: short ones are easy to paste into chat, but each model you share is stored in a secret\nGitHub Gist (needs the gh command, signed in). Long ones carry the model and upload nothing. Short links? [y/N] ');
221
+ const a = await rl.question(
222
+ '\nModel links: short ones are easy to paste into chat, but each model you share is stored in a secret\nGitHub Gist (needs the gh command, signed in). Long ones carry the model and upload nothing. Short links? [y/N] ',
223
+ );
144
224
  rl.close();
145
225
  share = /^y/i.test(a.trim()) ? 'gist' : 'long';
146
226
  }
147
227
  if (share === 'gist') {
148
- const cfg = path.join(dir, 'cad.config.json'), c = JSON.parse(fs.readFileSync(cfg, 'utf8'));
228
+ const cfg = path.join(dir, 'cad.config.json'),
229
+ c = JSON.parse(fs.readFileSync(cfg, 'utf8'));
149
230
  c.targets = { ...c.targets, shorten: 'gist' };
150
231
  fs.writeFileSync(cfg, `${JSON.stringify(c, null, 2)}\n`);
151
232
  let ready = true;
152
- try { execFileSync('gh', ['auth', 'status'], { stdio: 'ignore' }); } catch { ready = false; }
153
- console.log(ready ? 'short links: models you share go into secret Gists (unlisted: only people with the link find them)'
154
- : 'short links are on, but the gh command isn\'t installed or signed in: install it from cli.github.com and run gh auth login');
155
- } else console.log(`model links carry the whole model${share ? '' : ' (no --share given)'}; for short ones later, add "shorten": "gist" to "targets" in cad.config.json`);
233
+ try {
234
+ execFileSync('gh', ['auth', 'status'], { stdio: 'ignore' });
235
+ } catch {
236
+ ready = false;
237
+ }
238
+ console.log(
239
+ ready
240
+ ? 'short links: models you share go into secret Gists (unlisted: only people with the link find them)'
241
+ : "short links are on, but the gh command isn't installed or signed in: install it from cli.github.com and run gh auth login",
242
+ );
243
+ } else
244
+ console.log(
245
+ `model links carry the whole model${share ? '' : ' (no --share given)'}; for short ones later, add "shorten": "gist" to "targets" in cad.config.json`,
246
+ );
156
247
  if (install) execSync('npm install', { cwd: dir, stdio: 'inherit' });
157
- const start = machine === 'arm' ? 'arm/arm' : machine === 'leg' ? 'leg/stand' : machine === 'frame' ? 'frame/box' : 'home/soap-tray';
158
- console.log(`\n cd ${path.relative(process.cwd(), dir)}\n npx cad check ${start}\n npx cad preview ${start}${machine === 'arm' ? '\n npx cad plot arm/arm projects/arm/drawings/test.svg' : machine === 'frame' ? '\n npx cad kit frame/box' : ''}\n\nREADME.md says what's where.`);
248
+ const start =
249
+ machine === 'arm'
250
+ ? 'arm/arm'
251
+ : machine === 'leg'
252
+ ? 'leg/stand'
253
+ : machine === 'frame'
254
+ ? 'frame/box'
255
+ : 'home/soap-tray';
256
+ console.log(
257
+ `\n cd ${path.relative(process.cwd(), dir)}\n npx cad check ${start}\n npx cad preview ${start}${machine === 'arm' ? '\n npx cad plot arm/arm projects/arm/drawings/test.svg' : machine === 'frame' ? '\n npx cad kit frame/box' : ''}\n\nREADME.md says what's where.`,
258
+ );
@@ -27,7 +27,7 @@ measured milestone.
27
27
  | | |
28
28
  |---|---|
29
29
  | **Board** | Arduino Uno (16 MHz), CNC Shield V3 on top, a step driver (DRV8825 or A4988) in each slot used; or an Arduino Mega 2560 (16 MHz) with a DRV8825 on a driver breakout for each axis |
30
- | **On your computer** | Node 20 or later; the Arduino IDE or `arduino-cli` with the `arduino:avr` core and the `Servo` library, to flash the sketch (`--fqbn arduino:avr:uno`, or `arduino:avr:mega` for the Mega) |
30
+ | **On your computer** | Node 22.13 or later; the Arduino IDE or `arduino-cli` with the `arduino:avr` core and the `Servo` library, to flash the sketch (`--fqbn arduino:avr:uno`, or `arduino:avr:mega` for the Mega) |
31
31
  | **Wiring** | The shoulder on the shield's X slot, the elbow on Y, a third axis (if any) on Z; the home switches on the X and Y limit pins (D9 and D10), a third axis's on D12; the pen servo's signal on D11 (the Z limit pin on a V3.00 shield). `cad machine` writes the wiring sheet |
32
32
 
33
33
  ## Using it
@@ -35,7 +35,7 @@ measured milestone.
35
35
  1. Flash the sketch: `arduino-cli compile --fqbn arduino:avr:uno firmware/arm` then `arduino-cli upload -p <port> --fqbn arduino:avr:uno firmware/arm`, or open `firmware/arm/arm.ino` in the Arduino IDE and upload it.
36
36
  2. Write the machine description and a step file: `npx cad machine arm/arm` writes `exports/arm/arm.machine.json`, and `npx cad plot arm/arm projects/arm/drawings/test.svg` writes `exports/arm/arm-test.steps.json`. `npx cad plot arm/arm --calibrate` writes the calibration drawing (a 100 mm square and a circle at three places on the sheet).
37
37
  3. Dry run, with no board: `node projects/arm/send.mjs exports/arm/arm-test.steps.json --machine exports/arm/arm.machine.json --dry-run`. It prints each line it would send with the answer the streamer would give, then a summary. `--quiet` prints the summary only. A dry run has no clock, so it takes each block as finished before the next line: its answer to `?` is the positions summed from the blocks so far, with 0 blocks queued.
38
- 4. Draw: `node projects/arm/send.mjs exports/arm/arm-test.steps.json --machine exports/arm/arm.machine.json --port <port>`. It turns the drivers on, homes each axis, sends the file, reports every hundredth line, and turns the drivers off. `--no-home` skips homing.
38
+ 4. Draw: `node projects/arm/send.mjs exports/arm/arm-test.steps.json --machine exports/arm/arm.machine.json --port <port>`. It turns the drivers on, homes each axis, sends the file, reports every hundredth line, waits until the last move has run, and turns the drivers off. `--no-home` skips homing.
39
39
 
40
40
  ## A leg on the same streamer
41
41
 
@@ -50,7 +50,7 @@ hip's motor on the shield's X slot and the knee's on Y) takes the same sketch, t
50
50
  3. Dry run: `node projects/leg/send.mjs exports/leg/stand-gait.steps.json --machine exports/leg/stand.machine.json --dry-run`.
51
51
  4. Stand the leg in its pose, then send the file with `--port <port>`. The stand has no home switches, so the streamer
52
52
  counts from where the motors are when it starts: the file's first block takes the leg from its pose to the cycle, and
53
- its last brings it back. At the end the drivers go off and the carriage settles on its stop collars.
53
+ its last brings it back. Once it is back in its pose the drivers go off and the carriage settles on its stop collars.
54
54
 
55
55
  How the gait becomes blocks:
56
56
 
@@ -114,7 +114,8 @@ shield's limit pins; the leg's printed parts do not yet carry a switch's post an
114
114
  ## The line protocol
115
115
 
116
116
  115200 baud, 8 data bits, no parity, 1 stop bit. One command a line, ended by a newline. The streamer answers every
117
- line once: `ok` when it has taken the line, or `error: <what>` when it cannot. The sender waits for that answer before
117
+ line once: `ok` when it has taken the line, or `error: <what>` when it cannot. A block's `ok` means it is queued, not that
118
+ it has run: up to 12 can still be waiting when the last one is answered. The sender waits for that answer before
118
119
  it sends the next line. That is the flow control: a line that finds the queue full is held until a block finishes,
119
120
  and only then answered, so the 12-block queue never overruns. A line is at most 95 characters on the Uno and 127 on the
120
121
  Mega. Every number is a whole number.
@@ -129,7 +130,7 @@ block, naming its line, before it sends anything (see Timing). `cad plot` plans
129
130
  | Command | Arguments | What it does | Answers |
130
131
  |---|---|---|---|
131
132
  | `e` | | Drivers on: the motors hold | `ok` |
132
- | `d` | | Drivers off: the motors go slack | `ok` |
133
+ | `d` | | Drivers off: the motors go slack. Like `h`, it waits until every block, pen move and wait queued before it has run, so the last moves never run slack | `ok`, once the drivers are off |
133
134
  | `h` | axis, direction, rate, back | Home one axis (0, 1 or 2 on the Uno, 0 to 7 on the Mega): step towards direction (1 or -1) at rate steps/s until its switch closes, then step back off it by back steps, and call that position 0. It waits for the queue to empty first | `ok`; `error: endstop` if the switch has not closed after 60 s; `error: home` for a bad axis or rate |
134
135
  | `p` | degrees, milliseconds | Queue the pen servo to degrees, then a wait of milliseconds before the next block | `ok` |
135
136
  | `w` | milliseconds | Queue a wait | `ok` |
@@ -143,6 +144,13 @@ On power-up, and each time the serial port opens (which resets the board), the s
143
144
  `streamer ready, 3 axes` (`8 axes` on the Mega). The sender waits 2.5 s for it, and refuses to send lines written for
144
145
  the other board.
145
146
 
147
+ **The end of a job.** The sender's last line is `d`. Before it, the sender asks `?` every 100 ms until no block is
148
+ queued and no axis has moved since the last answer (`?` counts the blocks waiting, not the one running, so a count of
149
+ 0 alone can mean the last block is still under way), then sends `d`, which the streamer itself holds until everything
150
+ queued has run. So the drivers stay on until the last step, and the final `done` comes when the machine has stopped.
151
+ A streamer flashed before November 2026 turned the drivers off the moment `d` arrived, with the last blocks still to
152
+ run: the sender's wait keeps such a board safe, but reflash it to be sure (step 1 above).
153
+
146
154
  ## Timing
147
155
 
148
156
  | Figure | Value | Source |
@@ -207,3 +215,4 @@ board. On the simulated Mega the trot's 148 lines stream in 14.43 s against 14.5
207
215
  | MAX_RATE | a block 1 step/s past it is answered `error: rate`, a block at it `ok` |
208
216
  | Ceiling | the loop steps one to all its axes faster than MAX_RATE at the cruise, speeding up and slowing down (nine figures on the Uno, twenty-four on the Mega), and no axis of the machine asks more than MAX_RATE |
209
217
  | STEP pulse | at least 1.9 µs high |
218
+ | Drivers off | every step of the job comes before the enable pin goes high, the lines sent through `send.mjs`'s own `stream`; `test/firmware-disable.test.mjs` checks the same for the arm and the stand, and that the streamer's `d` and the sender's wait each keep the drivers on alone |
@@ -6,7 +6,7 @@
6
6
  // next line only after the answer: that is the flow control, and the buffer can never overrun.
7
7
  //
8
8
  // e drivers on (the motors hold)
9
- // d drivers off
9
+ // d drivers off, once everything queued has run (like h, it waits; answers "ok" when off)
10
10
  // h <axis> <dir> <rate> <back> home an axis (0 to AXES - 1): step towards dir (1 or -1) at rate steps/s until its
11
11
  // endstop closes, then come back off it by back steps. Answers "ok" when done, "error: endstop" if none in 60 s
12
12
  // p <deg> <ms> the pen servo to deg, then wait ms before anything after it
@@ -156,7 +156,12 @@ bool obey() {
156
156
  char c = cmd;
157
157
  if (bad) { Serial.println(F("error: line")); return true; }
158
158
  if (c == 'e') { digitalWrite(ENABLE_PIN, LOW); Serial.println(F("ok")); return true; }
159
- if (c == 'd') { digitalWrite(ENABLE_PIN, HIGH); Serial.println(F("ok")); return true; }
159
+ if (c == 'd') {
160
+ // drivers off only once every queued block, pen move and wait has run: "ok" to a block means it is queued, not done,
161
+ // so a d obeyed at once left the last blocks (up to the 12 the queue holds) to run with the motors slack
162
+ if (running || waiting || count()) return false;
163
+ digitalWrite(ENABLE_PIN, HIGH); Serial.println(F("ok")); return true;
164
+ }
160
165
  if (c == '!') { head = tail = 0; running = false; waiting = false; chained = false; Serial.println(F("ok")); return true; }
161
166
  if (c == '?') { Serial.print(F("q ")); for (uint8_t i = 0; i < AXES; i++) { Serial.print(ax[i].position); Serial.print(' '); } Serial.println(count()); return true; }
162
167
  if (c == 'h') {
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
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
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.
4
+ // machine description's controller says which. The streamer answers a block when it is queued, not when it has run, so
5
+ // before the last line (d, drivers off) the sender asks the board where it is until nothing is queued and nothing moves.
5
6
  // node send.mjs <file.steps.json> --port /dev/tty.usbmodem101 [--machine arm.machine.json] [--no-home]
6
7
  // node send.mjs <file.steps.json> --dry-run [--machine arm.machine.json] [--quiet]
7
8
  // echoes each line it would send with the answer the streamer would give,
@@ -115,6 +116,57 @@ export function dryRun(lines, { machine, turnaround = TURNAROUND } = {}) {
115
116
  return { lines: lines.length, ...seen, peakRate: peak, axisPeaks, position, said };
116
117
  }
117
118
 
119
+ /** The lines of a whole job, in the order send.mjs sends them: drivers on, each axis homed (where the machine has a switch
120
+ * for it, and unless home is false), the file's blocks, drivers off. Throws as linesOf does, before anything is sent.
121
+ * @param {object} file a step file @param {object | null} [machine] cad machine's description @param {{ home?: boolean }} [o] */
122
+ export function jobLines(file, machine, { home = true } = {}) {
123
+ const st = streamerOf(machine);
124
+ return ['e', ...(machine && home ? homeLines(machine) : []), ...linesOf(file, { ...(machine?.pen ? { pen: machine.pen } : {}), axes: st.axes, ...(machine ? { names: machine.axes.map((a) => a.name) } : {}) }), 'd'];
125
+ }
126
+
127
+ /** How long the sender waits between two questions to the board while its last moves run, ms. The slowest a block steps
128
+ * is the streamer's MIN_RATE, 80 steps/s, a step every 12.5 ms, so a moving machine always moves between two questions. */
129
+ export const POLL = 100;
130
+
131
+ /** The streamer's answer to `?` read: "q <a position for each axis> <blocks queued>". Null for any other line.
132
+ * @param {string} line @returns {{ position: number[], queued: number } | null} */
133
+ export function report(line) {
134
+ if (!/^q( -?\d+){2,}$/.test(line ?? '')) return null;
135
+ const x = line.slice(2).split(' ').map(Number);
136
+ return { position: x.slice(0, -1), queued: x.at(-1) };
137
+ }
138
+
139
+ /** Wait until the board has run everything it was sent: ask it `?` every POLL ms until no block is queued and no axis has
140
+ * moved since the last answer. `?` counts the blocks waiting, not the one running, so 0 alone can mean the last block is
141
+ * still under way. A streamer flashed before d waited for its queue (it turned the drivers off at once, with up to 12
142
+ * blocks still to run) is kept safe by this; the streamer now waits too. A final wait or pen move, with no axis moving,
143
+ * is not waited for here (the streamer's own d waits for it).
144
+ * @param {(line: string) => Promise<string> | string} ask sends a line, gives its answer
145
+ * @param {(ms: number) => Promise<void> | void} [pause] @returns {Promise<string>} the board's last report */
146
+ export async function settle(ask, pause = (ms) => new Promise((res) => setTimeout(res, ms))) {
147
+ let last = null;
148
+ for (;;) {
149
+ const a = await ask('?'), r = report(a);
150
+ if (!r) throw new Error(`the board answered "?" with "${a}", and the streamer answers "q <positions> <blocks queued>"`);
151
+ if (r.queued === 0 && last && r.position.join(' ') === last.position.join(' ')) return a;
152
+ last = r;
153
+ await pause(POLL);
154
+ }
155
+ }
156
+
157
+ /** Send a job's lines, each after the last was answered "ok", waiting for the board to finish moving (settle) before d.
158
+ * Throws at the first line answered otherwise, naming it, after stop() (the sender's "!": stop at once).
159
+ * @param {string[]} lines @param {(line: string) => Promise<string> | string} ask sends a line, gives its answer
160
+ * @param {{ pause?: (ms: number) => Promise<void> | void, say?: (text: string) => void, stop?: () => void }} [o] */
161
+ export async function stream(lines, ask, { pause, say = () => {}, stop = () => {} } = {}) {
162
+ for (const [i, l] of lines.entries()) {
163
+ if (l === 'd') await settle(ask, pause);
164
+ const reply = await ask(l);
165
+ if (reply !== 'ok') { stop(); throw new Error(`line ${i + 1} ("${l}"): ${reply}`); }
166
+ if (i % 100 === 0) say(`${i} of ${lines.length}`);
167
+ }
168
+ }
169
+
118
170
  /** What a gait's step file is, for the summary: its cycles, time and start pose (nothing for a drawing). @param {object} file */
119
171
  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
172
 
@@ -124,16 +176,12 @@ async function send(port, lines, say, axes = 3) {
124
176
  const rd = fs.createReadStream(port), wr = fs.createWriteStream(port);
125
177
  let buffer = '', answer = null;
126
178
  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); } } });
179
+ 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|q )/.test(l)) { const a = answer; answer = null; a(l); } else if (l) { greeting = /^streamer ready, (\d+) axes$/.exec(l)?.[1] ?? greeting; say(l); } } });
128
180
  await new Promise((res) => setTimeout(res, 2500)); // the board resets when the port opens
129
181
  // the streamer says how many axes it was built for: lines written for another board would be misread
130
182
  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();
183
+ const ask = (l) => new Promise((res) => { answer = res; wr.write(`${l}\n`); });
184
+ try { await stream(lines, ask, { say, stop: () => wr.write('!\n') }); } finally { rd.destroy(); wr.end(); }
137
185
  }
138
186
 
139
187
  if (process.argv[1] === fileURLToPath(import.meta.url)) {
@@ -143,7 +191,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
143
191
  const file = JSON.parse(fs.readFileSync(fileName, 'utf8')), machine = opt('machine') ? JSON.parse(fs.readFileSync(opt('machine'), 'utf8')) : null;
144
192
  // the whole file is checked before anything moves: a block refused halfway through a drawing would spoil it
145
193
  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); }
194
+ try { st = streamerOf(machine); lines = jobLines(file, machine, { home: !has('no-home') }); } catch (e) { console.error(`${has('dry-run') ? 'dry run' : 'not sent'}: ${e.message}`); process.exit(1); }
147
195
  try { r = dryRun(lines, { machine }); } catch (e) { console.error(`${has('dry-run') ? 'dry run' : 'not sent'}: ${e.message}`); process.exit(1); }
148
196
  if (has('dry-run')) {
149
197
  if (!has('quiet')) for (const s of r.said) console.log(s);
@@ -9,6 +9,7 @@
9
9
  "feet": "levelling"
10
10
  },
11
11
  "loads": [
12
- { "mass": 5, "at": "x3.top@50%", "note": "5 kg set on the middle of the top's front beam: change it to what the box carries" }
12
+ { "mass": 2.5, "at": "x3.top@50%", "note": "Half of 5 kg set on the top, on the middle of its front beam: change it to what the box carries" },
13
+ { "mass": 2.5, "at": "x4.top@50%", "note": "The other half, on the middle of the top's back beam. On the front beam alone, the box tips forward under a light push (frame.tip)" }
13
14
  ]
14
15
  }
@@ -27,7 +27,7 @@ measured milestone.
27
27
  | | |
28
28
  |---|---|
29
29
  | **Board** | Arduino Uno (16 MHz), CNC Shield V3 on top, a step driver (DRV8825 or A4988) in each slot used; or an Arduino Mega 2560 (16 MHz) with a DRV8825 on a driver breakout for each axis |
30
- | **On your computer** | Node 20 or later; the Arduino IDE or `arduino-cli` with the `arduino:avr` core and the `Servo` library, to flash the sketch (`--fqbn arduino:avr:uno`, or `arduino:avr:mega` for the Mega) |
30
+ | **On your computer** | Node 22.13 or later; the Arduino IDE or `arduino-cli` with the `arduino:avr` core and the `Servo` library, to flash the sketch (`--fqbn arduino:avr:uno`, or `arduino:avr:mega` for the Mega) |
31
31
  | **Wiring** | The shoulder on the shield's X slot, the elbow on Y, a third axis (if any) on Z; the home switches on the X and Y limit pins (D9 and D10), a third axis's on D12; the pen servo's signal on D11 (the Z limit pin on a V3.00 shield). `cad machine` writes the wiring sheet |
32
32
 
33
33
  ## Using it
@@ -35,7 +35,7 @@ measured milestone.
35
35
  1. Flash the sketch: `arduino-cli compile --fqbn arduino:avr:uno firmware/arm` then `arduino-cli upload -p <port> --fqbn arduino:avr:uno firmware/arm`, or open `firmware/arm/arm.ino` in the Arduino IDE and upload it.
36
36
  2. Write the machine description and a step file: `npx cad machine arm/arm` writes `exports/arm/arm.machine.json`, and `npx cad plot arm/arm projects/arm/drawings/test.svg` writes `exports/arm/arm-test.steps.json`. `npx cad plot arm/arm --calibrate` writes the calibration drawing (a 100 mm square and a circle at three places on the sheet).
37
37
  3. Dry run, with no board: `node projects/arm/send.mjs exports/arm/arm-test.steps.json --machine exports/arm/arm.machine.json --dry-run`. It prints each line it would send with the answer the streamer would give, then a summary. `--quiet` prints the summary only. A dry run has no clock, so it takes each block as finished before the next line: its answer to `?` is the positions summed from the blocks so far, with 0 blocks queued.
38
- 4. Draw: `node projects/arm/send.mjs exports/arm/arm-test.steps.json --machine exports/arm/arm.machine.json --port <port>`. It turns the drivers on, homes each axis, sends the file, reports every hundredth line, and turns the drivers off. `--no-home` skips homing.
38
+ 4. Draw: `node projects/arm/send.mjs exports/arm/arm-test.steps.json --machine exports/arm/arm.machine.json --port <port>`. It turns the drivers on, homes each axis, sends the file, reports every hundredth line, waits until the last move has run, and turns the drivers off. `--no-home` skips homing.
39
39
 
40
40
  ## A leg on the same streamer
41
41
 
@@ -50,7 +50,7 @@ hip's motor on the shield's X slot and the knee's on Y) takes the same sketch, t
50
50
  3. Dry run: `node projects/leg/send.mjs exports/leg/stand-gait.steps.json --machine exports/leg/stand.machine.json --dry-run`.
51
51
  4. Stand the leg in its pose, then send the file with `--port <port>`. The stand has no home switches, so the streamer
52
52
  counts from where the motors are when it starts: the file's first block takes the leg from its pose to the cycle, and
53
- its last brings it back. At the end the drivers go off and the carriage settles on its stop collars.
53
+ its last brings it back. Once it is back in its pose the drivers go off and the carriage settles on its stop collars.
54
54
 
55
55
  How the gait becomes blocks:
56
56
 
@@ -114,7 +114,8 @@ shield's limit pins; the leg's printed parts do not yet carry a switch's post an
114
114
  ## The line protocol
115
115
 
116
116
  115200 baud, 8 data bits, no parity, 1 stop bit. One command a line, ended by a newline. The streamer answers every
117
- line once: `ok` when it has taken the line, or `error: <what>` when it cannot. The sender waits for that answer before
117
+ line once: `ok` when it has taken the line, or `error: <what>` when it cannot. A block's `ok` means it is queued, not that
118
+ it has run: up to 12 can still be waiting when the last one is answered. The sender waits for that answer before
118
119
  it sends the next line. That is the flow control: a line that finds the queue full is held until a block finishes,
119
120
  and only then answered, so the 12-block queue never overruns. A line is at most 95 characters on the Uno and 127 on the
120
121
  Mega. Every number is a whole number.
@@ -129,7 +130,7 @@ block, naming its line, before it sends anything (see Timing). `cad plot` plans
129
130
  | Command | Arguments | What it does | Answers |
130
131
  |---|---|---|---|
131
132
  | `e` | | Drivers on: the motors hold | `ok` |
132
- | `d` | | Drivers off: the motors go slack | `ok` |
133
+ | `d` | | Drivers off: the motors go slack. Like `h`, it waits until every block, pen move and wait queued before it has run, so the last moves never run slack | `ok`, once the drivers are off |
133
134
  | `h` | axis, direction, rate, back | Home one axis (0, 1 or 2 on the Uno, 0 to 7 on the Mega): step towards direction (1 or -1) at rate steps/s until its switch closes, then step back off it by back steps, and call that position 0. It waits for the queue to empty first | `ok`; `error: endstop` if the switch has not closed after 60 s; `error: home` for a bad axis or rate |
134
135
  | `p` | degrees, milliseconds | Queue the pen servo to degrees, then a wait of milliseconds before the next block | `ok` |
135
136
  | `w` | milliseconds | Queue a wait | `ok` |
@@ -143,6 +144,13 @@ On power-up, and each time the serial port opens (which resets the board), the s
143
144
  `streamer ready, 3 axes` (`8 axes` on the Mega). The sender waits 2.5 s for it, and refuses to send lines written for
144
145
  the other board.
145
146
 
147
+ **The end of a job.** The sender's last line is `d`. Before it, the sender asks `?` every 100 ms until no block is
148
+ queued and no axis has moved since the last answer (`?` counts the blocks waiting, not the one running, so a count of
149
+ 0 alone can mean the last block is still under way), then sends `d`, which the streamer itself holds until everything
150
+ queued has run. So the drivers stay on until the last step, and the final `done` comes when the machine has stopped.
151
+ A streamer flashed before November 2026 turned the drivers off the moment `d` arrived, with the last blocks still to
152
+ run: the sender's wait keeps such a board safe, but reflash it to be sure (step 1 above).
153
+
146
154
  ## Timing
147
155
 
148
156
  | Figure | Value | Source |
@@ -207,3 +215,4 @@ board. On the simulated Mega the trot's 148 lines stream in 14.43 s against 14.5
207
215
  | MAX_RATE | a block 1 step/s past it is answered `error: rate`, a block at it `ok` |
208
216
  | Ceiling | the loop steps one to all its axes faster than MAX_RATE at the cruise, speeding up and slowing down (nine figures on the Uno, twenty-four on the Mega), and no axis of the machine asks more than MAX_RATE |
209
217
  | STEP pulse | at least 1.9 µs high |
218
+ | Drivers off | every step of the job comes before the enable pin goes high, the lines sent through `send.mjs`'s own `stream`; `test/firmware-disable.test.mjs` checks the same for the arm and the stand, and that the streamer's `d` and the sender's wait each keep the drivers on alone |
@@ -6,7 +6,7 @@
6
6
  // next line only after the answer: that is the flow control, and the buffer can never overrun.
7
7
  //
8
8
  // e drivers on (the motors hold)
9
- // d drivers off
9
+ // d drivers off, once everything queued has run (like h, it waits; answers "ok" when off)
10
10
  // h <axis> <dir> <rate> <back> home an axis (0 to AXES - 1): step towards dir (1 or -1) at rate steps/s until its
11
11
  // endstop closes, then come back off it by back steps. Answers "ok" when done, "error: endstop" if none in 60 s
12
12
  // p <deg> <ms> the pen servo to deg, then wait ms before anything after it
@@ -156,7 +156,12 @@ bool obey() {
156
156
  char c = cmd;
157
157
  if (bad) { Serial.println(F("error: line")); return true; }
158
158
  if (c == 'e') { digitalWrite(ENABLE_PIN, LOW); Serial.println(F("ok")); return true; }
159
- if (c == 'd') { digitalWrite(ENABLE_PIN, HIGH); Serial.println(F("ok")); return true; }
159
+ if (c == 'd') {
160
+ // drivers off only once every queued block, pen move and wait has run: "ok" to a block means it is queued, not done,
161
+ // so a d obeyed at once left the last blocks (up to the 12 the queue holds) to run with the motors slack
162
+ if (running || waiting || count()) return false;
163
+ digitalWrite(ENABLE_PIN, HIGH); Serial.println(F("ok")); return true;
164
+ }
160
165
  if (c == '!') { head = tail = 0; running = false; waiting = false; chained = false; Serial.println(F("ok")); return true; }
161
166
  if (c == '?') { Serial.print(F("q ")); for (uint8_t i = 0; i < AXES; i++) { Serial.print(ax[i].position); Serial.print(' '); } Serial.println(count()); return true; }
162
167
  if (c == 'h') {
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
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
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.
4
+ // machine description's controller says which. The streamer answers a block when it is queued, not when it has run, so
5
+ // before the last line (d, drivers off) the sender asks the board where it is until nothing is queued and nothing moves.
5
6
  // node send.mjs <file.steps.json> --port /dev/tty.usbmodem101 [--machine arm.machine.json] [--no-home]
6
7
  // node send.mjs <file.steps.json> --dry-run [--machine arm.machine.json] [--quiet]
7
8
  // echoes each line it would send with the answer the streamer would give,
@@ -115,6 +116,57 @@ export function dryRun(lines, { machine, turnaround = TURNAROUND } = {}) {
115
116
  return { lines: lines.length, ...seen, peakRate: peak, axisPeaks, position, said };
116
117
  }
117
118
 
119
+ /** The lines of a whole job, in the order send.mjs sends them: drivers on, each axis homed (where the machine has a switch
120
+ * for it, and unless home is false), the file's blocks, drivers off. Throws as linesOf does, before anything is sent.
121
+ * @param {object} file a step file @param {object | null} [machine] cad machine's description @param {{ home?: boolean }} [o] */
122
+ export function jobLines(file, machine, { home = true } = {}) {
123
+ const st = streamerOf(machine);
124
+ return ['e', ...(machine && home ? homeLines(machine) : []), ...linesOf(file, { ...(machine?.pen ? { pen: machine.pen } : {}), axes: st.axes, ...(machine ? { names: machine.axes.map((a) => a.name) } : {}) }), 'd'];
125
+ }
126
+
127
+ /** How long the sender waits between two questions to the board while its last moves run, ms. The slowest a block steps
128
+ * is the streamer's MIN_RATE, 80 steps/s, a step every 12.5 ms, so a moving machine always moves between two questions. */
129
+ export const POLL = 100;
130
+
131
+ /** The streamer's answer to `?` read: "q <a position for each axis> <blocks queued>". Null for any other line.
132
+ * @param {string} line @returns {{ position: number[], queued: number } | null} */
133
+ export function report(line) {
134
+ if (!/^q( -?\d+){2,}$/.test(line ?? '')) return null;
135
+ const x = line.slice(2).split(' ').map(Number);
136
+ return { position: x.slice(0, -1), queued: x.at(-1) };
137
+ }
138
+
139
+ /** Wait until the board has run everything it was sent: ask it `?` every POLL ms until no block is queued and no axis has
140
+ * moved since the last answer. `?` counts the blocks waiting, not the one running, so 0 alone can mean the last block is
141
+ * still under way. A streamer flashed before d waited for its queue (it turned the drivers off at once, with up to 12
142
+ * blocks still to run) is kept safe by this; the streamer now waits too. A final wait or pen move, with no axis moving,
143
+ * is not waited for here (the streamer's own d waits for it).
144
+ * @param {(line: string) => Promise<string> | string} ask sends a line, gives its answer
145
+ * @param {(ms: number) => Promise<void> | void} [pause] @returns {Promise<string>} the board's last report */
146
+ export async function settle(ask, pause = (ms) => new Promise((res) => setTimeout(res, ms))) {
147
+ let last = null;
148
+ for (;;) {
149
+ const a = await ask('?'), r = report(a);
150
+ if (!r) throw new Error(`the board answered "?" with "${a}", and the streamer answers "q <positions> <blocks queued>"`);
151
+ if (r.queued === 0 && last && r.position.join(' ') === last.position.join(' ')) return a;
152
+ last = r;
153
+ await pause(POLL);
154
+ }
155
+ }
156
+
157
+ /** Send a job's lines, each after the last was answered "ok", waiting for the board to finish moving (settle) before d.
158
+ * Throws at the first line answered otherwise, naming it, after stop() (the sender's "!": stop at once).
159
+ * @param {string[]} lines @param {(line: string) => Promise<string> | string} ask sends a line, gives its answer
160
+ * @param {{ pause?: (ms: number) => Promise<void> | void, say?: (text: string) => void, stop?: () => void }} [o] */
161
+ export async function stream(lines, ask, { pause, say = () => {}, stop = () => {} } = {}) {
162
+ for (const [i, l] of lines.entries()) {
163
+ if (l === 'd') await settle(ask, pause);
164
+ const reply = await ask(l);
165
+ if (reply !== 'ok') { stop(); throw new Error(`line ${i + 1} ("${l}"): ${reply}`); }
166
+ if (i % 100 === 0) say(`${i} of ${lines.length}`);
167
+ }
168
+ }
169
+
118
170
  /** What a gait's step file is, for the summary: its cycles, time and start pose (nothing for a drawing). @param {object} file */
119
171
  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
172
 
@@ -124,16 +176,12 @@ async function send(port, lines, say, axes = 3) {
124
176
  const rd = fs.createReadStream(port), wr = fs.createWriteStream(port);
125
177
  let buffer = '', answer = null;
126
178
  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); } } });
179
+ 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|q )/.test(l)) { const a = answer; answer = null; a(l); } else if (l) { greeting = /^streamer ready, (\d+) axes$/.exec(l)?.[1] ?? greeting; say(l); } } });
128
180
  await new Promise((res) => setTimeout(res, 2500)); // the board resets when the port opens
129
181
  // the streamer says how many axes it was built for: lines written for another board would be misread
130
182
  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();
183
+ const ask = (l) => new Promise((res) => { answer = res; wr.write(`${l}\n`); });
184
+ try { await stream(lines, ask, { say, stop: () => wr.write('!\n') }); } finally { rd.destroy(); wr.end(); }
137
185
  }
138
186
 
139
187
  if (process.argv[1] === fileURLToPath(import.meta.url)) {
@@ -143,7 +191,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
143
191
  const file = JSON.parse(fs.readFileSync(fileName, 'utf8')), machine = opt('machine') ? JSON.parse(fs.readFileSync(opt('machine'), 'utf8')) : null;
144
192
  // the whole file is checked before anything moves: a block refused halfway through a drawing would spoil it
145
193
  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); }
194
+ try { st = streamerOf(machine); lines = jobLines(file, machine, { home: !has('no-home') }); } catch (e) { console.error(`${has('dry-run') ? 'dry run' : 'not sent'}: ${e.message}`); process.exit(1); }
147
195
  try { r = dryRun(lines, { machine }); } catch (e) { console.error(`${has('dry-run') ? 'dry run' : 'not sent'}: ${e.message}`); process.exit(1); }
148
196
  if (has('dry-run')) {
149
197
  if (!has('quiet')) for (const s of r.said) console.log(s);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-rulecad",
3
- "version": "0.3.28",
3
+ "version": "0.4.0",
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": {
@@ -8,6 +8,7 @@
8
8
  },
9
9
  "files": [
10
10
  "index.mjs",
11
+ "frame-sizes.mjs",
11
12
  "template",
12
13
  "machines",
13
14
  "README.md",
@@ -23,7 +24,7 @@
23
24
  "scaffold"
24
25
  ],
25
26
  "engines": {
26
- "node": ">=20.6"
27
+ "node": ">=22.13"
27
28
  },
28
29
  "repository": {
29
30
  "type": "git",
@@ -77,6 +77,10 @@ variable says which rule it comes from. Follow these steps; they're what makes a
77
77
  `@rulecad/gears`, `@rulecad/motors`, `@rulecad/fixings` and files in their project, and can't write files or start
78
78
  programs. To see a value while designing, `console.log` it: it comes
79
79
  out with the command's output. A misspelt `v.name` stops the build and says which name was meant.
80
+ A design may run for an hour (3600 s) and hold 4096 MB: `design.time` or `design.memory` means it was stopped
81
+ there, most often by a loop that never ends. Fix the loop; raise `designTimeout` or `designMemory` in
82
+ cad.config.json only for a design that is truly that slow (a raise above the defaults counts once the user has
83
+ run `cad trust`).
80
84
  - Something printed under the part and removed afterwards is a named `support` part (`return { cap, pillar }`, both
81
85
  described in the .json's `parts`), not part of the shape. Look at `cad preview --explode` too.
82
86
 
@@ -104,7 +108,9 @@ variable says which rule it comes from. Follow these steps; they're what makes a
104
108
  and name the screw by thread and head with no length: the check chooses one. It reads the holes from the parts as
105
109
  drawn: one axis through the stack, a clearance hole in each part passed, a pilot, insert or nut at the far end, the
106
110
  length chosen from what is sold, thread engaged, the seat under the head and the key's way to it, and `cad list`
107
- counts the screws. Report what it finds with its numbers, and fix the part, never the relation, to make it pass.
111
+ counts the screws. `fasten.stack` fails where the parts do not meet along the screw (a part placed wrong: move it,
112
+ never lengthen the screw), and `fasten.wall` warns where too little plastic is left round the far hole (move the
113
+ hole in or thicken the part). Report what it finds with its numbers, and fix the part, never the relation, to make it pass.
108
114
  - **A frame is beams and joins, never loose boxes.** Each beam is a `"beam"` item of a profile from a rule set (the
109
115
  kit's or one in `rules/`, never sizes typed into an object), placed by its ends; each meeting of two beams is a
110
116
  declared join, and its drilling, tapping, screws and nuts follow from it: never draw a join's holes or type its
@@ -123,29 +129,36 @@ variable says which rule it comes from. Follow these steps; they're what makes a
123
129
  or slot: choose another set, never edit the set to pass. The other kinds are checked where they meet and say their
124
130
  fitting comes later (`join.fitting`). Move the beam to fix `join.geometry`, never the address, unless the
125
131
  address is what was wrong; `join.stiffness` says whether it rests on an estimate or on the joint rig's
126
- measurement (and its date): report it as it says. A `join.drop` is a prediction for a beam held by one join, to
127
- measure and write back with `cad measured`, never a figure to tune. `frame.deflection` gives each sag twice, on
132
+ measurement (and its date): report it as it says. A `join.drop` is a prediction for a beam held by one join and nothing
133
+ else, from the frame's solve on the supports it is given (or, on the joint rig, its base beam held along its
134
+ length), to measure and write back with `cad measured`, never a figure to tune. `frame.deflection` gives each sag twice, on
128
135
  the joins' springs and with the joins rigid: report the first with what it rests on (`refs.restsOn`), never the
129
136
  rigid one alone. Say where the frame stands with `"frame": { "supports" }` or fitted feet, not by moving beams. A `frame.solve` warning that its supports are guessed means neither is given.
130
137
  `frame.rack` gives the racking stiffness each way and the gain each change (gussets, a brace, a panel) solves to:
131
138
  report the stiffness, the gain and the change it advises, and say the push and the joins' springs are estimates.
139
+ `frame.tip` fails a frame standing free on its feet that its load, or that push at its top, tips over: report the
140
+ push that tips it (`values.tips`) and the feet it lifts (`refs.lifts`), then widen its base or carry the load nearer
141
+ the middle or lower. Say it is bolted down with `"frame": { "supports" }` only where it really is; never lower the
142
+ push to make it pass.
132
143
  `frame.frequency` gives the lowest mode against what the machine excites: report it with its pose, and look at
133
144
  `<assembly>.frame-mode.svg` from `cad beams` to see what moves. To choose profiles, give `"frame": { "size": {
134
145
  "profiles": [...] } }` and read `frame.size` (or `npx cad frame <project>/<assembly> --size`): report each group's
135
146
  profile with the limit that set it (or the join a lighter profile could not make) and its margin, never pick a
136
147
  profile by hand where the sizing can; give `"rack"` to hold racking too; write it with
137
- `--size --write` and check again, as its joins and lengths change. A task on a guide counts the beam's sag (the
148
+ `--size --write`, which checks the design it would write and writes nothing that fails (it names the checks: fix
149
+ what they say, or leave out the profile that breaks them), then check again. A task on a guide counts the beam's sag (the
138
150
  frame's own figure where the frame is solved), straightness and twist in `task.accuracy`: report the biggest term
139
151
  as it is named. `frame.heat` (given `"frame": { "heat": { "air": 45 } }`) says how much the frame grows and holds
140
- each printed fitting to its plastic's softening point: move a failing fitting from the heat or print it in a plastic
141
- that softens higher, never raise the softening figure. `beam.printable` (given `"frame": { "printed": "petg" }`)
152
+ each printed fitting and printed beam to its plastic's softening point: move a failing part from the heat or print it
153
+ in a plastic that softens higher (a beam can be metal), never raise the softening figure. `beam.printable` (given `"frame": { "printed": "petg" }`)
142
154
  says which beams could be printed and the margin each misses by: report the margin and what governs it, say it
143
155
  rests on estimates (the printed section, creep) until the beam coupon is measured, and name the joins it says need
144
156
  changing. A `beam.coupon` sag or break is a prediction to measure on the bench and write back with `cad measured`,
145
157
  never a figure to tune; `beam.creep` fails a printed beam held too hard for months: a deeper section or aluminium.
146
158
  A beam that needs slots in more than its top face prints standing up from the metal's profile
147
159
  (`"printed": { "pose": "standing", "end": "nut" }`): its tapped end takes the thread `beam.end` names, and a foot
148
- under it takes that `"thread"`. Report each printed beam's pose, grams and the sag `frame.deflection` gives.
160
+ under it takes that `"thread"`. Report each printed beam's pose, grams and the sag `frame.deflection` gives, after creep too where it says so (an
161
+ estimate).
149
162
  - **A frame for a size starts from a generator**: `"frame": { "kind": "box", "inside": [w, d, h], "profile",
150
163
  "join": "blind" }` (also portal, table, gantry, shelf) expands into beams, joins, feet and caps before anything is
151
164
  checked. Ask by `inside` for what it must enclose, `outside` for what it must fit in; never work the lengths out by
@@ -196,7 +209,8 @@ variable says which rule it comes from. Follow these steps; they're what makes a
196
209
  - **A part screwed onto a beam is a `fasten` into a slot**: `"into": "x1.top"` (or `x1.top.2`, or `x1.top@120`, the
197
210
  middle of its screws), the
198
211
  part's holes drawn with `v.fixings` at the slot's spacing, `"nut"` the slot nut's kind. `fasten.slot` fails a hole off
199
- a slot's centre line, with the distance: move the hole. `frame.nut` fails slide-in nuts in a slot that joins close
212
+ a slot's centre line, with the distance: move the hole. It fails a nut that runs past the beam's end, and
213
+ `frame.nut` two nuts that crowd one stretch of slot: move the part along the beam. `frame.nut` fails slide-in nuts in a slot that joins close
200
214
  at both ends: use the kind it names (`"nut": "drop-in"`). `frame.preload` lists nuts to load before a join; tell
201
215
  the user, and `cad order` shows them on the step.
202
216
  - **A frame's build is `cad order`**: from bars to a square frame in numbered steps (cut, drill and tap, sides built
@@ -231,6 +245,8 @@ variable says which rule it comes from. Follow these steps; they're what makes a
231
245
 
232
246
  ## Circuit boards
233
247
  - `"engine": "pcb"` in the .json; `main(v)` returns a board built with `v.pcb` (see @rulecad/pcb's README).
248
+ - A board design runs in the sandbox as any design does, with `v.pcb` as its only way to the board engine: it can't
249
+ import Node's modules, read files outside the workspace or write any. A workspace with boards asks for no trust.
234
250
  - Parts come from rule sets where one exists (`v.pcb.xiao`, `qwiic`, `jstph`, `header`), or any standard footprint by
235
251
  name (`v.pcb.part('U2', 'soic8', x, y)`). Turn parts in quarter turns with `rotation`, held in a variable.
236
252
  - A board's mounting holes are named by their screws' thread, never typed: `v.pcb.mount('M2', x, y)` in its `holes`
@@ -252,8 +268,8 @@ variable says which rule it comes from. Follow these steps; they're what makes a
252
268
  region is never emptied: if `cad optimise` says part of one has nothing holding it up, give the part more material
253
269
  to stand it on, or keep less. `cad check` tests the part for one piece and nothing starting in mid-air.
254
270
  - Before reporting numbers for a final shape, verify them: give the `analysis` a smaller `cell` (solids: about a
255
- third of the problem's) and check the stiffness has settled (`fea.settled`). Report the verified numbers, the safety
256
- factor, and where the peak stress is.
271
+ third of the problem's) and check it has settled (`fea.settled`: the stiffness, and with `min_safety` the peak
272
+ stress too). Report the verified numbers, the safety factor, and where the peak stress is.
257
273
  - For a part that must not break (a lever, a pedal), give its problem a `"stress"` limit (the material's strength
258
274
  over a safety factor) instead of a `"volume"`: the lightest layout under it. Then verify it on finer cells.
259
275
  Add `"robust": true` so it holds made a little thin and a little thick too (`cad optimise` prints both copies'