@rulecad/motors 0.1.6 → 0.2.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
@@ -4,6 +4,31 @@ What changed in each release, for someone upgrading a workspace. A **printed siz
4
4
  print (a hole's diameter, a seat's depth, a part's outline). Each release says whether any printed size moved, and
5
5
  why.
6
6
 
7
+ ## 0.2.0: needs Node 22.13 or later, the version the kit is tested on
8
+
9
+ ### Changed
10
+
11
+ - @rulecad/motors now states Node 22.13 or later in its `engines`, the same lowest Node as every rulecad package, and
12
+ the 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
13
+ April 2026, and the kit's packages stated five different lowest versions, some of them too low: on Node 20.6 to 20.9
14
+ `cad` stopped at start-up with "Unexpected token 'with'", and on Node 22.0 to 22.12 every `cad` command that runs a
15
+ design stops, because the sandbox designs run in cannot start there. npm gave no warning at install for either.
16
+
17
+ Upgrading: on a Node older than 22.13, npm now warns at install that this package needs Node 22.13; install Node 22.13
18
+ or later (24 recommended). Nothing else changes, and no printed size moves.
19
+
20
+ ## 0.1.7: bores from shapes' shaftBore
21
+ ### Changed
22
+
23
+ - `boreModel` and `bore` read their fit from `@rulecad/shapes`' `shaftBore` (#307), the one place every shaft bore in
24
+ the kit reads it. `DEFAULTS.fit` and `DEFAULTS.press` are now the same objects as `SHAFT_FITS.slide` and
25
+ `SHAFT_FITS.press`, with a source and a date. The package depends on `@rulecad/shapes`, which fixings already did, at the release that
26
+ first ships `shaftBore`. A printer's `hole_comp` below 0 is still taken.
27
+
28
+ ### Printed sizes
29
+
30
+ - None moved: a NEMA 17's bore is still 5.2 mm (4.7 across its flat) at slide and 5.06 mm (4.56) at press.
31
+
7
32
  ## 0.1.6: motors mount through fixings (Fixings 3)
8
33
 
9
34
  ### What reads fixings now
package/README.md CHANGED
@@ -91,7 +91,8 @@ shaft passes through. A servo goes through the part instead: its body down a slo
91
91
  `bore(model, { depth, fit?, printer? }, ops?)` is the hole a gear or hub takes, with the shaft's flat in it. The shaft
92
92
  goes in from z = 0 with its tip at `depth`: the flat is cut only where the flat is, so a bore deeper than the flat is
93
93
  round at its mouth and the shaft's round root can pass. `boreModel` warns of a bore that grips too little of the shaft
94
- or misses its flat. A servo's spline is finer than a printer draws: drive it through its horn. A brushless motor drives
94
+ or misses its flat. Its fit, `slide` (the default, measured on the fit bar) or `press`, is `@rulecad/shapes`'
95
+ `shaftBore`'s, the one place every shaft bore in the kit reads it, so a pulley on the same shaft gets the same bore. A servo's spline is finer than a printer draws: drive it through its horn. A brushless motor drives
95
96
  through its bell.
96
97
 
97
98
  Anchors for placing a motor in an assembly are on the model: `face`, `shaft` (where the shaft leaves the motor), `tip`,
package/diagram.mjs CHANGED
@@ -14,23 +14,54 @@ const fig = (x) => String(+Number(x).toFixed(2));
14
14
  export function curve(m, o = {}) {
15
15
  const { supply, ratio = 1, efficiency = 1, at, width = 640, height = 380 } = o;
16
16
  const ask = (speed) => performance(m, { speed, ratio, efficiency, ...(supply != null ? { supply } : {}) });
17
- const first = ask(0), limit = first.limit, N = 120, pts = [];
18
- for (let i = 0; i <= N; i++) { const s = (limit * i) / N; pts.push([s, ask(s).output.torque]); }
19
- const yMax = Math.max(first.output.torque, ...pts.map((p) => p[1]), at?.load ?? 0) * 1.1, L = 76, B = height - 56, R = width - 24, T = 40;
20
- const X = (s) => L + ((R - L) * s) / limit, Y = (t) => B - ((B - T) * t) / yMax, out = [];
21
- out.push(`<rect width="100%" height="100%" fill="#fff"/><text x="${L}" y="24" font-size="15" font-family="system-ui, sans-serif" fill="#1a1a1a">${esc(m.name)}${ratio !== 1 ? `, through ${fig(ratio)}:1` : ''}: torque against speed</text>`);
17
+ const first = ask(0),
18
+ limit = first.limit,
19
+ N = 120,
20
+ pts = [];
21
+ for (let i = 0; i <= N; i++) {
22
+ const s = (limit * i) / N;
23
+ pts.push([s, ask(s).output.torque]);
24
+ }
25
+ const yMax = Math.max(first.output.torque, ...pts.map((p) => p[1]), at?.load ?? 0) * 1.1,
26
+ L = 76,
27
+ B = height - 56,
28
+ R = width - 24,
29
+ T = 40;
30
+ const X = (s) => L + ((R - L) * s) / limit,
31
+ Y = (t) => B - ((B - T) * t) / yMax,
32
+ out = [];
33
+ out.push(
34
+ `<rect width="100%" height="100%" fill="#fff"/><text x="${L}" y="24" font-size="15" font-family="system-ui, sans-serif" fill="#1a1a1a">${esc(m.name)}${ratio !== 1 ? `, through ${fig(ratio)}:1` : ''}: torque against speed</text>`,
35
+ );
22
36
  for (let i = 0; i <= 4; i++) {
23
- const t = (yMax * i) / 4, s = (limit * i) / 4;
24
- out.push(`<line x1="${L}" x2="${R}" y1="${fig(Y(t))}" y2="${fig(Y(t))}" stroke="#e4e4e4"/><text x="${L - 8}" y="${fig(Y(t) + 4)}" text-anchor="end" font-size="11" font-family="system-ui, sans-serif" fill="#555">${fig(t)}</text>`);
25
- out.push(`<line x1="${fig(X(s))}" x2="${fig(X(s))}" y1="${T}" y2="${B}" stroke="#e4e4e4"/><text x="${fig(X(s))}" y="${B + 16}" text-anchor="middle" font-size="11" font-family="system-ui, sans-serif" fill="#555">${fig(s)}</text>`);
37
+ const t = (yMax * i) / 4,
38
+ s = (limit * i) / 4;
39
+ out.push(
40
+ `<line x1="${L}" x2="${R}" y1="${fig(Y(t))}" y2="${fig(Y(t))}" stroke="#e4e4e4"/><text x="${L - 8}" y="${fig(Y(t) + 4)}" text-anchor="end" font-size="11" font-family="system-ui, sans-serif" fill="#555">${fig(t)}</text>`,
41
+ );
42
+ out.push(
43
+ `<line x1="${fig(X(s))}" x2="${fig(X(s))}" y1="${T}" y2="${B}" stroke="#e4e4e4"/><text x="${fig(X(s))}" y="${B + 16}" text-anchor="middle" font-size="11" font-family="system-ui, sans-serif" fill="#555">${fig(s)}</text>`,
44
+ );
26
45
  }
27
- out.push(`<polyline fill="none" stroke="#2266cc" stroke-width="2.2" points="${pts.map(([s, t]) => `${fig(X(s))},${fig(Y(t))}`).join(' ')}"/>`);
28
- out.push(`<text x="${(L + R) / 2}" y="${height - 22}" text-anchor="middle" font-size="12" font-family="system-ui, sans-serif" fill="#333">output speed, rpm</text><text transform="translate(18 ${(T + B) / 2}) rotate(-90)" text-anchor="middle" font-size="12" font-family="system-ui, sans-serif" fill="#333">output torque, N m</text>`);
46
+ out.push(
47
+ `<polyline fill="none" stroke="#2266cc" stroke-width="2.2" points="${pts.map(([s, t]) => `${fig(X(s))},${fig(Y(t))}`).join(' ')}"/>`,
48
+ );
49
+ out.push(
50
+ `<text x="${(L + R) / 2}" y="${height - 22}" text-anchor="middle" font-size="12" font-family="system-ui, sans-serif" fill="#333">output speed, rpm</text><text transform="translate(18 ${(T + B) / 2}) rotate(-90)" text-anchor="middle" font-size="12" font-family="system-ui, sans-serif" fill="#333">output torque, N m</text>`,
51
+ );
29
52
  if (at) {
30
- const here = ask(at.speed).output.torque, x = X(at.speed);
31
- out.push(`<circle cx="${fig(x)}" cy="${fig(Y(here))}" r="5" fill="#2266cc"/><text x="${fig(x + 9)}" y="${fig(Y(here) - 8)}" font-size="12" font-family="system-ui, sans-serif" fill="#1a1a1a">${fig(here)} N m at ${fig(at.speed)} rpm</text>`);
32
- if (at.load != null) out.push(`<line x1="${L}" x2="${R}" y1="${fig(Y(at.load))}" y2="${fig(Y(at.load))}" stroke="#cc3322" stroke-dasharray="6 4" stroke-width="1.4"/><text x="${R}" y="${fig(Y(at.load) - 6)}" text-anchor="end" font-size="12" font-family="system-ui, sans-serif" fill="#cc3322">the load, ${fig(at.load)} N m</text>`);
53
+ const here = ask(at.speed).output.torque,
54
+ x = X(at.speed);
55
+ out.push(
56
+ `<circle cx="${fig(x)}" cy="${fig(Y(here))}" r="5" fill="#2266cc"/><text x="${fig(x + 9)}" y="${fig(Y(here) - 8)}" font-size="12" font-family="system-ui, sans-serif" fill="#1a1a1a">${fig(here)} N m at ${fig(at.speed)} rpm</text>`,
57
+ );
58
+ if (at.load != null)
59
+ out.push(
60
+ `<line x1="${L}" x2="${R}" y1="${fig(Y(at.load))}" y2="${fig(Y(at.load))}" stroke="#cc3322" stroke-dasharray="6 4" stroke-width="1.4"/><text x="${R}" y="${fig(Y(at.load) - 6)}" text-anchor="end" font-size="12" font-family="system-ui, sans-serif" fill="#cc3322">the load, ${fig(at.load)} N m</text>`,
61
+ );
33
62
  }
34
- out.push(`<text x="${R}" y="24" text-anchor="end" font-size="11" font-family="system-ui, sans-serif" fill="#888">rests on ${esc(first.rests.join(', '))} figures</text>`);
63
+ out.push(
64
+ `<text x="${R}" y="24" text-anchor="end" font-size="11" font-family="system-ui, sans-serif" fill="#888">rests on ${esc(first.rests.join(', '))} figures</text>`,
65
+ );
35
66
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">${out.join('')}</svg>\n`;
36
67
  }
package/drivers.mjs CHANGED
@@ -19,9 +19,26 @@ export const DRIVER_EFFICIENCY = 0.85;
19
19
  export function driver(name, { variant } = {}) {
20
20
  const set = SETS[String(name).toLowerCase()];
21
21
  if (!set) throw new Error(`driver: no driver "${name}" (${Object.keys(SETS).join(', ')})`);
22
- if (variant != null && !set.variants?.[variant]) throw new Error(`driver: ${set.name} has no variant "${variant}" (${Object.keys(set.variants || {}).join(', ') || 'none'})`);
23
- const over = variant ? set.variants[variant].values : {}, v = (k) => over[k] ?? set.rules[k]?.value;
24
- return { name: set.name, variant: variant ?? null, voltage: [v('motor_voltage_min'), v('motor_voltage_max')], logic: [v('logic_voltage_min'), v('logic_voltage_max')], bare: v('current_bare'), cooled: v('current_cooled'), sense: v('sense_resistor'), gain: v('vref_gain'), formula: v('vref_formula'), maxMicrosteps: v('max_microsteps'), figures: set.rules, uart: set.rules.uart_note != null };
22
+ if (variant != null && !set.variants?.[variant])
23
+ throw new Error(
24
+ `driver: ${set.name} has no variant "${variant}" (${Object.keys(set.variants || {}).join(', ') || 'none'})`,
25
+ );
26
+ const over = variant ? set.variants[variant].values : {},
27
+ v = (k) => over[k] ?? set.rules[k]?.value;
28
+ return {
29
+ name: set.name,
30
+ variant: variant ?? null,
31
+ voltage: [v('motor_voltage_min'), v('motor_voltage_max')],
32
+ logic: [v('logic_voltage_min'), v('logic_voltage_max')],
33
+ bare: v('current_bare'),
34
+ cooled: v('current_cooled'),
35
+ sense: v('sense_resistor'),
36
+ gain: v('vref_gain'),
37
+ formula: v('vref_formula'),
38
+ maxMicrosteps: v('max_microsteps'),
39
+ figures: set.rules,
40
+ uart: set.rules.uart_note != null,
41
+ };
25
42
  }
26
43
 
27
44
  /**
@@ -31,11 +48,33 @@ export function driver(name, { variant } = {}) {
31
48
  */
32
49
  export function setting(d, current, { cooled = false, supply, microsteps } = {}) {
33
50
  if (!(current > 0)) throw new Error(`setting: current is above 0 A (got ${current})`);
34
- const out = [], f = (level, text, code, values) => out.push({ level, text, code, ...(values ? { values } : {}) }), limit = cooled ? d.cooled : d.bare, vref = current / d.gain;
35
- if (current > d.cooled) f('fail', `${d.name} carries ${d.cooled} A per coil at most, with cooling, and this asks ${n3(current, 2)} A`, 'motor.driver', { current, limit: d.cooled });
36
- else if (current > limit) f('warn', `${d.name} carries about ${d.bare} A with no heat sink, and this asks ${n3(current, 2)} A: fit a heat sink and moving air (up to ${d.cooled} A)`, 'motor.driver', { current, limit });
37
- if (supply != null && (supply < d.voltage[0] || supply > d.voltage[1])) f('fail', `${d.name} takes ${d.voltage[0]} to ${d.voltage[1]} V, and the supply is ${supply} V`, 'motor.driver', { supply, range: d.voltage });
38
- if (microsteps != null && microsteps > d.maxMicrosteps) f('fail', `${d.name} goes down to 1/${d.maxMicrosteps} of a step, and this asks 1/${microsteps}`, 'motor.driver', { microsteps });
51
+ const out = [],
52
+ f = (level, text, code, values) => out.push({ level, text, code, ...(values ? { values } : {}) }),
53
+ limit = cooled ? d.cooled : d.bare,
54
+ vref = current / d.gain;
55
+ if (current > d.cooled)
56
+ f(
57
+ 'fail',
58
+ `${d.name} carries ${d.cooled} A per coil at most, with cooling, and this asks ${n3(current, 2)} A`,
59
+ 'motor.driver',
60
+ { current, limit: d.cooled },
61
+ );
62
+ else if (current > limit)
63
+ f(
64
+ 'warn',
65
+ `${d.name} carries about ${d.bare} A with no heat sink, and this asks ${n3(current, 2)} A: fit a heat sink and moving air (up to ${d.cooled} A)`,
66
+ 'motor.driver',
67
+ { current, limit },
68
+ );
69
+ if (supply != null && (supply < d.voltage[0] || supply > d.voltage[1]))
70
+ f('fail', `${d.name} takes ${d.voltage[0]} to ${d.voltage[1]} V, and the supply is ${supply} V`, 'motor.driver', {
71
+ supply,
72
+ range: d.voltage,
73
+ });
74
+ if (microsteps != null && microsteps > d.maxMicrosteps)
75
+ f('fail', `${d.name} goes down to 1/${d.maxMicrosteps} of a step, and this asks 1/${microsteps}`, 'motor.driver', {
76
+ microsteps,
77
+ });
39
78
  return { vref, findings: out };
40
79
  }
41
80
 
@@ -51,16 +90,43 @@ export function powerBudget(parts, { voltage, current, margin = 1.25, duty = 1 }
51
90
  if (!(voltage > 0)) throw new Error(`powerBudget: give the supply's voltage (got ${voltage})`);
52
91
  if (!Array.isArray(parts) || !parts.length) throw new Error('powerBudget: give the parts that draw power');
53
92
  const rows = parts.map((p) => {
54
- const d = p.duty ?? duty, full = p.watts ?? (p.resistance != null ? (2 * p.current * p.current * p.resistance) / DRIVER_EFFICIENCY : p.current * (p.voltage ?? voltage));
55
- if (!(full >= 0) || !Number.isFinite(full)) throw new Error(`powerBudget: ${p.name}: give watts, or a current with a resistance or a voltage`);
93
+ const d = p.duty ?? duty,
94
+ full =
95
+ p.watts ??
96
+ (p.resistance != null
97
+ ? (2 * p.current * p.current * p.resistance) / DRIVER_EFFICIENCY
98
+ : p.current * (p.voltage ?? voltage));
99
+ if (!(full >= 0) || !Number.isFinite(full))
100
+ throw new Error(`powerBudget: ${p.name}: give watts, or a current with a resistance or a voltage`);
56
101
  return { name: p.name, watts: full, duty: d, average: full * d };
57
102
  });
58
- const watts = rows.reduce((t, p) => t + p.watts, 0), amps = watts / voltage, needed = amps * margin, findings = [];
103
+ const watts = rows.reduce((t, p) => t + p.watts, 0),
104
+ amps = watts / voltage,
105
+ needed = amps * margin,
106
+ findings = [];
59
107
  if (current != null) {
60
108
  const v = { amps, needed, rating: current, watts };
61
- if (current < amps) findings.push({ level: 'fail', text: `the machine draws ${n3(amps, 2)} A at ${voltage} V (${n3(watts, 1)} W), and the supply gives ${current} A`, code: 'power.supply', values: v });
62
- else if (current < needed) findings.push({ level: 'fail', text: `the machine draws ${n3(amps, 2)} A at ${voltage} V (${n3(watts, 1)} W): with ${margin} times in hand it wants ${n3(needed, 2)} A, and the supply gives ${current} A`, code: 'power.supply', values: v });
63
- else findings.push({ level: 'pass', text: `the machine draws ${n3(amps, 2)} A at ${voltage} V (${n3(watts, 1)} W), and the supply gives ${current} A, ${n3(current / amps, 1)} times over`, code: 'power.supply', values: v });
109
+ if (current < amps)
110
+ findings.push({
111
+ level: 'fail',
112
+ text: `the machine draws ${n3(amps, 2)} A at ${voltage} V (${n3(watts, 1)} W), and the supply gives ${current} A`,
113
+ code: 'power.supply',
114
+ values: v,
115
+ });
116
+ else if (current < needed)
117
+ findings.push({
118
+ level: 'fail',
119
+ text: `the machine draws ${n3(amps, 2)} A at ${voltage} V (${n3(watts, 1)} W): with ${margin} times in hand it wants ${n3(needed, 2)} A, and the supply gives ${current} A`,
120
+ code: 'power.supply',
121
+ values: v,
122
+ });
123
+ else
124
+ findings.push({
125
+ level: 'pass',
126
+ text: `the machine draws ${n3(amps, 2)} A at ${voltage} V (${n3(watts, 1)} W), and the supply gives ${current} A, ${n3(current / amps, 1)} times over`,
127
+ code: 'power.supply',
128
+ values: v,
129
+ });
64
130
  }
65
131
  return { watts, amps, needed, parts: rows, findings };
66
132
  }
package/motors.mjs CHANGED
@@ -17,6 +17,7 @@ import bldc2204 from '@rulecad/rules/bldc2204.json' with { type: 'json' };
17
17
  import x1c from '@rulecad/rules/x1c.json' with { type: 'json' };
18
18
  import engagementSet from '@rulecad/rules/engagement.json' with { type: 'json' };
19
19
  import { fixingModel, threads, holeModel, hole, counterboreModel, counterbore } from '@rulecad/fixings';
20
+ import { shaftBore, SHAFT_FITS } from '@rulecad/shapes';
20
21
 
21
22
  export { driver, setting, powerBudget, DRIVER_EFFICIENCY } from './drivers.mjs';
22
23
 
@@ -26,8 +27,19 @@ const { translate } = jscad.transforms;
26
27
  const booleans = { union: jscad.booleans.union, subtract: jscad.booleans.subtract };
27
28
 
28
29
  const CATALOGUE = Object.fromEntries([nema17, nema14, byj, n20, sg90, mg90s, bldc2204].map((s) => [s.name, s]));
29
- const key = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
30
- const ALIASES = { ...Object.fromEntries(Object.keys(CATALOGUE).map((n) => [key(n), n])), byj48: '28byj48', '28byj': '28byj48', mg90: 'mg90s', '2204': 'bldc2204', gimbal2204: 'bldc2204', n20gearmotor: 'n20' };
30
+ const key = (s) =>
31
+ String(s)
32
+ .toLowerCase()
33
+ .replace(/[^a-z0-9]/g, '');
34
+ const ALIASES = {
35
+ ...Object.fromEntries(Object.keys(CATALOGUE).map((n) => [key(n), n])),
36
+ byj48: '28byj48',
37
+ '28byj': '28byj48',
38
+ mg90: 'mg90s',
39
+ 2204: 'bldc2204',
40
+ gimbal2204: 'bldc2204',
41
+ n20gearmotor: 'n20',
42
+ };
31
43
  for (const s of Object.values(CATALOGUE)) for (const v of Object.keys(s.variants || {})) ALIASES[key(v)] = s.name;
32
44
 
33
45
  /**
@@ -35,25 +47,50 @@ for (const s of Object.values(CATALOGUE)) for (const v of Object.keys(s.variants
35
47
  * @type {Record<string, { value: number, unit: string, rule: string, kind: string }>}
36
48
  */
37
49
  export const DEFAULTS = {
38
- running: { value: Math.SQRT1_2, unit: '× holding torque', rule: 'A stepper moving, against holding torque: holding has both phases at full current, and a driver moving it keeps the vector the size of one phase, 1/√2 of that', kind: 'spec' },
39
- supply: { value: 24, unit: 'V', rule: 'The stepper driver\'s supply, if you don\'t say: above the motor\'s rated volts, as a chopper drive needs, and what a printer\'s board runs at', kind: 'default' },
40
- fit: { value: 0.05, unit: 'mm', rule: 'Gap each side of a shaft in its bore, with the printed hole\'s shrinkage allowed for, so it slides on and no more: measured on the fit bar, a 5 mm D-shaft sliding in a bore drawn 5.2 mm', kind: 'measured' },
41
- press: { value: -0.02, unit: 'mm', rule: 'Each side of a shaft in a press-fit bore as printed: a hair tight, 0.8% strain on a 5 mm shaft, well inside what PLA stretches to before it cracks. A D flat does the driving', kind: 'estimate' },
42
- grip: { value: 1.5, unit: '× shaft diameter', rule: 'The shortest length of bore worth trusting to drive a gear', kind: 'community' }
50
+ running: {
51
+ value: Math.SQRT1_2,
52
+ unit: '× holding torque',
53
+ rule: 'A stepper moving, against holding torque: holding has both phases at full current, and a driver moving it keeps the vector the size of one phase, 1/√2 of that',
54
+ kind: 'spec',
55
+ },
56
+ supply: {
57
+ value: 24,
58
+ unit: 'V',
59
+ rule: "The stepper driver's supply, if you don't say: above the motor's rated volts, as a chopper drive needs, and what a printer's board runs at",
60
+ kind: 'default',
61
+ },
62
+ // a shaft's bore fits, from @rulecad/shapes, where every shaft bore in the kit reads them (the same objects)
63
+ fit: SHAFT_FITS.slide,
64
+ press: SHAFT_FITS.press,
65
+ grip: {
66
+ value: 1.5,
67
+ unit: '× shaft diameter',
68
+ rule: 'The shortest length of bore worth trusting to drive a gear',
69
+ kind: 'community',
70
+ },
43
71
  };
44
72
  const D = (k) => DEFAULTS[k].value;
45
73
 
46
74
  const r3 = (x) => +x.toFixed(3);
47
75
  const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
48
76
  const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
49
- const near = (a, b) => { // edits between two names, to suggest the nearest
77
+ const near = (a, b) => {
78
+ // edits between two names, to suggest the nearest
50
79
  const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
51
80
  for (let j = 1; j <= b.length; j++) d[0][j] = j;
52
- for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
81
+ for (let i = 1; i <= a.length; i++)
82
+ for (let j = 1; j <= b.length; j++)
83
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
53
84
  return d[a.length][b.length];
54
85
  };
55
- function positive(what, k, v) { if (!(isNum(v) && v > 0)) throw new Error(`${what}: ${k} is a number above 0 (got ${shown(v)})`); return v; }
56
- function isModel(what, m) { if (!m || m.kind !== 'motor') throw new Error(`${what}: give a motor's model (motorModel), not ${shown(m)}`); return m; }
86
+ function positive(what, k, v) {
87
+ if (!(isNum(v) && v > 0)) throw new Error(`${what}: ${k} is a number above 0 (got ${shown(v)})`);
88
+ return v;
89
+ }
90
+ function isModel(what, m) {
91
+ if (!m || m.kind !== 'motor') throw new Error(`${what}: give a motor's model (motorModel), not ${shown(m)}`);
92
+ return m;
93
+ }
57
94
 
58
95
  /** @returns {string[]} the names of the motors in the catalogue */
59
96
  export const motors = () => Object.keys(CATALOGUE);
@@ -78,68 +115,177 @@ export const motors = () => Object.keys(CATALOGUE);
78
115
  */
79
116
  export function motorModel(which, change = {}) {
80
117
  const what = 'motorModel';
81
- let set = which, variant = null;
118
+ let set = which,
119
+ variant = null;
82
120
  if (typeof which === 'string') {
83
- const k = key(which), name = ALIASES[k];
121
+ const k = key(which),
122
+ name = ALIASES[k];
84
123
  if (!name) {
85
- const guess = Object.keys(ALIASES).map((a) => [near(k, a), ALIASES[a]]).sort((a, b) => a[0] - b[0])[0];
86
- throw new Error(`${what}: no motor "${which}"${guess && guess[0] <= 3 ? ` (did you mean ${guess[1]}?)` : ''}. There are: ${motors().join(', ')}. For another motor, hand in a rule set of your own in the same names`);
124
+ const guess = Object.keys(ALIASES)
125
+ .map((a) => [near(k, a), ALIASES[a]])
126
+ .sort((a, b) => a[0] - b[0])[0];
127
+ throw new Error(
128
+ `${what}: no motor "${which}"${guess && guess[0] <= 3 ? ` (did you mean ${guess[1]}?)` : ''}. There are: ${motors().join(', ')}. For another motor, hand in a rule set of your own in the same names`,
129
+ );
87
130
  }
88
131
  set = CATALOGUE[name];
89
132
  variant = Object.entries(set.variants || {}).find(([v]) => key(v) === k)?.[1] ?? null;
90
133
  }
91
- if (!set || typeof set !== 'object' || !set.rules) throw new Error(`${what}: give a motor's name (${motors().join(', ')}) or a rule set, not ${shown(which)}`);
134
+ if (!set || typeof set !== 'object' || !set.rules)
135
+ throw new Error(`${what}: give a motor's name (${motors().join(', ')}) or a rule set, not ${shown(which)}`);
92
136
  const figures = Object.fromEntries(Object.entries(set.rules).map(([n, r]) => [n, { ...r }]));
93
- if (variant) for (const [n, value] of Object.entries(variant.values)) figures[n] = { ...figures[n], value, kind: variant.kind, source: variant.source };
137
+ if (variant)
138
+ for (const [n, value] of Object.entries(variant.values))
139
+ figures[n] = { ...figures[n], value, kind: variant.kind, source: variant.source };
94
140
  for (const [n, c] of Object.entries(change)) {
95
- if (!figures[n]) { const guess = Object.keys(figures).map((a) => [near(n, a), a]).sort((a, b) => a[0] - b[0])[0]; throw new Error(`${what}: ${set.name} has no figure "${n}"${guess[0] <= 3 ? ` (did you mean ${guess[1]}?)` : ''}`); }
96
- figures[n] = typeof c === 'object' && c ? { ...figures[n], ...c } : { ...figures[n], value: c, kind: 'given', source: 'given to motorModel' };
141
+ if (!figures[n]) {
142
+ const guess = Object.keys(figures)
143
+ .map((a) => [near(n, a), a])
144
+ .sort((a, b) => a[0] - b[0])[0];
145
+ throw new Error(
146
+ `${what}: ${set.name} has no figure "${n}"${guess[0] <= 3 ? ` (did you mean ${guess[1]}?)` : ''}`,
147
+ );
148
+ }
149
+ figures[n] =
150
+ typeof c === 'object' && c
151
+ ? { ...figures[n], ...c }
152
+ : { ...figures[n], value: c, kind: 'given', source: 'given to motorModel' };
97
153
  if (figures[n].value == null) throw new Error(`${what}: ${n} needs a value (got ${shown(c)})`);
98
154
  }
99
155
  // A gear motor with another gearbox: torque goes up with the ratio and speed down, unless you've given them too
100
156
  if (change.ratio != null && set.rules.ratio && set.rules.stall_torque) {
101
- const k = figures.ratio.value / set.rules.ratio.value, from = `scaled from its ${set.rules.ratio.value}:1 gearbox`;
102
- if (change.stall_torque == null) figures.stall_torque = { ...figures.stall_torque, value: figures.stall_torque.value * k, kind: 'derived', source: from };
103
- if (change.no_load_speed == null) figures.no_load_speed = { ...figures.no_load_speed, value: figures.no_load_speed.value / k, kind: 'derived', source: from };
157
+ const k = figures.ratio.value / set.rules.ratio.value,
158
+ from = `scaled from its ${set.rules.ratio.value}:1 gearbox`;
159
+ if (change.stall_torque == null)
160
+ figures.stall_torque = {
161
+ ...figures.stall_torque,
162
+ value: figures.stall_torque.value * k,
163
+ kind: 'derived',
164
+ source: from,
165
+ };
166
+ if (change.no_load_speed == null)
167
+ figures.no_load_speed = {
168
+ ...figures.no_load_speed,
169
+ value: figures.no_load_speed.value / k,
170
+ kind: 'derived',
171
+ source: from,
172
+ };
104
173
  }
105
174
  const v = (n, fallback) => figures[n]?.value ?? fallback;
106
175
  const type = v('type');
107
- if (!['stepper', 'dc', 'servo', 'brushless'].includes(type)) throw new Error(`${what}: ${set.name}: type is stepper, dc, servo or brushless (got ${shown(type)})`);
108
- const shape = v('body_shape'), round = shape === 'round', width = round ? v('body_diameter') : v('body_width'), depth = round || shape === 'square' ? width : v('body_depth', width);
109
- for (const [k, x] of [['the body\'s width', width], ['the body\'s depth', depth], ['the shaft\'s diameter', v('shaft_diameter')]]) positive(`${what}: ${set.name}`, k, x);
110
- const tab = v('mount_tab_length', 0), off = v('boss_offset', 0), centre = tab ? [-off, 0] : [0, -off];
111
- const top = v('body_top', 0), bossHeight = v('boss_height', 0), base = top ? top + bossHeight : 0, spacing = v('mount_hole_spacing', 0), pattern = v('mount_pattern');
112
- const holes = pattern === 'square' ? [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => [centre[0] + (a * spacing) / 2, centre[1] + (b * spacing) / 2]) : [[centre[0] - spacing / 2, centre[1]], [centre[0] + spacing / 2, centre[1]]];
113
- const shaftLength = v('shaft_length'), tip = base + shaftLength, shaftFlats = v('shaft_flats', 0);
176
+ if (!['stepper', 'dc', 'servo', 'brushless'].includes(type))
177
+ throw new Error(`${what}: ${set.name}: type is stepper, dc, servo or brushless (got ${shown(type)})`);
178
+ const shape = v('body_shape'),
179
+ round = shape === 'round',
180
+ width = round ? v('body_diameter') : v('body_width'),
181
+ depth = round || shape === 'square' ? width : v('body_depth', width);
182
+ for (const [k, x] of [
183
+ ["the body's width", width],
184
+ ["the body's depth", depth],
185
+ ["the shaft's diameter", v('shaft_diameter')],
186
+ ])
187
+ positive(`${what}: ${set.name}`, k, x);
188
+ const tab = v('mount_tab_length', 0),
189
+ off = v('boss_offset', 0),
190
+ centre = tab ? [-off, 0] : [0, -off];
191
+ const top = v('body_top', 0),
192
+ bossHeight = v('boss_height', 0),
193
+ base = top ? top + bossHeight : 0,
194
+ spacing = v('mount_hole_spacing', 0),
195
+ pattern = v('mount_pattern');
196
+ const holes =
197
+ pattern === 'square'
198
+ ? [
199
+ [-1, -1],
200
+ [1, -1],
201
+ [1, 1],
202
+ [-1, 1],
203
+ ].map(([a, b]) => [centre[0] + (a * spacing) / 2, centre[1] + (b * spacing) / 2])
204
+ : [
205
+ [centre[0] - spacing / 2, centre[1]],
206
+ [centre[0] + spacing / 2, centre[1]],
207
+ ];
208
+ const shaftLength = v('shaft_length'),
209
+ tip = base + shaftLength,
210
+ shaftFlats = v('shaft_flats', 0);
114
211
  const m = {
115
- kind: 'motor', name: set.name, type, figures,
212
+ kind: 'motor',
213
+ name: set.name,
214
+ type,
215
+ figures,
116
216
  body: { shape, width, depth, length: v('body_length'), top, corner: v('body_corner', 0), centre },
117
217
  boss: { diameter: v('boss_diameter', 0), height: bossHeight, top: top + bossHeight },
118
- shaft: { diameter: v('shaft_diameter'), length: shaftLength, flats: shaftFlats, across: v('shaft_flat_across', v('shaft_diameter')), flatLength: v('shaft_flat_length', 0), base, tip },
119
- mount: { pattern, spacing, holes, thread: v('mount_hole_thread', null), depth: v('mount_hole_depth', 0), diameter: v('mount_hole_diameter', 0), ear: v('mount_ear_radius', 0), earThickness: v('mount_ear_thickness', 0), tab, tabThickness: v('mount_tab_thickness', 0), side: type === 'servo' ? -1 : 1 },
218
+ shaft: {
219
+ diameter: v('shaft_diameter'),
220
+ length: shaftLength,
221
+ flats: shaftFlats,
222
+ across: v('shaft_flat_across', v('shaft_diameter')),
223
+ flatLength: v('shaft_flat_length', 0),
224
+ base,
225
+ tip,
226
+ },
227
+ mount: {
228
+ pattern,
229
+ spacing,
230
+ holes,
231
+ thread: v('mount_hole_thread', null),
232
+ depth: v('mount_hole_depth', 0),
233
+ diameter: v('mount_hole_diameter', 0),
234
+ ear: v('mount_ear_radius', 0),
235
+ earThickness: v('mount_ear_thickness', 0),
236
+ tab,
237
+ tabThickness: v('mount_tab_thickness', 0),
238
+ side: type === 'servo' ? -1 : 1,
239
+ },
120
240
  cable: { width: v('cable_width', 0), reach: v('cable_reach', 0) },
121
- mass: v('mass', 0), ratio: v('ratio', 1), stepAngle: null, range: v('range', null)
241
+ mass: v('mass', 0),
242
+ ratio: v('ratio', 1),
243
+ stepAngle: null,
244
+ range: v('range', null),
122
245
  };
123
246
  if (type === 'stepper') m.stepAngle = v('step_angle') / m.ratio;
124
247
  // Anchors an assembly places a motor by: the shaft where it leaves the motor, its tip, and the mounting face
125
- m.anchors = { face: { origin: [0, 0, 0], axis: [0, 0, 1] }, connector: { origin: [centre[0], centre[1] + depth / 2, -m.body.length / 2], axis: [0, 1, 0] }, shaft: { origin: [0, 0, base], axis: [0, 0, 1] }, tip: { origin: [0, 0, tip], axis: [0, 0, 1] }, ...(type === 'servo' ? { horn: { origin: [0, 0, tip], axis: [0, 0, 1] } } : {}), ...Object.fromEntries(holes.map((h, i) => [`hole${i + 1}`, { origin: [h[0], h[1], 0], axis: [0, 0, 1] }])) };
248
+ m.anchors = {
249
+ face: { origin: [0, 0, 0], axis: [0, 0, 1] },
250
+ connector: { origin: [centre[0], centre[1] + depth / 2, -m.body.length / 2], axis: [0, 1, 0] },
251
+ shaft: { origin: [0, 0, base], axis: [0, 0, 1] },
252
+ tip: { origin: [0, 0, tip], axis: [0, 0, 1] },
253
+ ...(type === 'servo' ? { horn: { origin: [0, 0, tip], axis: [0, 0, 1] } } : {}),
254
+ ...Object.fromEntries(holes.map((h, i) => [`hole${i + 1}`, { origin: [h[0], h[1], 0], axis: [0, 0, 1] }])),
255
+ };
126
256
  return m;
127
257
  }
128
258
 
129
259
  // ---------- shapes ----------
130
260
  const extrude = (height, pts) => extrudeLinear({ height }, polygon({ points: pts }));
131
261
  const SEG = 48;
132
- const disc = (d, z0, z1, at = [0, 0]) => cylinder({ radius: d / 2, height: z1 - z0, center: [at[0], at[1], (z0 + z1) / 2], segments: SEG });
133
- const box = (x0, x1, y0, y1, z0, z1) => cuboid({ size: [x1 - x0, y1 - y0, z1 - z0], center: [(x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2] });
262
+ const disc = (d, z0, z1, at = [0, 0]) =>
263
+ cylinder({ radius: d / 2, height: z1 - z0, center: [at[0], at[1], (z0 + z1) / 2], segments: SEG });
264
+ const box = (x0, x1, y0, y1, z0, z1) =>
265
+ cuboid({ size: [x1 - x0, y1 - y0, z1 - z0], center: [(x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2] });
134
266
  // A shaft's section with its flats: a circle less the part past each flat, as a closed outline. Two flats: opposite,
135
267
  // across = the distance between; one flat (a D): across = the distance from the flat to the far side of the shaft
136
268
  function dSection(d, flats, across) {
137
- const r = d / 2, y = flats === 2 ? across / 2 : across - r, a0 = Math.asin(y / r), n = 40, pts = [];
269
+ const r = d / 2,
270
+ y = flats === 2 ? across / 2 : across - r,
271
+ a0 = Math.asin(y / r),
272
+ n = 40,
273
+ pts = [];
138
274
  if (flats === 2) {
139
- for (const [from, to] of [[-a0, a0], [Math.PI - a0, Math.PI + a0]]) for (let i = 0; i <= n; i++) { const t = from + ((to - from) * i) / n; pts.push([r * Math.cos(t), r * Math.sin(t)]); }
275
+ for (const [from, to] of [
276
+ [-a0, a0],
277
+ [Math.PI - a0, Math.PI + a0],
278
+ ])
279
+ for (let i = 0; i <= n; i++) {
280
+ const t = from + ((to - from) * i) / n;
281
+ pts.push([r * Math.cos(t), r * Math.sin(t)]);
282
+ }
140
283
  return pts;
141
284
  }
142
- for (let i = 0; i <= n * 2; i++) { const t = Math.PI - a0 + ((Math.PI + 2 * a0) * i) / (n * 2); pts.push([r * Math.cos(t), r * Math.sin(t)]); } // round the far side, from one end of the flat to the other
285
+ for (let i = 0; i <= n * 2; i++) {
286
+ const t = Math.PI - a0 + ((Math.PI + 2 * a0) * i) / (n * 2);
287
+ pts.push([r * Math.cos(t), r * Math.sin(t)]);
288
+ } // round the far side, from one end of the flat to the other
143
289
  return pts;
144
290
  }
145
291
 
@@ -162,42 +308,96 @@ export function motor(m, ops = booleans) {
162
308
  */
163
309
  export function motorParts(m, ops = booleans) {
164
310
  isModel('motor', m);
165
- const { body, boss, shaft, mount: h } = m, [cx, cy] = body.centre, parts = [];
166
- const low = -body.length, high = body.top;
311
+ const { body, boss, shaft, mount: h } = m,
312
+ [cx, cy] = body.centre,
313
+ parts = [];
314
+ const low = -body.length,
315
+ high = body.top;
167
316
  if (body.shape === 'square') {
168
- const w = body.width / 2, c = body.corner;
169
- parts.push(translate([cx, cy, low], extrude(body.length, [[-w + c, -w], [w - c, -w], [w, -w + c], [w, w - c], [w - c, w], [-w + c, w], [-w, w - c], [-w, -w + c]])));
317
+ const w = body.width / 2,
318
+ c = body.corner;
319
+ parts.push(
320
+ translate(
321
+ [cx, cy, low],
322
+ extrude(body.length, [
323
+ [-w + c, -w],
324
+ [w - c, -w],
325
+ [w, -w + c],
326
+ [w, w - c],
327
+ [w - c, w],
328
+ [-w + c, w],
329
+ [-w, w - c],
330
+ [-w, -w + c],
331
+ ]),
332
+ ),
333
+ );
170
334
  } else if (body.shape === 'round') parts.push(disc(body.width, low || 0, high || 0, [cx, cy]));
171
335
  else parts.push(box(cx - body.width / 2, cx + body.width / 2, cy - body.depth / 2, cy + body.depth / 2, low, high));
172
336
  if (h.ear) for (const p of h.holes) parts.push(disc(2 * h.ear, -h.earThickness, 0, p));
173
337
  if (h.ear) parts.push(box(h.holes[0][0], h.holes[1][0], cy - h.ear, cy + h.ear, -h.earThickness, 0));
174
- if (h.tab) parts.push(box(cx - h.tab / 2, cx + h.tab / 2, cy - body.depth / 2, cy + body.depth / 2, 0, h.tabThickness));
338
+ if (h.tab)
339
+ parts.push(box(cx - h.tab / 2, cx + h.tab / 2, cy - body.depth / 2, cy + body.depth / 2, 0, h.tabThickness));
175
340
  if (boss.height) parts.push(disc(boss.diameter, high, high + boss.height));
176
- let solid = ops.union(parts), rod = null;
341
+ let solid = ops.union(parts),
342
+ rod = null;
177
343
  if (m.type === 'brushless') solid = ops.subtract(solid, disc(shaft.diameter, low - 1, high + 1));
178
344
  else if (shaft.length) {
179
- const flatFrom = shaft.flats ? shaft.tip - shaft.flatLength : shaft.tip, rods = [];
345
+ const flatFrom = shaft.flats ? shaft.tip - shaft.flatLength : shaft.tip,
346
+ rods = [];
180
347
  if (flatFrom > shaft.base) rods.push(disc(shaft.diameter, shaft.base, flatFrom));
181
- if (shaft.flats) rods.push(translate([0, 0, Math.max(flatFrom, shaft.base)], extrude(shaft.tip - Math.max(flatFrom, shaft.base), dSection(shaft.diameter, shaft.flats, shaft.across))));
348
+ if (shaft.flats)
349
+ rods.push(
350
+ translate(
351
+ [0, 0, Math.max(flatFrom, shaft.base)],
352
+ extrude(shaft.tip - Math.max(flatFrom, shaft.base), dSection(shaft.diameter, shaft.flats, shaft.across)),
353
+ ),
354
+ );
182
355
  rod = rods.length > 1 ? ops.union(rods) : rods[0];
183
356
  }
184
- if (h.holes.length && h.ear) solid = ops.subtract(solid, h.holes.map((p) => disc(h.diameter, -h.earThickness - 1, 1, p)));
357
+ if (h.holes.length && h.ear)
358
+ solid = ops.subtract(
359
+ solid,
360
+ h.holes.map((p) => disc(h.diameter, -h.earThickness - 1, 1, p)),
361
+ );
185
362
  return { body: solid, shaft: rod };
186
363
  }
187
364
 
188
365
  // The printer's clearances, from its rule set, with a design's own printer laid over them
189
- function printerOf(p) { return { fit: p?.fit ?? x1c.rules.fit.value, holeComp: p?.hole_comp ?? x1c.rules.hole_comp.value, layer: p?.layer ?? x1c.rules.layer.value, line: p?.line ?? x1c.rules.line.value }; }
366
+ function printerOf(p) {
367
+ return {
368
+ fit: p?.fit ?? x1c.rules.fit.value,
369
+ holeComp: p?.hole_comp ?? x1c.rules.hole_comp.value,
370
+ layer: p?.layer ?? x1c.rules.layer.value,
371
+ line: p?.line ?? x1c.rules.line.value,
372
+ };
373
+ }
190
374
  const an = (thread) => `${/^(M|8-)/.test(thread) ? 'an' : 'a'} ${thread}`;
191
375
  // The screw that holds a motor, from @rulecad/fixings: on the thread its holes are tapped (a stepper's face), else the
192
376
  // one asked for, else the size its plain holes take. A screw asked for by its whole name ('M3x8 cap') brings its length
193
377
  // and head; a thread alone ('M3') is a cap screw, its length worked out from the plate
194
378
  function screwOf(what, m, said) {
195
- const h = m.mount, made = (name) => { try { return fixingModel(name, {}, { anyLength: true }); } catch (e) { throw new Error(`${what}: ${String(e.message).replace(/^fixingModel: /, '')}`); } };
196
- if (said != null && (typeof said !== 'string' || !said.trim())) throw new Error(`${what}: screw is a screw's name ('M3', or 'M3x8 cap' with its length and head), not ${shown(said)}`);
379
+ const h = m.mount,
380
+ made = (name) => {
381
+ try {
382
+ return fixingModel(name, {}, { anyLength: true });
383
+ } catch (e) {
384
+ throw new Error(`${what}: ${String(e.message).replace(/^fixingModel: /, '')}`);
385
+ }
386
+ };
387
+ if (said != null && (typeof said !== 'string' || !said.trim()))
388
+ throw new Error(
389
+ `${what}: screw is a screw's name ('M3', or 'M3x8 cap' with its length and head), not ${shown(said)}`,
390
+ );
197
391
  const asked = said == null ? null : made(said);
198
- if (asked && asked.item !== 'thread' && asked.item !== 'screw') throw new Error(`${what}: screw is a screw's name ('M3', or 'M3x8 cap' with its length and head), and "${said}" is ${asked.item === 'insert' ? 'an' : 'a'} ${asked.item}`);
392
+ if (asked && asked.item !== 'thread' && asked.item !== 'screw')
393
+ throw new Error(
394
+ `${what}: screw is a screw's name ('M3', or 'M3x8 cap' with its length and head), and "${said}" is ${asked.item === 'insert' ? 'an' : 'a'} ${asked.item}`,
395
+ );
199
396
  const thread = h.thread ?? asked?.thread ?? (h.diameter >= 4 ? 'M4' : h.diameter >= 3 ? 'M3' : 'M2');
200
- if (h.thread && asked && asked.thread !== h.thread) throw new Error(`${what}: ${m.name}'s holes are tapped ${h.thread} (${m.name}.mount_hole_thread), so ${an(asked.thread)} screw does not go in them: give ${h.thread}, or leave screw out`);
397
+ if (h.thread && asked && asked.thread !== h.thread)
398
+ throw new Error(
399
+ `${what}: ${m.name}'s holes are tapped ${h.thread} (${m.name}.mount_hole_thread), so ${an(asked.thread)} screw does not go in them: give ${h.thread}, or leave screw out`,
400
+ );
201
401
  if (!threads().includes(thread)) throw new Error(`${what}: no screw "${thread}" (${threads().join(', ')})`);
202
402
  return asked?.item === 'screw' ? asked : made(`${thread} cap`);
203
403
  }
@@ -226,35 +426,111 @@ const LIP = 0.1;
226
426
  export function mountModel(m, p) {
227
427
  const what = 'mount';
228
428
  isModel(what, m);
229
- if (!p || typeof p !== 'object') throw new Error(`${what}: give the part's { plate } (its thickness at the mount, mm), not ${shown(p)}`);
230
- const plate = positive(what, 'plate', p.plate), pr = printerOf(p.printer), { mount: h, boss, shaft } = m, out = [], f = (level, text, code, extra = {}) => out.push({ level, text, code, ...extra });
231
- const fx = screwOf(what, m, p.screw), thread = fx.thread, d = fx.major, values = { fit: pr.fit, hole_comp: pr.holeComp, layer: pr.layer };
232
- const clear = holeModel(fx, { kind: 'clearance', printer: values }), seat = p.counterbore ? counterboreModel(fx, { printer: values }) : null;
233
- const screw = { thread, name: fx.name, clearance: clear.nominal, head: fx.head.across, headHeight: fx.head.height, model: fx };
234
- const pocket = boss.diameter ? boss.diameter + 2 * pr.fit + pr.holeComp : 0, pocketDepth = boss.height ? boss.height + 2 * pr.layer : 0;
429
+ if (!p || typeof p !== 'object')
430
+ throw new Error(`${what}: give the part's { plate } (its thickness at the mount, mm), not ${shown(p)}`);
431
+ const plate = positive(what, 'plate', p.plate),
432
+ pr = printerOf(p.printer),
433
+ { mount: h, boss, shaft } = m,
434
+ out = [],
435
+ f = (level, text, code, extra = {}) => out.push({ level, text, code, ...extra });
436
+ const fx = screwOf(what, m, p.screw),
437
+ thread = fx.thread,
438
+ d = fx.major,
439
+ values = { fit: pr.fit, hole_comp: pr.holeComp, layer: pr.layer };
440
+ const clear = holeModel(fx, { kind: 'clearance', printer: values }),
441
+ seat = p.counterbore ? counterboreModel(fx, { printer: values }) : null;
442
+ const screw = {
443
+ thread,
444
+ name: fx.name,
445
+ clearance: clear.nominal,
446
+ head: fx.head.across,
447
+ headHeight: fx.head.height,
448
+ model: fx,
449
+ };
450
+ const pocket = boss.diameter ? boss.diameter + 2 * pr.fit + pr.holeComp : 0,
451
+ pocketDepth = boss.height ? boss.height + 2 * pr.layer : 0;
235
452
  const shaftHole = shaft.diameter + 2 * pr.fit + pr.holeComp + 0.4;
236
453
  const holeD = m.type === 'servo' ? h.diameter - 0.4 + pr.holeComp : clear.diameter;
237
454
  const head = seat ? seat.diameter : null;
238
- if (pocketDepth >= plate && m.mount.side === 1) f('fail', `the plate is ${plate} mm thick and the boss's pocket ${pocketDepth} mm deep: it needs to be thicker than that, or it's only a hole`, 'mount.plate');
455
+ if (pocketDepth >= plate && m.mount.side === 1)
456
+ f(
457
+ 'fail',
458
+ `the plate is ${plate} mm thick and the boss's pocket ${pocketDepth} mm deep: it needs to be thicker than that, or it's only a hole`,
459
+ 'mount.plate',
460
+ );
239
461
  const thickest = h.thread ? h.depth : 0;
240
462
  // a screw's length: through the plate, into the thread, its head sunk or not; or the one asked for
241
463
  const under = plate - (p.counterbore ? screw.headHeight : 0);
242
- const screwLength = fx.length ?? (h.thread ? Math.floor(under + Math.min(thickest, 2.5 * d)) : Math.ceil(plate + (h.earThickness || h.tabThickness) + 2));
243
- if (m.mount.side === 1 && h.thread && under + thickest < screwLength) f('warn', `an ${thread} × ${screwLength} would bottom out in the motor's ${thickest} mm of thread`, 'mount.screw');
244
- if (plate < 1.5 * d) f('warn', `a ${plate} mm plate is thin for ${thread} screws: at least ${1.5 * d} mm, or the head pulls through`, 'mount.plate');
464
+ const screwLength =
465
+ fx.length ??
466
+ (h.thread
467
+ ? Math.floor(under + Math.min(thickest, 2.5 * d))
468
+ : Math.ceil(plate + (h.earThickness || h.tabThickness) + 2));
469
+ if (m.mount.side === 1 && h.thread && under + thickest < screwLength)
470
+ f('warn', `an ${thread} × ${screwLength} would bottom out in the motor's ${thickest} mm of thread`, 'mount.screw');
471
+ if (plate < 1.5 * d)
472
+ f(
473
+ 'warn',
474
+ `a ${plate} mm plate is thin for ${thread} screws: at least ${1.5 * d} mm, or the head pulls through`,
475
+ 'mount.plate',
476
+ );
245
477
  // the screw's thread in the motor's: what passes the plate, up to the depth the motor is tapped
246
478
  let engaged = null;
247
479
  if (m.mount.side === 1 && h.thread && thickest > 0) {
248
480
  engaged = +Math.max(0, Math.min(screwLength - under, thickest)).toFixed(3);
249
- const least = +(LEAST.value * d).toFixed(3), n = h.holes.length, name = `${thread}x${+screwLength.toFixed(3)} ${fx.head.form}`, depthRule = `${m.name}.mount_hole_depth`;
250
- const lengths = fx.figures.lengths?.value ?? [], fits = [...lengths].reverse().find((L) => L - under <= thickest + 1e-9 && L - under >= least - 1e-9);
251
- const dia = (x) => `${+x.toFixed(2)} diameter${+x.toFixed(2) === 1 ? '' : 's'}`, An = an(thread).replace(/^a/, 'A'), fix = fits ? ` ${An}x${fits} ${fx.head.form} would engage ${+(fits - under).toFixed(3)} mm` : ` No length sold reaches ${least} mm of thread and stops short of the motor's ${thickest} mm: a ${p.counterbore ? 'deeper counterbore' : 'counterbore'} or a thinner plate at the screws`;
252
- const said = `${n} ${name} screw${n > 1 ? 's' : ''} through ${+under.toFixed(3)} mm of plate`, vals = { values: { engaged, depth: thickest, least, length: screwLength, under: +under.toFixed(3), count: n }, refs: { screw: name, rule: depthRule, least: 'engagement.steel', kind: LEAST.kind } };
253
- if (screwLength - under <= 1e-9) f('fail', `${said} do not reach the motor's thread: ${name} ends ${under - screwLength > 1e-9 ? `${+(under - screwLength).toFixed(3)} mm short of` : 'at'} its face.${fix}`, 'mount.engagement', vals);
254
- else if (engaged < least - 1e-9) f('fail', `${said} engage ${engaged} mm of the motor's ${thickest} mm of ${thread} thread (${depthRule}), ${dia(engaged / d)}: less than the ${least} mm (engagement.steel, ${LEAST.value} diameter, the least any metal is given), so the thread strips before the screw holds.${fix}`, 'mount.engagement', vals);
255
- else f('pass', `${said} engage ${engaged} mm of the motor's ${thickest} mm of ${thread} thread (${depthRule}), ${dia(engaged / d)}, at least the ${least} mm engagement.steel gives any metal`, 'mount.engagement', vals);
481
+ const least = +(LEAST.value * d).toFixed(3),
482
+ n = h.holes.length,
483
+ name = `${thread}x${+screwLength.toFixed(3)} ${fx.head.form}`,
484
+ depthRule = `${m.name}.mount_hole_depth`;
485
+ const lengths = fx.figures.lengths?.value ?? [],
486
+ fits = [...lengths].reverse().find((L) => L - under <= thickest + 1e-9 && L - under >= least - 1e-9);
487
+ const dia = (x) => `${+x.toFixed(2)} diameter${+x.toFixed(2) === 1 ? '' : 's'}`,
488
+ An = an(thread).replace(/^a/, 'A'),
489
+ fix = fits
490
+ ? ` ${An}x${fits} ${fx.head.form} would engage ${+(fits - under).toFixed(3)} mm`
491
+ : ` No length sold reaches ${least} mm of thread and stops short of the motor's ${thickest} mm: a ${p.counterbore ? 'deeper counterbore' : 'counterbore'} or a thinner plate at the screws`;
492
+ const said = `${n} ${name} screw${n > 1 ? 's' : ''} through ${+under.toFixed(3)} mm of plate`,
493
+ vals = {
494
+ values: { engaged, depth: thickest, least, length: screwLength, under: +under.toFixed(3), count: n },
495
+ refs: { screw: name, rule: depthRule, least: 'engagement.steel', kind: LEAST.kind },
496
+ };
497
+ if (screwLength - under <= 1e-9)
498
+ f(
499
+ 'fail',
500
+ `${said} do not reach the motor's thread: ${name} ends ${under - screwLength > 1e-9 ? `${+(under - screwLength).toFixed(3)} mm short of` : 'at'} its face.${fix}`,
501
+ 'mount.engagement',
502
+ vals,
503
+ );
504
+ else if (engaged < least - 1e-9)
505
+ f(
506
+ 'fail',
507
+ `${said} engage ${engaged} mm of the motor's ${thickest} mm of ${thread} thread (${depthRule}), ${dia(engaged / d)}: less than the ${least} mm (engagement.steel, ${LEAST.value} diameter, the least any metal is given), so the thread strips before the screw holds.${fix}`,
508
+ 'mount.engagement',
509
+ vals,
510
+ );
511
+ else
512
+ f(
513
+ 'pass',
514
+ `${said} engage ${engaged} mm of the motor's ${thickest} mm of ${thread} thread (${depthRule}), ${dia(engaged / d)}, at least the ${least} mm engagement.steel gives any metal`,
515
+ 'mount.engagement',
516
+ vals,
517
+ );
256
518
  }
257
- return { plate, side: h.side, pocket: r3(pocket), pocketDepth: r3(pocketDepth), shaftHole: r3(shaftHole), holes: h.holes.map((at) => ({ at, diameter: r3(holeD) })), screw, screwLength, head, recess: p.recess ?? 0, engaged, printer: pr, findings: out };
519
+ return {
520
+ plate,
521
+ side: h.side,
522
+ pocket: r3(pocket),
523
+ pocketDepth: r3(pocketDepth),
524
+ shaftHole: r3(shaftHole),
525
+ holes: h.holes.map((at) => ({ at, diameter: r3(holeD) })),
526
+ screw,
527
+ screwLength,
528
+ head,
529
+ recess: p.recess ?? 0,
530
+ engaged,
531
+ printer: pr,
532
+ findings: out,
533
+ };
258
534
  }
259
535
 
260
536
  /**
@@ -267,25 +543,66 @@ export function mountModel(m, p) {
267
543
  * @returns {object} a JSCAD solid to subtract
268
544
  */
269
545
  export function mount(m, p, ops = booleans) {
270
- const g = mountModel(m, p), { plate, pocket, pocketDepth, shaftHole, holes, recess, printer: pr } = g, { body } = m, [cx, cy] = body.centre, cuts = [], over = 0.5;
546
+ const g = mountModel(m, p),
547
+ { plate, pocket, pocketDepth, shaftHole, holes, recess, printer: pr } = g,
548
+ { body } = m,
549
+ [cx, cy] = body.centre,
550
+ cuts = [],
551
+ over = 0.5;
271
552
  if (m.type === 'servo') {
272
553
  // the body through a slot, with the fit all round; the screws' pilot holes in the plate
273
- cuts.push(box(cx - body.width / 2 - pr.fit, cx + body.width / 2 + pr.fit, cy - body.depth / 2 - pr.fit, cy + body.depth / 2 + pr.fit, -plate - over, over));
554
+ cuts.push(
555
+ box(
556
+ cx - body.width / 2 - pr.fit,
557
+ cx + body.width / 2 + pr.fit,
558
+ cy - body.depth / 2 - pr.fit,
559
+ cy + body.depth / 2 + pr.fit,
560
+ -plate - over,
561
+ over,
562
+ ),
563
+ );
274
564
  for (const x of holes) cuts.push(disc(x.diameter, -plate - over, over, x.at));
275
565
  return ops.union(cuts);
276
566
  }
277
567
  if (pocket && pocketDepth) cuts.push(disc(pocket, -over, pocketDepth));
278
568
  cuts.push(disc(shaftHole, -over, plate + over));
279
569
  // each screw's hole down through the plate, from over its top face to under the motor's, its head's seat at the top
280
- const values = { fit: pr.fit, hole_comp: pr.holeComp, layer: pr.layer }, top = plate + over - LIP, length = plate + 2 * (over - LIP), fx = g.screw.model;
570
+ const values = { fit: pr.fit, hole_comp: pr.holeComp, layer: pr.layer },
571
+ top = plate + over - LIP,
572
+ length = plate + 2 * (over - LIP),
573
+ fx = g.screw.model;
281
574
  for (const x of holes) {
282
575
  const at = [x.at[0], x.at[1], top];
283
- cuts.push(g.head ? counterbore(fx, { printer: values, at, depth: g.screw.headHeight + over - LIP, length, into: '-z' }) : hole(fx, { kind: 'clearance', printer: values, at, depth: length, into: '-z' }));
576
+ cuts.push(
577
+ g.head
578
+ ? counterbore(fx, { printer: values, at, depth: g.screw.headHeight + over - LIP, length, into: '-z' })
579
+ : hole(fx, { kind: 'clearance', printer: values, at, depth: length, into: '-z' }),
580
+ );
284
581
  }
285
582
  if (recess) {
286
583
  if (body.shape === 'round') cuts.push(disc(body.width + 2 * pr.fit + pr.holeComp, -recess - over, 0, [cx, cy]));
287
- else cuts.push(box(cx - body.width / 2 - pr.fit, cx + body.width / 2 + pr.fit, cy - body.depth / 2 - pr.fit, cy + body.depth / 2 + pr.fit, -recess - over, 0));
288
- if (m.cable.width) cuts.push(box(cx - m.cable.width / 2 - pr.fit, cx + m.cable.width / 2 + pr.fit, cy - (m.cable.reach || body.depth / 2 + 8), cy, -recess - over, 0));
584
+ else
585
+ cuts.push(
586
+ box(
587
+ cx - body.width / 2 - pr.fit,
588
+ cx + body.width / 2 + pr.fit,
589
+ cy - body.depth / 2 - pr.fit,
590
+ cy + body.depth / 2 + pr.fit,
591
+ -recess - over,
592
+ 0,
593
+ ),
594
+ );
595
+ if (m.cable.width)
596
+ cuts.push(
597
+ box(
598
+ cx - m.cable.width / 2 - pr.fit,
599
+ cx + m.cable.width / 2 + pr.fit,
600
+ cy - (m.cable.reach || body.depth / 2 + 8),
601
+ cy,
602
+ -recess - over,
603
+ 0,
604
+ ),
605
+ );
289
606
  }
290
607
  return ops.union(cuts);
291
608
  }
@@ -298,21 +615,60 @@ export function mount(m, p, ops = booleans) {
298
615
  * flatFrom: the height in the bore where the flat starts (the shaft's tip end is at depth); below it the bore is round, so the round root of the shaft can pass
299
616
  */
300
617
  export function boreModel(m, p) {
301
- const what = 'bore'; isModel(what, m);
618
+ const what = 'bore';
619
+ isModel(what, m);
302
620
  if (!p || typeof p !== 'object') throw new Error(`${what}: give the bore's { depth } in mm, not ${shown(p)}`);
303
- const depth = positive(what, 'depth', p.depth), fit = p.fit ?? 'slide';
621
+ const depth = positive(what, 'depth', p.depth),
622
+ fit = p.fit ?? 'slide';
304
623
  if (!['slide', 'press'].includes(fit)) throw new Error(`${what}: fit is slide or press (got ${shown(fit)})`);
305
- if (m.type === 'servo' || m.type === 'brushless') throw new Error(`${what}: a ${m.type}'s output is ${m.type === 'servo' ? 'a spline finer than a printer draws: drive it through its horn' : 'its bell: bolt to that'}, not a bore`);
624
+ if (m.type === 'servo' || m.type === 'brushless')
625
+ throw new Error(
626
+ `${what}: a ${m.type}'s output is ${m.type === 'servo' ? 'a spline finer than a printer draws: drive it through its horn' : 'its bell: bolt to that'}, not a bore`,
627
+ );
306
628
  const tip = p.tip ?? depth;
307
- if (!(isNum(tip) && tip > 0)) throw new Error(`${what}: tip is how far from the bore's mouth the shaft's tip sits, above 0 (got ${shown(p.tip)})`);
308
- const pr = printerOf(p.printer), { shaft } = m, each = fit === 'slide' ? D('fit') : D('press'), diameter = shaft.diameter + 2 * each + pr.holeComp, flatFrom = Math.max(0, tip - shaft.flatLength), flat = Math.max(0, Math.min(depth, tip) - flatFrom);
309
- const out = [], f = (level, text, code) => out.push({ level, text, code });
310
- if (depth > shaft.length) f('warn', `the bore is ${depth} mm deep and the shaft only ${shaft.length} mm long: the last ${+(depth - shaft.length).toFixed(2)} mm holds nothing`, 'bore.depth');
311
- const grip = Math.min(depth, shaft.length), want = shaft.flats ? Math.min(D('grip') * shaft.diameter, 0.8 * shaft.flatLength) : D('grip') * shaft.diameter;
312
- if (grip < want) f('warn', `only ${+grip.toFixed(2)} mm of the shaft is in the bore: ${r3(want)} mm or more, or the part rocks on it`, 'bore.grip');
313
- if (shaft.flats && flat < 0.5 * want) f('warn', `only ${+flat.toFixed(2)} mm of bore meets the flat: it's the flat that turns the part`, 'bore.flat');
629
+ if (!(isNum(tip) && tip > 0))
630
+ throw new Error(
631
+ `${what}: tip is how far from the bore's mouth the shaft's tip sits, above 0 (got ${shown(p.tip)})`,
632
+ );
633
+ const pr = printerOf(p.printer),
634
+ { shaft } = m,
635
+ b = shaftBore(shaft.diameter, {
636
+ fit,
637
+ across: shaft.across,
638
+ printer: { hole_comp: pr.holeComp, fit: pr.fit },
639
+ what,
640
+ }),
641
+ flatFrom = Math.max(0, tip - shaft.flatLength),
642
+ flat = Math.max(0, Math.min(depth, tip) - flatFrom);
643
+ const out = [],
644
+ f = (level, text, code) => out.push({ level, text, code });
645
+ if (depth > shaft.length)
646
+ f(
647
+ 'warn',
648
+ `the bore is ${depth} mm deep and the shaft only ${shaft.length} mm long: the last ${+(depth - shaft.length).toFixed(2)} mm holds nothing`,
649
+ 'bore.depth',
650
+ );
651
+ const grip = Math.min(depth, shaft.length),
652
+ want = shaft.flats ? Math.min(D('grip') * shaft.diameter, 0.8 * shaft.flatLength) : D('grip') * shaft.diameter;
653
+ if (grip < want)
654
+ f(
655
+ 'warn',
656
+ `only ${+grip.toFixed(2)} mm of the shaft is in the bore: ${r3(want)} mm or more, or the part rocks on it`,
657
+ 'bore.grip',
658
+ );
659
+ if (shaft.flats && flat < 0.5 * want)
660
+ f('warn', `only ${+flat.toFixed(2)} mm of bore meets the flat: it's the flat that turns the part`, 'bore.flat');
314
661
  if (!shaft.flats) f('warn', 'this shaft has no flat: only friction or a grub screw turns the part', 'bore.flat');
315
- return { depth, diameter: r3(diameter), across: r3(shaft.across + 2 * each + pr.holeComp), flats: shaft.flats, flatFrom, grip, fit, findings: out };
662
+ return {
663
+ depth,
664
+ diameter: r3(b.diameter),
665
+ across: r3(b.across),
666
+ flats: shaft.flats,
667
+ flatFrom,
668
+ grip,
669
+ fit,
670
+ findings: out,
671
+ };
316
672
  }
317
673
 
318
674
  /**
@@ -322,20 +678,40 @@ export function boreModel(m, p) {
322
678
  * @param {{ union: Function, subtract: Function }} [ops] @returns {object} a JSCAD solid to subtract
323
679
  */
324
680
  export function bore(m, p, ops = booleans) {
325
- const b = boreModel(m, p), parts = [], over = 0.5;
681
+ const b = boreModel(m, p),
682
+ parts = [],
683
+ over = 0.5;
326
684
  if (b.flatFrom > 0) parts.push(disc(b.diameter, -over, b.flatFrom + 0.001));
327
- if (b.flats) parts.push(translate([0, 0, b.flatFrom > 0 ? b.flatFrom : -over], extrude(b.depth - (b.flatFrom > 0 ? b.flatFrom : -over) + over, dSection(b.diameter, b.flats, b.across))));
685
+ if (b.flats)
686
+ parts.push(
687
+ translate(
688
+ [0, 0, b.flatFrom > 0 ? b.flatFrom : -over],
689
+ extrude(b.depth - (b.flatFrom > 0 ? b.flatFrom : -over) + over, dSection(b.diameter, b.flats, b.across)),
690
+ ),
691
+ );
328
692
  else parts.push(disc(b.diameter, -over, b.depth + over));
329
693
  return parts.length > 1 ? ops.union(parts) : parts[0];
330
694
  }
331
695
 
332
696
  /** A motor is bought, so a part list can't print one. @param {Motor} m @returns {{ level: 'fail', text: string, code: string }[]} */
333
- export function printable(m) { isModel('printable', m); return [{ level: 'fail', text: `${m.name} is a motor: it's bought and fitted, not printed`, code: 'motor.printable' }]; }
697
+ export function printable(m) {
698
+ isModel('printable', m);
699
+ return [
700
+ { level: 'fail', text: `${m.name} is a motor: it's bought and fitted, not printed`, code: 'motor.printable' },
701
+ ];
702
+ }
334
703
 
335
704
  // ---------- what it does ----------
336
705
  const fig = (x, d = 3) => String(+x.toFixed(d));
337
706
  // A figure's value, and note how far it is trusted
338
- function used(m, names, rests) { return names.map((n) => { const f = m.figures[n]; if (f == null) throw new Error(`performance: ${m.name} has no ${n}: give it to motorModel`); rests.add(f.kind); return f.value; }); }
707
+ function used(m, names, rests) {
708
+ return names.map((n) => {
709
+ const f = m.figures[n];
710
+ if (f == null) throw new Error(`performance: ${m.name} has no ${n}: give it to motorModel`);
711
+ rests.add(f.kind);
712
+ return f.value;
713
+ });
714
+ }
339
715
 
340
716
  /**
341
717
  * The torque and speed at the output, at a speed, through a ratio: what an assembly asks of its motor.
@@ -346,39 +722,74 @@ function used(m, names, rests) { return names.map((n) => { const f = m.figures[n
346
722
  * limit: the fastest the output can go; rests: the kinds of figure the answer rests on
347
723
  */
348
724
  export function performance(m, p = {}) {
349
- const what = 'performance'; isModel(what, m);
350
- const speed = p.speed ?? 0, ratio = p.ratio ?? 1, efficiency = p.efficiency ?? 1;
351
- if (!(isNum(speed) && speed >= 0)) throw new Error(`${what}: speed is the output's, in rpm, 0 or more (got ${shown(speed)})`);
352
- if (!(isNum(ratio) && ratio > 0)) throw new Error(`${what}: ratio is input turns per output turn, above 0 (got ${shown(ratio)})`);
353
- if (!(isNum(efficiency) && efficiency > 0 && efficiency <= 1)) throw new Error(`${what}: efficiency is from 0 to 1 (got ${shown(efficiency)})`);
354
- const n = speed * ratio, rests = new Set(), out = [], f = (level, text, code) => out.push({ level, text, code });
725
+ const what = 'performance';
726
+ isModel(what, m);
727
+ const speed = p.speed ?? 0,
728
+ ratio = p.ratio ?? 1,
729
+ efficiency = p.efficiency ?? 1;
730
+ if (!(isNum(speed) && speed >= 0))
731
+ throw new Error(`${what}: speed is the output's, in rpm, 0 or more (got ${shown(speed)})`);
732
+ if (!(isNum(ratio) && ratio > 0))
733
+ throw new Error(`${what}: ratio is input turns per output turn, above 0 (got ${shown(ratio)})`);
734
+ if (!(isNum(efficiency) && efficiency > 0 && efficiency <= 1))
735
+ throw new Error(`${what}: efficiency is from 0 to 1 (got ${shown(efficiency)})`);
736
+ const n = speed * ratio,
737
+ rests = new Set(),
738
+ out = [],
739
+ f = (level, text, code) => out.push({ level, text, code });
355
740
  let torque, limit, how;
356
741
  if (m.type === 'stepper' && m.figures.pull_in_torque) {
357
742
  // A geared stepper: its pull-in torque, up to the fastest it starts; figures are at its own output
358
743
  const [T, rate, step, gear] = used(m, ['pull_in_torque', 'step_rate', 'step_angle', 'ratio'], rests);
359
- const steps = (360 / step) * gear; limit = (rate / steps) * 60; torque = T;
744
+ const steps = (360 / step) * gear;
745
+ limit = (rate / steps) * 60;
746
+ torque = T;
360
747
  how = `pull-in torque, to its ${fig(limit, 2)} rpm`;
361
748
  } else if (m.type === 'stepper') {
362
- const [hold, L, I] = used(m, ['holding_torque', 'inductance', 'rated_current'], rests), [step] = used(m, ['step_angle'], rests), V = p.supply ?? p.volts ?? D('supply');
363
- positive(what, 'supply', V); rests.add(DEFAULTS.running.kind);
749
+ const [hold, L, I] = used(m, ['holding_torque', 'inductance', 'rated_current'], rests),
750
+ [step] = used(m, ['step_angle'], rests),
751
+ V = p.supply ?? p.volts ?? D('supply');
752
+ positive(what, 'supply', V);
753
+ rests.add(DEFAULTS.running.kind);
364
754
  // Flat until the windings can no longer reach full current in a step (corner speed), then constant power
365
- const fullSteps = 360 / step, corner = (60 * V) / (2 * (L / 1000) * I * fullSteps), T0 = hold * D('running');
366
- limit = 5 * corner; torque = n <= corner ? T0 : (T0 * corner) / n;
755
+ const fullSteps = 360 / step,
756
+ corner = (60 * V) / (2 * (L / 1000) * I * fullSteps),
757
+ T0 = hold * D('running');
758
+ limit = 5 * corner;
759
+ torque = n <= corner ? T0 : (T0 * corner) / n;
367
760
  how = `${fig(D('running'), 2)} of holding torque, flat to ${fig(corner, 0)} rpm at ${V} V, then falling as 1/speed (no curve for this motor: measure yours)`;
368
761
  } else if (m.type === 'dc') {
369
762
  const [stall, free] = used(m, ['stall_torque', 'no_load_speed'], rests);
370
- limit = free; torque = Math.max(0, stall * (1 - n / free));
763
+ limit = free;
764
+ torque = Math.max(0, stall * (1 - n / free));
371
765
  how = `the straight line from ${fig(stall)} N m stalled to ${fig(free, 0)} rpm free`;
372
766
  } else if (m.type === 'servo') {
373
767
  const [stall, s60, range] = used(m, ['stall_torque', 'speed_60', 'range'], rests);
374
- limit = (60 / s60) / 6; torque = stall; // deg per second to rpm
768
+ limit = 60 / s60 / 6;
769
+ torque = stall; // deg per second to rpm
375
770
  how = `rated stall torque, within its ${range}° at up to ${fig(limit, 0)} rpm`;
376
771
  } else {
377
772
  const [kv, I, V] = used(m, ['kv', 'rated_current', 'rated_voltage'], rests);
378
- const kt = 60 / (2 * Math.PI * kv); limit = kv * V; torque = n <= limit ? kt * I : 0;
773
+ const kt = 60 / (2 * Math.PI * kv);
774
+ limit = kv * V;
775
+ torque = n <= limit ? kt * I : 0;
379
776
  how = `torque constant ${fig(kt, 4)} N m/A (60 / 2π Kv) at ${I} A`;
380
777
  }
381
- if (n > limit) f('fail', `${fig(speed, 2)} rpm at the output is ${fig(n, 1)} rpm at the motor, past its ${fig(limit, 1)} rpm: more ratio makes it worse, less helps`, 'motor.speed');
778
+ if (n > limit)
779
+ f(
780
+ 'fail',
781
+ `${fig(speed, 2)} rpm at the output is ${fig(n, 1)} rpm at the motor, past its ${fig(limit, 1)} rpm: more ratio makes it worse, less helps`,
782
+ 'motor.speed',
783
+ );
382
784
  const motorTorque = n > limit ? 0 : torque;
383
- return { output: { torque: motorTorque * ratio * efficiency, speed }, motor: { torque: motorTorque, speed: n }, limit: limit / ratio, ratio, efficiency, rests: [...rests], how, findings: out };
785
+ return {
786
+ output: { torque: motorTorque * ratio * efficiency, speed },
787
+ motor: { torque: motorTorque, speed: n },
788
+ limit: limit / ratio,
789
+ ratio,
790
+ efficiency,
791
+ rests: [...rests],
792
+ how,
793
+ findings: out,
794
+ };
384
795
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/motors",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "Motors for printed machines: steppers, DC gear motors, servos and brushless motors from their datasheets, as models with sourced figures, solids to place in an assembly, the mounts and D-bores a part takes for them, and what torque and speed reach the output.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -15,24 +15,45 @@
15
15
  },
16
16
  "types": "./motors.d.mts",
17
17
  "files": [
18
- "motors.mjs",
19
- "diagram.mjs",
20
- "drivers.mjs",
21
- "drivers.d.mts",
22
- "motors.d.mts",
23
- "diagram.d.mts",
18
+ "*.mjs",
19
+ "*.d.mts",
24
20
  "README.md",
25
21
  "CHANGELOG.md",
26
- "LICENSE"
22
+ "LICENSE",
23
+ "!test.mjs"
27
24
  ],
28
25
  "license": "MIT",
29
- "keywords": ["jscad", "3d-printing", "motors", "stepper", "servo", "nema17", "cad"],
30
- "engines": { "node": ">=20.10" },
26
+ "keywords": [
27
+ "jscad",
28
+ "3d-printing",
29
+ "motors",
30
+ "stepper",
31
+ "servo",
32
+ "nema17",
33
+ "cad"
34
+ ],
35
+ "engines": {
36
+ "node": ">=22.13"
37
+ },
31
38
  "sideEffects": false,
32
- "repository": { "type": "git", "url": "git+https://github.com/JoniBach/rulecad.git", "directory": "packages/motors" },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/JoniBach/rulecad.git",
42
+ "directory": "packages/motors"
43
+ },
33
44
  "homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/motors#readme",
34
- "bugs": { "url": "https://github.com/JoniBach/rulecad/issues" },
35
- "scripts": { "test": "node --test" },
36
- "peerDependencies": { "@jscad/modeling": "^2.12.0" },
37
- "dependencies": { "@rulecad/rules": "^0.3.11", "@rulecad/fixings": "^0.1.3" }
45
+ "bugs": {
46
+ "url": "https://github.com/JoniBach/rulecad/issues"
47
+ },
48
+ "scripts": {
49
+ "test": "node --test"
50
+ },
51
+ "peerDependencies": {
52
+ "@jscad/modeling": "^2.12.0"
53
+ },
54
+ "dependencies": {
55
+ "@rulecad/rules": "^0.4.0",
56
+ "@rulecad/fixings": "^0.2.0",
57
+ "@rulecad/shapes": "^0.5.0"
58
+ }
38
59
  }