@rulecad/motors 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JoniBach and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,102 @@
1
- # Temporary Holding Version
1
+ # @rulecad/motors
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Motors for printed machines. A stepper, a DC gear motor, a servo or a brushless motor comes back from its name as a
4
+ model (every figure with how far to trust it and where it comes from), a solid to place in an assembly, the shape a
5
+ part subtracts to hold it, and the bore a gear takes for its shaft. One function answers what a design asks of a motor:
6
+ at this speed, through this ratio, what torque reaches the output? Its figures live in
7
+ [`@rulecad/rules`](https://github.com/JoniBach/rulecad/tree/main/packages/rules) as open data, and this package holds no
8
+ numbers of its own for any motor. Needs JSCAD. Part of [rulecad](https://github.com/JoniBach/rulecad).
9
+
10
+ ```js
11
+ import { motorModel, motor, mount, mountModel, bore, boreModel, performance } from '@rulecad/motors';
12
+
13
+ const m = motorModel('nema17'); // or '17HS4401', '28BYJ-48', 'sg90', …
14
+ console.log(m.type, m.shaft.diameter, m.mount.spacing, m.figures.holding_torque.value, m.figures.holding_torque.kind);
15
+
16
+ const held = mountModel(m, { plate: 5 }); // what a 5 mm plate needs to hold it
17
+ console.log(held.pocket, held.holes[0].diameter, held.screw.thread, held.screwLength);
18
+
19
+ const hub = boreModel(m, { depth: 8 }); // the bore a gear takes for its shaft
20
+ console.log(hub.diameter, hub.across, hub.findings.length);
21
+
22
+ const out = performance(m, { speed: 12, ratio: 50, efficiency: 0.8 }); // 12 rpm at the output, through 50:1 gears
23
+ console.log(out.output.torque.toFixed(2), out.motor.speed, out.rests.join(', '));
24
+
25
+ const body = motor(m); // a JSCAD solid, its mounting face at z = 0, shaft up +z
26
+ const plate = mount(m, { plate: 5 }); // subtract this from your part
27
+ const gearBore = bore(m, { depth: 8 }); // and this from your gear
28
+ ```
29
+
30
+ ```text
31
+ stepper 5 31 0.59 spec
32
+ 22.5 3.5 M3 9
33
+ 5.3 4.8 0
34
+ 16.69 600 spec
35
+ ```
36
+
37
+ So the 48 mm NEMA 17 gets a 22.5 mm pocket for its boss and 3.5 mm holes for M3 × 9 screws, a D-bore 5.3 mm across and
38
+ 4.8 mm over its flat, and 16.7 N m at the output of 50:1 gears turning at 12 rpm.
39
+
40
+ ## The motors
41
+
42
+ | Name | What it is | Output | Torque |
43
+ |---|---|---|---|
44
+ | `nema17` | Stepper, 48 mm body (`17HS19-2004S1`; `17HS4401` is the 40 mm body) | 5 mm D shaft, four M3 on 31 mm | 0.59 N m holding (0.40 for the 40 mm) |
45
+ | `nema14` | Stepper, 34 mm body (`14HS13-0804S`) | 5 mm D shaft, four M3 on 26 mm | 0.18 N m holding |
46
+ | `28byj48` | 5 V geared stepper, 1:64 | 5 mm double-flat shaft, two ears 35 mm apart, shaft off-centre | 0.034 N m pull-in, at least (varies between makers) |
47
+ | `n20` | Brushed DC gear motor, Pololu's 100:1 HP 6 V | 3 mm D shaft, two M1.6 | 0.167 N m stalled, 310 rpm free (give `ratio` for another gearbox) |
48
+ | `sg90` | 9 g servo, plastic gears | Spline: drive it through its horn | 0.18 N m stalled, 180° |
49
+ | `mg90s` | 13 g servo, metal gears | Spline: drive it through its horn | 0.18 N m stalled at 4.8 V, 180° |
50
+ | `bldc2204` | 2204 brushless gimbal motor, 260 KV | The bell turns | 0.022 N m at 0.6 A |
51
+
52
+ Hobby motors vary. Unbranded N20s and 28BYJ-48s look identical and differ by a factor of two, so each figure carries
53
+ its `kind` (`spec` from a datasheet, `community` as commonly quoted, `estimate` where nobody has published it) and its
54
+ `source`, and `performance` says in `rests` which kinds the answer depended on.
55
+
56
+ **Measure yours and say so.** A figure you've measured replaces the catalogue's:
57
+
58
+ ```js
59
+ motorModel('nema17', { holding_torque: { value: 0.52, kind: 'measured', source: 'a known arm and a kitchen scale, 2026-11-09' } })
60
+ ```
61
+
62
+ A different body or gearbox is a figure too (`motorModel('n20', { ratio: 50 })`: the torque and speed follow the
63
+ ratio, marked `derived`). A motor that isn't listed is a rule set of your own in the same names (see the rules
64
+ package's `vocabulary.json`), handed in where the name goes.
65
+
66
+ ## Holding a motor
67
+
68
+ `mount(model, { plate, printer?, screw?, counterbore?, recess? }, ops?)` is the negative a part subtracts; `mountModel`
69
+ gives the same as numbers, with what's wrong (a plate too thin for its screws, a boss pocket as deep as the plate).
70
+ Clearances come from the printer's rules (`fit`, `hole_comp`), and screw sizes from the screw rule sets, so a printer
71
+ of your own or a screw you've measured carries through.
72
+
73
+ Where the part goes: on the shaft's side of the mounting face, z from 0 to `plate`, so the boss enters a pocket and the
74
+ shaft passes through. A servo goes through the part instead: its body down a slot, its tabs on top, z from `-plate` to 0.
75
+
76
+ `bore(model, { depth, fit?, printer? }, ops?)` is the hole a gear or hub takes, with the shaft's flat in it. The shaft
77
+ 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
78
+ round at its mouth and the shaft's round root can pass. `boreModel` warns of a bore that grips too little of the shaft
79
+ or misses its flat. A servo's spline is finer than a printer draws: drive it through its horn. A brushless motor drives
80
+ through its bell.
81
+
82
+ Anchors for placing a motor in an assembly are on the model: `face`, `shaft` (where the shaft leaves the motor), `tip`,
83
+ `horn` on a servo, and `hole1` onward.
84
+
85
+ ## What it does
86
+
87
+ `performance(model, { speed, ratio, efficiency, supply })` gives the torque and speed at the output and at the motor,
88
+ the fastest the output can go (`limit`), what it rests on (`rests`) and how it was worked out (`how`). A speed past the
89
+ motor's limit is a `motor.speed` failure.
90
+
91
+ | What | Formula | Source |
92
+ |---|---|---|
93
+ | Stepper, moving | T = T_hold / √2, flat to the corner speed, then T_hold / √2 × n_c / n | Both phases are on at holding, one vector's worth moving; two-part curve as in Geckodrive's *Step Motor Basics* |
94
+ | Stepper's corner speed | n_c (rpm) = 60 V / (2 L I N), N the full steps per turn | The windings take L I / V to reach full current, and a step can't be shorter than the rise and fall |
95
+ | 28BYJ-48 | The datasheet's pull-in torque, to the rate it starts at | [Datasheet](https://cdn.shopify.com/s/files/1/0015/7571/4865/files/datasheet_28BYJ-48.pdf) |
96
+ | DC gear motor | T = T_stall (1 − n / n_free) | The DC motor's straight torque-speed line |
97
+ | Servo | Its stall torque, within its range | Datasheet; work it at under half |
98
+ | Brushless | T = K_t I, K_t = 60 / (2π KV) | The motor constant in SI units: K_t = K_e |
99
+ | Through gears | T_out = T ratio η, n_out = n / ratio | |
100
+
101
+ A stepper's real curve is on its datasheet when the maker gives one; the kit doesn't have one for any motor yet, says so
102
+ in `how`, and the straight model is on the cautious side of most motors but not all of them. Measure yours.
package/motors.d.mts ADDED
@@ -0,0 +1,222 @@
1
+ /**
2
+ * @typedef {{ value: number | string, unit?: string, kind: string, source: string, rule?: string }} Figure
3
+ * @typedef {{ kind: 'motor', name: string, type: 'stepper' | 'dc' | 'servo' | 'brushless', figures: Record<string, Figure>,
4
+ * body: { shape: string, width: number, depth: number, length: number, top: number, corner: number, centre: number[] },
5
+ * boss: { diameter: number, height: number, top: number }, shaft: { diameter: number, length: number, flats: number, across: number, flatLength: number, base: number, tip: number },
6
+ * mount: { pattern: string, spacing: number, holes: number[][], thread: string | null, depth: number, diameter: number, ear: number, earThickness: number, tab: number, tabThickness: number, side: 1 | -1 },
7
+ * cable: { width: number, reach: number }, mass: number, ratio: number, stepAngle: number | null, range: number | null,
8
+ * anchors: Record<string, { origin: number[], axis: number[] }> }} Motor
9
+ */
10
+ /**
11
+ * A motor by name, from its rule set, or from a rule set of your own (for a motor not in the catalogue).
12
+ * @param {string | { name?: string, rules: object }} which 'nema17', '28BYJ-48', a maker's part number listed as a
13
+ * variant ('17HS4401'), or your own rule set in the same names
14
+ * @param {Record<string, number | string | Figure>} [change] a different or measured figure, by its rule's name:
15
+ * { body_length: 40 } or { holding_torque: { value: 0.38, kind: 'measured', source: 'hung a weight on an arm' } }
16
+ * @returns {Motor}
17
+ */
18
+ export function motorModel(which: string | {
19
+ name?: string;
20
+ rules: object;
21
+ }, change?: Record<string, number | string | Figure>): Motor;
22
+ /**
23
+ * The motor as a solid, to be seen in an assembly: its body, boss, shaft with its flat, and its tabs or ears. It is
24
+ * bought, not printed.
25
+ * @param {Motor} m @param {{ union: Function, subtract: Function }} [ops] the design's v.ops, so Manifold can read it
26
+ * @returns {object} a JSCAD solid
27
+ */
28
+ export function motor(m: Motor, ops?: {
29
+ union: Function;
30
+ subtract: Function;
31
+ }): object;
32
+ /**
33
+ * What a part needs to hold a motor, as numbers: the pocket, the holes, the screws. mount() cuts it.
34
+ * @param {Motor} m
35
+ * @param {{ plate: number, printer?: object, screw?: string, counterbore?: boolean, recess?: number }} p
36
+ * plate: the part's thickness at the mount (mm); printer: its fit, hole_comp, layer; screw: the screws going through
37
+ * a motor's plain holes (default the size they take); counterbore: sink the screw heads; recess: let the body into
38
+ * the part this far as well
39
+ * @returns {{ plate: number, side: 1 | -1, pocket: number, pocketDepth: number, shaftHole: number, holes: { at: number[], diameter: number }[], screw: object | null, screwLength: number | null, head: number | null, recess: number, findings: object[] }}
40
+ * side: which side of the mounting face the plate is on, +1 above it (a motor's face against the part), -1 below it (a servo through it)
41
+ */
42
+ export function mountModel(m: Motor, p: {
43
+ plate: number;
44
+ printer?: object;
45
+ screw?: string;
46
+ counterbore?: boolean;
47
+ recess?: number;
48
+ }): {
49
+ plate: number;
50
+ side: 1 | -1;
51
+ pocket: number;
52
+ pocketDepth: number;
53
+ shaftHole: number;
54
+ holes: {
55
+ at: number[];
56
+ diameter: number;
57
+ }[];
58
+ screw: object | null;
59
+ screwLength: number | null;
60
+ head: number | null;
61
+ recess: number;
62
+ findings: object[];
63
+ };
64
+ /**
65
+ * The negative a part subtracts to hold a motor. For most motors the plate sits on the mounting face, on the shaft's
66
+ * side (z from 0 to plate); a servo's plate is under its tabs, with the body through a slot (z from -plate to 0). The
67
+ * part goes where the motor's mounting face is.
68
+ * @param {Motor} m @param {{ plate: number, printer?: object, screw?: string, counterbore?: boolean, recess?: number }} p as mountModel
69
+ * @param {{ union: Function, subtract: Function }} [ops] the design's v.ops
70
+ * @returns {object} a JSCAD solid to subtract
71
+ */
72
+ export function mount(m: Motor, p: {
73
+ plate: number;
74
+ printer?: object;
75
+ screw?: string;
76
+ counterbore?: boolean;
77
+ recess?: number;
78
+ }, ops?: {
79
+ union: Function;
80
+ subtract: Function;
81
+ }): object;
82
+ /**
83
+ * A bore for the motor's shaft, as numbers, with what's wrong with it.
84
+ * @param {Motor} m @param {{ depth: number, fit?: 'slide' | 'press', printer?: object }} p depth: how far the shaft goes in
85
+ * @returns {{ depth: number, diameter: number, across: number, flats: number, flatFrom: number, grip: number, findings: object[] }}
86
+ * 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
87
+ */
88
+ export function boreModel(m: Motor, p: {
89
+ depth: number;
90
+ fit?: "slide" | "press";
91
+ printer?: object;
92
+ }): {
93
+ depth: number;
94
+ diameter: number;
95
+ across: number;
96
+ flats: number;
97
+ flatFrom: number;
98
+ grip: number;
99
+ findings: object[];
100
+ };
101
+ /**
102
+ * The bore a gear or hub takes for the motor's shaft, to subtract: round where the round of the shaft passes, with
103
+ * the flat where the flat is. The shaft goes in from z = 0, its tip going to z = depth.
104
+ * @param {Motor} m @param {{ depth: number, fit?: 'slide' | 'press', printer?: object }} p as boreModel
105
+ * @param {{ union: Function, subtract: Function }} [ops] @returns {object} a JSCAD solid to subtract
106
+ */
107
+ export function bore(m: Motor, p: {
108
+ depth: number;
109
+ fit?: "slide" | "press";
110
+ printer?: object;
111
+ }, ops?: {
112
+ union: Function;
113
+ subtract: Function;
114
+ }): object;
115
+ /** A motor is bought, so a part list can't print one. @param {Motor} m @returns {{ level: 'fail', text: string, code: string }[]} */
116
+ export function printable(m: Motor): {
117
+ level: "fail";
118
+ text: string;
119
+ code: string;
120
+ }[];
121
+ /**
122
+ * The torque and speed at the output, at a speed, through a ratio: what an assembly asks of its motor.
123
+ * @param {Motor} m
124
+ * @param {{ speed?: number, ratio?: number, efficiency?: number, supply?: number, volts?: number }} [p] speed: the output's, rpm (default 0, standing still);
125
+ * ratio: of the gears after the motor, input turns per output turn (default 1); efficiency: of those gears, 0 to 1 (default 1); supply: a stepper's driver supply, volts
126
+ * @returns {{ output: { torque: number, speed: number }, motor: { torque: number, speed: number }, limit: number, ratio: number, efficiency: number, rests: string[], how: string, findings: object[] }}
127
+ * limit: the fastest the output can go; rests: the kinds of figure the answer rests on
128
+ */
129
+ export function performance(m: Motor, p?: {
130
+ speed?: number;
131
+ ratio?: number;
132
+ efficiency?: number;
133
+ supply?: number;
134
+ volts?: number;
135
+ }): {
136
+ output: {
137
+ torque: number;
138
+ speed: number;
139
+ };
140
+ motor: {
141
+ torque: number;
142
+ speed: number;
143
+ };
144
+ limit: number;
145
+ ratio: number;
146
+ efficiency: number;
147
+ rests: string[];
148
+ how: string;
149
+ findings: object[];
150
+ };
151
+ /**
152
+ * The rules this package adds to the motors' own figures, each with what it comes from.
153
+ * @type {Record<string, { value: number, unit: string, rule: string, kind: string }>}
154
+ */
155
+ export const DEFAULTS: Record<string, {
156
+ value: number;
157
+ unit: string;
158
+ rule: string;
159
+ kind: string;
160
+ }>;
161
+ export function motors(): string[];
162
+ export type Figure = {
163
+ value: number | string;
164
+ unit?: string;
165
+ kind: string;
166
+ source: string;
167
+ rule?: string;
168
+ };
169
+ export type Motor = {
170
+ kind: "motor";
171
+ name: string;
172
+ type: "stepper" | "dc" | "servo" | "brushless";
173
+ figures: Record<string, Figure>;
174
+ body: {
175
+ shape: string;
176
+ width: number;
177
+ depth: number;
178
+ length: number;
179
+ top: number;
180
+ corner: number;
181
+ centre: number[];
182
+ };
183
+ boss: {
184
+ diameter: number;
185
+ height: number;
186
+ top: number;
187
+ };
188
+ shaft: {
189
+ diameter: number;
190
+ length: number;
191
+ flats: number;
192
+ across: number;
193
+ flatLength: number;
194
+ base: number;
195
+ tip: number;
196
+ };
197
+ mount: {
198
+ pattern: string;
199
+ spacing: number;
200
+ holes: number[][];
201
+ thread: string | null;
202
+ depth: number;
203
+ diameter: number;
204
+ ear: number;
205
+ earThickness: number;
206
+ tab: number;
207
+ tabThickness: number;
208
+ side: 1 | -1;
209
+ };
210
+ cable: {
211
+ width: number;
212
+ reach: number;
213
+ };
214
+ mass: number;
215
+ ratio: number;
216
+ stepAngle: number | null;
217
+ range: number | null;
218
+ anchors: Record<string, {
219
+ origin: number[];
220
+ axis: number[];
221
+ }>;
222
+ };
package/motors.mjs ADDED
@@ -0,0 +1,333 @@
1
+ // Motors for printed machines: a stepper, a DC gear motor, a servo or a brushless motor as its model (what it is and
2
+ // what it does, every figure with how far to trust it and where it comes from), a solid to place in an assembly, the
3
+ // negative a part subtracts to hold it (the mount) and the bore a gear takes for its shaft. performance() answers what
4
+ // an assembly asks: at this speed, through this ratio, what torque reaches the output?
5
+ //
6
+ // Every motor is one rule set in @rulecad/rules, so its numbers are open data and live there, not here. A motor is
7
+ // drawn with its mounting face at z = 0, its shaft on the z axis at the origin, pointing up +z. Units: mm, degrees,
8
+ // N m, rpm, kg.
9
+ import jscad from '@jscad/modeling';
10
+ import nema17 from '@rulecad/rules/nema17.json' with { type: 'json' };
11
+ import nema14 from '@rulecad/rules/nema14.json' with { type: 'json' };
12
+ import byj from '@rulecad/rules/28byj48.json' with { type: 'json' };
13
+ import n20 from '@rulecad/rules/n20.json' with { type: 'json' };
14
+ import sg90 from '@rulecad/rules/sg90.json' with { type: 'json' };
15
+ import mg90s from '@rulecad/rules/mg90s.json' with { type: 'json' };
16
+ import bldc2204 from '@rulecad/rules/bldc2204.json' with { type: 'json' };
17
+ import x1c from '@rulecad/rules/x1c.json' with { type: 'json' };
18
+ import m1_6 from '@rulecad/rules/m1_6.json' with { type: 'json' };
19
+ import m2 from '@rulecad/rules/m2.json' with { type: 'json' };
20
+ import m3 from '@rulecad/rules/m3.json' with { type: 'json' };
21
+ import m4 from '@rulecad/rules/m4.json' with { type: 'json' };
22
+
23
+ const { cuboid, cylinder, polygon } = jscad.primitives;
24
+ const { extrudeLinear } = jscad.extrusions;
25
+ const { translate } = jscad.transforms;
26
+ const booleans = { union: jscad.booleans.union, subtract: jscad.booleans.subtract };
27
+
28
+ const CATALOGUE = Object.fromEntries([nema17, nema14, byj, n20, sg90, mg90s, bldc2204].map((s) => [s.name, s]));
29
+ const SCREWS = { 'M1.6': m1_6, M2: m2, M3: m3, M4: m4 };
30
+ const key = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
31
+ const ALIASES = { ...Object.fromEntries(Object.keys(CATALOGUE).map((n) => [key(n), n])), byj48: '28byj48', '28byj': '28byj48', mg90: 'mg90s', '2204': 'bldc2204', gimbal2204: 'bldc2204', n20gearmotor: 'n20' };
32
+ for (const s of Object.values(CATALOGUE)) for (const v of Object.keys(s.variants || {})) ALIASES[key(v)] = s.name;
33
+
34
+ /**
35
+ * The rules this package adds to the motors' own figures, each with what it comes from.
36
+ * @type {Record<string, { value: number, unit: string, rule: string, kind: string }>}
37
+ */
38
+ export const DEFAULTS = {
39
+ 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' },
40
+ 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' },
41
+ fit: { value: 0.1, 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', kind: 'estimate' },
42
+ press: { value: -0.05, unit: 'mm', rule: 'Each side of a shaft in a press-fit bore: tight enough to hold, and a D flat does the driving', kind: 'estimate' },
43
+ grip: { value: 1.5, unit: '× shaft diameter', rule: 'The shortest length of bore worth trusting to drive a gear', kind: 'community' }
44
+ };
45
+ const D = (k) => DEFAULTS[k].value;
46
+
47
+ const r3 = (x) => +x.toFixed(3);
48
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
49
+ const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
50
+ const near = (a, b) => { // edits between two names, to suggest the nearest
51
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
52
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
53
+ 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));
54
+ return d[a.length][b.length];
55
+ };
56
+ 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; }
57
+ function isModel(what, m) { if (!m || m.kind !== 'motor') throw new Error(`${what}: give a motor's model (motorModel), not ${shown(m)}`); return m; }
58
+
59
+ /** @returns {string[]} the names of the motors in the catalogue */
60
+ export const motors = () => Object.keys(CATALOGUE);
61
+
62
+ /**
63
+ * @typedef {{ value: number | string, unit?: string, kind: string, source: string, rule?: string }} Figure
64
+ * @typedef {{ kind: 'motor', name: string, type: 'stepper' | 'dc' | 'servo' | 'brushless', figures: Record<string, Figure>,
65
+ * body: { shape: string, width: number, depth: number, length: number, top: number, corner: number, centre: number[] },
66
+ * boss: { diameter: number, height: number, top: number }, shaft: { diameter: number, length: number, flats: number, across: number, flatLength: number, base: number, tip: number },
67
+ * mount: { pattern: string, spacing: number, holes: number[][], thread: string | null, depth: number, diameter: number, ear: number, earThickness: number, tab: number, tabThickness: number, side: 1 | -1 },
68
+ * cable: { width: number, reach: number }, mass: number, ratio: number, stepAngle: number | null, range: number | null,
69
+ * anchors: Record<string, { origin: number[], axis: number[] }> }} Motor
70
+ */
71
+
72
+ /**
73
+ * A motor by name, from its rule set, or from a rule set of your own (for a motor not in the catalogue).
74
+ * @param {string | { name?: string, rules: object }} which 'nema17', '28BYJ-48', a maker's part number listed as a
75
+ * variant ('17HS4401'), or your own rule set in the same names
76
+ * @param {Record<string, number | string | Figure>} [change] a different or measured figure, by its rule's name:
77
+ * { body_length: 40 } or { holding_torque: { value: 0.38, kind: 'measured', source: 'hung a weight on an arm' } }
78
+ * @returns {Motor}
79
+ */
80
+ export function motorModel(which, change = {}) {
81
+ const what = 'motorModel';
82
+ let set = which, variant = null;
83
+ if (typeof which === 'string') {
84
+ const k = key(which), name = ALIASES[k];
85
+ if (!name) {
86
+ const guess = Object.keys(ALIASES).map((a) => [near(k, a), ALIASES[a]]).sort((a, b) => a[0] - b[0])[0];
87
+ 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`);
88
+ }
89
+ set = CATALOGUE[name];
90
+ variant = Object.entries(set.variants || {}).find(([v]) => key(v) === k)?.[1] ?? null;
91
+ }
92
+ 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)}`);
93
+ const figures = Object.fromEntries(Object.entries(set.rules).map(([n, r]) => [n, { ...r }]));
94
+ if (variant) for (const [n, value] of Object.entries(variant.values)) figures[n] = { ...figures[n], value, kind: variant.kind, source: variant.source };
95
+ for (const [n, c] of Object.entries(change)) {
96
+ 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]}?)` : ''}`); }
97
+ figures[n] = typeof c === 'object' && c ? { ...figures[n], ...c } : { ...figures[n], value: c, kind: 'given', source: 'given to motorModel' };
98
+ if (figures[n].value == null) throw new Error(`${what}: ${n} needs a value (got ${shown(c)})`);
99
+ }
100
+ // A gear motor with another gearbox: torque goes up with the ratio and speed down, unless you've given them too
101
+ if (change.ratio != null && set.rules.ratio && set.rules.stall_torque) {
102
+ const k = figures.ratio.value / set.rules.ratio.value, from = `scaled from its ${set.rules.ratio.value}:1 gearbox`;
103
+ if (change.stall_torque == null) figures.stall_torque = { ...figures.stall_torque, value: figures.stall_torque.value * k, kind: 'derived', source: from };
104
+ 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 };
105
+ }
106
+ const v = (n, fallback) => figures[n]?.value ?? fallback;
107
+ const type = v('type');
108
+ if (!['stepper', 'dc', 'servo', 'brushless'].includes(type)) throw new Error(`${what}: ${set.name}: type is stepper, dc, servo or brushless (got ${shown(type)})`);
109
+ 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);
110
+ 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);
111
+ const tab = v('mount_tab_length', 0), off = v('boss_offset', 0), centre = tab ? [-off, 0] : [0, -off];
112
+ 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');
113
+ 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]]];
114
+ const shaftLength = v('shaft_length'), tip = base + shaftLength, shaftFlats = v('shaft_flats', 0);
115
+ const m = {
116
+ kind: 'motor', name: set.name, type, figures,
117
+ body: { shape, width, depth, length: v('body_length'), top, corner: v('body_corner', 0), centre },
118
+ boss: { diameter: v('boss_diameter', 0), height: bossHeight, top: top + bossHeight },
119
+ 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 },
120
+ 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 },
121
+ cable: { width: v('cable_width', 0), reach: v('cable_reach', 0) },
122
+ mass: v('mass', 0), ratio: v('ratio', 1), stepAngle: null, range: v('range', null)
123
+ };
124
+ if (type === 'stepper') m.stepAngle = v('step_angle') / m.ratio;
125
+ // Anchors an assembly places a motor by: the shaft where it leaves the motor, its tip, and the mounting face
126
+ m.anchors = { face: { origin: [0, 0, 0], axis: [0, 0, 1] }, 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] }])) };
127
+ return m;
128
+ }
129
+
130
+ // ---------- shapes ----------
131
+ const extrude = (height, pts) => extrudeLinear({ height }, polygon({ points: pts }));
132
+ const SEG = 48;
133
+ 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 });
134
+ 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] });
135
+ // A shaft's section with its flats: a circle less the part past each flat, as a closed outline. Two flats: opposite,
136
+ // across = the distance between; one flat (a D): across = the distance from the flat to the far side of the shaft
137
+ function dSection(d, flats, across) {
138
+ const r = d / 2, y = flats === 2 ? across / 2 : across - r, a0 = Math.asin(y / r), n = 40, pts = [];
139
+ if (flats === 2) {
140
+ 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)]); }
141
+ return pts;
142
+ }
143
+ 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
144
+ return pts;
145
+ }
146
+
147
+ /**
148
+ * The motor as a solid, to be seen in an assembly: its body, boss, shaft with its flat, and its tabs or ears. It is
149
+ * bought, not printed.
150
+ * @param {Motor} m @param {{ union: Function, subtract: Function }} [ops] the design's v.ops, so Manifold can read it
151
+ * @returns {object} a JSCAD solid
152
+ */
153
+ export function motor(m, ops = booleans) {
154
+ isModel('motor', m);
155
+ const { body, boss, shaft, mount: h } = m, [cx, cy] = body.centre, parts = [];
156
+ const low = -body.length, high = body.top;
157
+ if (body.shape === 'square') {
158
+ const w = body.width / 2, c = body.corner;
159
+ 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]])));
160
+ } else if (body.shape === 'round') parts.push(disc(body.width, low || 0, high || 0, [cx, cy]));
161
+ else parts.push(box(cx - body.width / 2, cx + body.width / 2, cy - body.depth / 2, cy + body.depth / 2, low, high));
162
+ if (h.ear) for (const p of h.holes) parts.push(disc(2 * h.ear, -h.earThickness, 0, p));
163
+ if (h.ear) parts.push(box(h.holes[0][0], h.holes[1][0], cy - h.ear, cy + h.ear, -h.earThickness, 0));
164
+ 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));
165
+ if (boss.height) parts.push(disc(boss.diameter, high, high + boss.height));
166
+ let solid = ops.union(parts);
167
+ if (m.type === 'brushless') solid = ops.subtract(solid, disc(shaft.diameter, low - 1, high + 1));
168
+ else if (shaft.length) {
169
+ const flatFrom = shaft.flats ? shaft.tip - shaft.flatLength : shaft.tip;
170
+ solid = ops.union(solid, ...(flatFrom > shaft.base ? [disc(shaft.diameter, 0, flatFrom)] : []), ...(shaft.flats ? [translate([0, 0, Math.max(flatFrom, 0)], extrude(shaft.tip - Math.max(flatFrom, 0), dSection(shaft.diameter, shaft.flats, shaft.across)))] : []));
171
+ }
172
+ if (h.holes.length && (h.diameter || h.ear) && h.ear) solid = ops.subtract(solid, h.holes.map((p) => disc(h.diameter, -h.earThickness - 1, 1, p)));
173
+ return solid;
174
+ }
175
+
176
+ // The printer's clearances, from its rule set, with a design's own printer laid over them
177
+ 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 }; }
178
+ function screwOf(thread) {
179
+ const set = SCREWS[thread];
180
+ return set ? { thread, clearance: set.rules.clearance.value, head: set.rules.head.value, headHeight: set.rules.head_height.value } : null;
181
+ }
182
+
183
+ /**
184
+ * What a part needs to hold a motor, as numbers: the pocket, the holes, the screws. mount() cuts it.
185
+ * @param {Motor} m
186
+ * @param {{ plate: number, printer?: object, screw?: string, counterbore?: boolean, recess?: number }} p
187
+ * plate: the part's thickness at the mount (mm); printer: its fit, hole_comp, layer; screw: the screws going through
188
+ * a motor's plain holes (default the size they take); counterbore: sink the screw heads; recess: let the body into
189
+ * the part this far as well
190
+ * @returns {{ plate: number, side: 1 | -1, pocket: number, pocketDepth: number, shaftHole: number, holes: { at: number[], diameter: number }[], screw: object | null, screwLength: number | null, head: number | null, recess: number, findings: object[] }}
191
+ * side: which side of the mounting face the plate is on, +1 above it (a motor's face against the part), -1 below it (a servo through it)
192
+ */
193
+ export function mountModel(m, p) {
194
+ const what = 'mount';
195
+ isModel(what, m);
196
+ if (!p || typeof p !== 'object') throw new Error(`${what}: give the part's { plate } (its thickness at the mount, mm), not ${shown(p)}`);
197
+ const plate = positive(what, 'plate', p.plate), pr = printerOf(p.printer), { mount: h, boss, shaft } = m, out = [], f = (level, text, code) => out.push({ level, text, code });
198
+ const thread = h.thread ?? p.screw ?? (h.diameter >= 4 ? 'M4' : h.diameter >= 3 ? 'M3' : 'M2'), screw = screwOf(thread);
199
+ if (!screw) throw new Error(`${what}: no screw "${thread}" (${Object.keys(SCREWS).join(', ')})`);
200
+ const pocket = boss.diameter ? boss.diameter + 2 * pr.fit + pr.holeComp : 0, pocketDepth = boss.height ? boss.height + 2 * pr.layer : 0;
201
+ const shaftHole = shaft.diameter + 2 * pr.fit + pr.holeComp + 0.4;
202
+ const plain = !h.thread; // holes the screw only passes through, tapped by the screw or nutted
203
+ const holeD = m.type === 'servo' ? h.diameter - 0.4 + pr.holeComp : screw.clearance + pr.holeComp;
204
+ const head = p.counterbore ? screw.head + 2 * pr.fit + pr.holeComp : null;
205
+ 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');
206
+ const thickest = h.thread ? h.depth : 0;
207
+ // a screw's length: through the plate, into the thread, its head sunk or not
208
+ const under = plate - (p.counterbore ? screw.headHeight : 0);
209
+ const screwLength = h.thread ? Math.floor(under + Math.min(thickest, 2.5 * parseFloat(thread.slice(1)))) : Math.ceil(plate + (h.earThickness || h.tabThickness) + 2);
210
+ 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');
211
+ if (plate < 1.5 * parseFloat(thread.slice(1))) f('warn', `a ${plate} mm plate is thin for ${thread} screws: at least ${1.5 * parseFloat(thread.slice(1))} mm, or the head pulls through`, 'mount.plate');
212
+ 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, printer: pr, findings: out };
213
+ }
214
+
215
+ /**
216
+ * The negative a part subtracts to hold a motor. For most motors the plate sits on the mounting face, on the shaft's
217
+ * side (z from 0 to plate); a servo's plate is under its tabs, with the body through a slot (z from -plate to 0). The
218
+ * part goes where the motor's mounting face is.
219
+ * @param {Motor} m @param {{ plate: number, printer?: object, screw?: string, counterbore?: boolean, recess?: number }} p as mountModel
220
+ * @param {{ union: Function, subtract: Function }} [ops] the design's v.ops
221
+ * @returns {object} a JSCAD solid to subtract
222
+ */
223
+ export function mount(m, p, ops = booleans) {
224
+ const g = mountModel(m, p), { plate, pocket, pocketDepth, shaftHole, holes, recess, printer: pr } = g, { body, mount: h } = m, [cx, cy] = body.centre, cuts = [], over = 0.5;
225
+ if (m.type === 'servo') {
226
+ // the body through a slot, with the fit all round; the screws' pilot holes in the plate
227
+ 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));
228
+ for (const x of holes) cuts.push(disc(x.diameter, -plate - over, over, x.at));
229
+ return ops.union(cuts);
230
+ }
231
+ if (pocket && pocketDepth) cuts.push(disc(pocket, -over, pocketDepth));
232
+ cuts.push(disc(shaftHole, -over, plate + over));
233
+ for (const x of holes) {
234
+ cuts.push(disc(x.diameter, -over, plate + over, x.at));
235
+ if (g.head) cuts.push(disc(g.head, plate - g.screw.headHeight, plate + over, x.at));
236
+ }
237
+ if (recess) {
238
+ if (body.shape === 'round') cuts.push(disc(body.width + 2 * pr.fit + pr.holeComp, -recess - over, 0, [cx, cy]));
239
+ 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));
240
+ 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));
241
+ }
242
+ return ops.union(cuts);
243
+ }
244
+
245
+ /**
246
+ * A bore for the motor's shaft, as numbers, with what's wrong with it.
247
+ * @param {Motor} m @param {{ depth: number, fit?: 'slide' | 'press', printer?: object }} p depth: how far the shaft goes in
248
+ * @returns {{ depth: number, diameter: number, across: number, flats: number, flatFrom: number, grip: number, findings: object[] }}
249
+ * 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
250
+ */
251
+ export function boreModel(m, p) {
252
+ const what = 'bore'; isModel(what, m);
253
+ if (!p || typeof p !== 'object') throw new Error(`${what}: give the bore's { depth } in mm, not ${shown(p)}`);
254
+ const depth = positive(what, 'depth', p.depth), fit = p.fit ?? 'slide';
255
+ if (!['slide', 'press'].includes(fit)) throw new Error(`${what}: fit is slide or press (got ${shown(fit)})`);
256
+ 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`);
257
+ const pr = printerOf(p.printer), { shaft } = m, each = fit === 'slide' ? D('fit') : D('press'), diameter = shaft.diameter + 2 * each + pr.holeComp, flat = Math.min(depth, shaft.flatLength);
258
+ const out = [], f = (level, text, code) => out.push({ level, text, code });
259
+ 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');
260
+ const grip = Math.min(depth, shaft.length), want = D('grip') * shaft.diameter;
261
+ if (grip < want) f('warn', `only ${+grip.toFixed(2)} mm of the shaft is in the bore: ${want} mm or more, or the part rocks on it`, 'bore.grip');
262
+ 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');
263
+ if (!shaft.flats) f('warn', 'this shaft has no flat: only friction or a grub screw turns the part', 'bore.flat');
264
+ return { depth, diameter: r3(diameter), across: r3(shaft.across + 2 * each + pr.holeComp), flats: shaft.flats, flatFrom: depth - flat, grip, fit, findings: out };
265
+ }
266
+
267
+ /**
268
+ * The bore a gear or hub takes for the motor's shaft, to subtract: round where the round of the shaft passes, with
269
+ * the flat where the flat is. The shaft goes in from z = 0, its tip going to z = depth.
270
+ * @param {Motor} m @param {{ depth: number, fit?: 'slide' | 'press', printer?: object }} p as boreModel
271
+ * @param {{ union: Function, subtract: Function }} [ops] @returns {object} a JSCAD solid to subtract
272
+ */
273
+ export function bore(m, p, ops = booleans) {
274
+ const b = boreModel(m, p), parts = [], over = 0.5;
275
+ if (b.flatFrom > 0) parts.push(disc(b.diameter, -over, b.flatFrom + 0.001));
276
+ 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))));
277
+ else parts.push(disc(b.diameter, -over, b.depth + over));
278
+ return parts.length > 1 ? ops.union(parts) : parts[0];
279
+ }
280
+
281
+ /** A motor is bought, so a part list can't print one. @param {Motor} m @returns {{ level: 'fail', text: string, code: string }[]} */
282
+ 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' }]; }
283
+
284
+ // ---------- what it does ----------
285
+ const fig = (x, d = 3) => String(+x.toFixed(d));
286
+ // A figure's value, and note how far it is trusted
287
+ 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; }); }
288
+
289
+ /**
290
+ * The torque and speed at the output, at a speed, through a ratio: what an assembly asks of its motor.
291
+ * @param {Motor} m
292
+ * @param {{ speed?: number, ratio?: number, efficiency?: number, supply?: number, volts?: number }} [p] speed: the output's, rpm (default 0, standing still);
293
+ * ratio: of the gears after the motor, input turns per output turn (default 1); efficiency: of those gears, 0 to 1 (default 1); supply: a stepper's driver supply, volts
294
+ * @returns {{ output: { torque: number, speed: number }, motor: { torque: number, speed: number }, limit: number, ratio: number, efficiency: number, rests: string[], how: string, findings: object[] }}
295
+ * limit: the fastest the output can go; rests: the kinds of figure the answer rests on
296
+ */
297
+ export function performance(m, p = {}) {
298
+ const what = 'performance'; isModel(what, m);
299
+ const speed = p.speed ?? 0, ratio = p.ratio ?? 1, efficiency = p.efficiency ?? 1;
300
+ if (!(isNum(speed) && speed >= 0)) throw new Error(`${what}: speed is the output's, in rpm, 0 or more (got ${shown(speed)})`);
301
+ if (!(isNum(ratio) && ratio > 0)) throw new Error(`${what}: ratio is input turns per output turn, above 0 (got ${shown(ratio)})`);
302
+ if (!(isNum(efficiency) && efficiency > 0 && efficiency <= 1)) throw new Error(`${what}: efficiency is from 0 to 1 (got ${shown(efficiency)})`);
303
+ const n = speed * ratio, rests = new Set(), out = [], f = (level, text, code) => out.push({ level, text, code });
304
+ let torque, limit, how;
305
+ if (m.type === 'stepper' && m.figures.pull_in_torque) {
306
+ // A geared stepper: its pull-in torque, up to the fastest it starts; figures are at its own output
307
+ const [T, rate, step, gear] = used(m, ['pull_in_torque', 'step_rate', 'step_angle', 'ratio'], rests);
308
+ const steps = (360 / step) * gear; limit = (rate / steps) * 60; torque = T;
309
+ how = `pull-in torque, to its ${fig(limit, 2)} rpm`;
310
+ } else if (m.type === 'stepper') {
311
+ 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');
312
+ positive(what, 'supply', V); rests.add(DEFAULTS.running.kind);
313
+ // Flat until the windings can no longer reach full current in a step (corner speed), then constant power
314
+ const fullSteps = 360 / step, corner = (60 * V) / (2 * (L / 1000) * I * fullSteps), T0 = hold * D('running');
315
+ limit = 5 * corner; torque = n <= corner ? T0 : (T0 * corner) / n;
316
+ 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)`;
317
+ } else if (m.type === 'dc') {
318
+ const [stall, free] = used(m, ['stall_torque', 'no_load_speed'], rests);
319
+ limit = free; torque = Math.max(0, stall * (1 - n / free));
320
+ how = `the straight line from ${fig(stall)} N m stalled to ${fig(free, 0)} rpm free`;
321
+ } else if (m.type === 'servo') {
322
+ const [stall, s60, range] = used(m, ['stall_torque', 'speed_60', 'range'], rests);
323
+ limit = (60 / s60) / 6; torque = stall; // deg per second to rpm
324
+ how = `rated stall torque, within its ${range}° at up to ${fig(limit, 0)} rpm`;
325
+ } else {
326
+ const [kv, I, V] = used(m, ['kv', 'rated_current', 'rated_voltage'], rests);
327
+ const kt = 60 / (2 * Math.PI * kv); limit = kv * V; torque = n <= limit ? kt * I : 0;
328
+ how = `torque constant ${fig(kt, 4)} N m/A (60 / 2π Kv) at ${I} A`;
329
+ }
330
+ 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');
331
+ const motorTorque = n > limit ? 0 : torque;
332
+ return { output: { torque: motorTorque * ratio * efficiency, speed }, motor: { torque: motorTorque, speed: n }, limit: limit / ratio, ratio, efficiency, rests: [...rests], how, findings: out };
333
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@rulecad/motors",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
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
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./motors.d.mts",
9
+ "default": "./motors.mjs"
10
+ }
11
+ },
12
+ "types": "./motors.d.mts",
13
+ "files": [
14
+ "motors.mjs",
15
+ "motors.d.mts",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "license": "MIT",
20
+ "keywords": ["jscad", "3d-printing", "motors", "stepper", "servo", "nema17", "cad"],
21
+ "engines": { "node": ">=20.10" },
22
+ "sideEffects": false,
23
+ "repository": { "type": "git", "url": "git+https://github.com/JoniBach/rulecad.git", "directory": "packages/motors" },
24
+ "homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/motors#readme",
25
+ "bugs": { "url": "https://github.com/JoniBach/rulecad/issues" },
26
+ "scripts": { "test": "node --test" },
27
+ "peerDependencies": { "@jscad/modeling": "^2.12.0" },
28
+ "dependencies": { "@rulecad/rules": "^0.3.6" }
29
+ }