@protoboardai/ext-drone 0.0.0-stage → 0.2.1

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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ Protoboard Stack: @protoboardai/ext-drone
2
+ Copyright 2026 Delta Robotics, Inc.
3
+
4
+ This product includes software developed at Delta Robotics, Inc.
5
+ (https://deltaroboticsinc.com).
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License").
8
+ See the LICENSE file in this package for full terms.
9
+
10
+ "Protoboard", the Protoboard logo and the "0" mark are trademarks of
11
+ Delta Robotics, Inc. The License grants no rights to them (section 6);
12
+ see TRADEMARKS.md in the Protoboard Stack repository
13
+ (https://github.com/Delta-Robotics-Inc/protoboard-stack).
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @protoboardai/ext-drone
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
+ Flight-controller configuration for multirotor drones.
4
+
5
+ Part of [Protoboard](https://github.com/Delta-Robotics-Inc/protoboard-stack), which designs hardware with your AI agent. A project lists this extension in its `protoboard.config.ts`; the Protoboard templates add it where it fits. You rarely install it by hand: the [command line](https://www.npmjs.com/package/@protoboardai/cli) and the [VS Code extension](https://marketplace.visualstudio.com/items?itemName=deltarobotics.vscode-protoboard) bring it with them.
6
+
7
+ - [Installation guide](https://github.com/Delta-Robotics-Inc/protoboard-stack/blob/main/docs/guides/installation.md)
8
+ - [Source](https://github.com/Delta-Robotics-Inc/protoboard-stack/tree/main/packages/ext-drone)
9
+ - [Report an issue](https://github.com/Delta-Robotics-Inc/protoboard-stack/issues)
10
+
11
+ Apache 2.0. Protoboard is a trademark of Delta Robotics, Inc.
@@ -0,0 +1,32 @@
1
+ {
2
+ "schema": "protoboard.eval-case/v0",
3
+ "title": "Update the flight-controller configuration after the GPS moved to UART3",
4
+ "skills": ["firmware-config"],
5
+ "tags": ["firmware"],
6
+ "fixture": {
7
+ "from": "../../../../examples/quadcopter-5in",
8
+ "exclude": ["docs"],
9
+ "steps": [
10
+ {
11
+ "note": "the model change: the GNSS lead's UART wires are soldered to the UART3 pads (the configuration still says UART1)",
12
+ "replace": { "file": "src/quadcopter.uhd.ts", "find": "p2: \"fc:uart1_tx\", p3: \"fc:uart1_rx\"", "with": "p2: \"fc:uart3_tx\", p3: \"fc:uart3_rx\"", "count": 1 }
13
+ }
14
+ ]
15
+ },
16
+ "instruction": "We re-soldered the GPS lead to the flight controller's UART3 pads, and the model (src/quadcopter.uhd.ts) already says so. Bring the flight controller's Betaflight configuration in firmware/ up to date with the model, and tell me which serial port lines changed.",
17
+ "tools": { "read": true, "edit": true, "commands": ["npx protoboard *"] },
18
+ "budget": { "turns": 15, "seconds": 600, "usd": 2 },
19
+ "graders": [
20
+ { "id": "check-clean", "kind": "check", "maxErrors": 0 },
21
+ { "id": "gps-on-uart3", "kind": "text", "file": "firmware/betaflight/cli.txt", "matches": ["serial UART3 2 115200", "set gps_provider = UBLOX"], "notMatches": ["serial UART1 2 "] },
22
+ { "id": "rest-unchanged", "kind": "text", "file": "firmware/betaflight/cli.txt", "matches": ["serial UART2 64 115200 57600 0 115200", "serial UART5 131073 ", "set motor_pwm_protocol = DSHOT600"] },
23
+ { "id": "reference-generated", "kind": "operation", "run": ["betaflight-cli", "--input", "out=firmware/betaflight/regenerated.txt"], "status": "succeeded", "weight": 0, "description": "the generator's output for the model, as the reference for the next grader" },
24
+ { "id": "matches-generator", "kind": "digest", "file": "firmware/betaflight/cli.txt", "sameAs": "firmware/betaflight/regenerated.txt", "description": "cli.txt is exactly what the generator makes from the model: regenerated, not patched by hand" },
25
+ { "id": "answer", "kind": "text", "matches": ["UART3", "UART1"] },
26
+ { "id": "model-untouched", "kind": "digest", "file": "src/quadcopter.uhd.ts", "changed": false }
27
+ ],
28
+ "solution": [
29
+ { "protoboard": ["run", "betaflight-cli"], "expect": { "status": "succeeded" } },
30
+ { "say": "Regenerated firmware/betaflight/cli.txt from the model (run betaflight-cli): the GPS serial line moved from `serial UART1 2 …` to `serial UART3 2 115200 115200 0 115200`; UART1 is now unused. The receiver (UART2) and DJI MSP (UART5) lines are unchanged." }
31
+ ]
32
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Betaflight configuration for the 5-inch quadcopter, derived from its UHD
3
+ * links and part facts (PB-792). CLI syntax and values follow
4
+ * ../skills/firmware-config/references/betaflight-reference.md (verified
5
+ * against Betaflight 4.5.5, 2025.12.5
6
+ * and 2026.6.2 sources). Output targets Betaflight >= 2025.12.1, which the
7
+ * M9N-5883's QMC5883P compass requires.
8
+ *
9
+ * Every line is emitted with a comment naming the link or part fact it
10
+ * comes from. Nothing here is flight-tested: verify on hardware.
11
+ */
12
+ import type { InterfaceDef, ModuleDef, TraitDef } from "@deltarobotics/uhd";
13
+ import { systemLinks, type LinkResult, type ModuleLookup, type ResolvedEndpoint } from "@deltarobotics/uhd";
14
+ import { resolveSpins } from "@deltarobotics/uhd";
15
+ import type { SpinDirection } from "@deltarobotics/uhd";
16
+
17
+ /** serialPortFunction_e values (betaflight-reference.md §1). */
18
+ const FUNCTION = { MSP: 1, GPS: 2, RX_SERIAL: 64, VTX_MSP: 131072 } as const;
19
+
20
+ interface Line {
21
+ text: string;
22
+ why: string;
23
+ }
24
+
25
+ const traitsOf = (x: { traits?: TraitDef[] }) => x.traits ?? [];
26
+
27
+ /** All trait params of a module and its interfaces, flattened. */
28
+ function facts(def: ModuleDef): Record<string, unknown>[] {
29
+ return [def, ...def.interfaces].flatMap(traitsOf).map((t) => (t.params ?? {}) as Record<string, unknown>);
30
+ }
31
+
32
+ function textOf(def: ModuleDef): string {
33
+ return JSON.stringify(facts(def));
34
+ }
35
+
36
+ const hasProtocol = (iface: InterfaceDef, type: string) => iface.protocols.some((p) => p.type === type);
37
+
38
+ function kindOf(end: ResolvedEndpoint): "receiver" | "gnss" | "dji" | "other" {
39
+ const words = `${end.owner.name} ${(end.owner.tags ?? []).join(" ")} ${(end.owner.categories ?? []).join(" ")}`.toLowerCase();
40
+ if (hasProtocol(end.iface, "crsf")) return "receiver";
41
+ if (/gnss|gps/.test(words)) return "gnss";
42
+ if (/dji|air unit/.test(words)) return "dji";
43
+ return "other";
44
+ }
45
+
46
+ /** "uart5" → 5, from the flight controller's interface id. */
47
+ const uartNumber = (iface: InterfaceDef) => Number(/^uart(\d+)$/.exec(iface.id)?.[1]);
48
+
49
+ function isFlightController(def: ModuleDef): boolean {
50
+ return /flight controller/i.test(def.name) || (def.categories ?? []).some((c) => /flight/i.test(c));
51
+ }
52
+
53
+ function param(iface: InterfaceDef, id: string) {
54
+ return iface.parameters?.find((p) => p.id === id);
55
+ }
56
+
57
+ export interface BetaflightConfig {
58
+ target?: string;
59
+ minFirmware: string;
60
+ buildOptions: string[];
61
+ lines: Line[];
62
+ warnings: string[];
63
+ }
64
+
65
+ export function betaflightConfig(system: ModuleDef, lookup: ModuleLookup): BetaflightConfig {
66
+ const links = systemLinks(system, lookup); // stored + derived through cables (PB-805)
67
+ const lines: Line[] = [];
68
+ const warnings: string[] = [];
69
+ const features = new Set<string>();
70
+ const buildOptions = new Set<string>(["DSHOT"]);
71
+ let minFirmware = "4.5.5";
72
+
73
+ const fcEnd = (r: LinkResult): [ResolvedEndpoint, ResolvedEndpoint] | undefined => {
74
+ if (r.protocol === "connector") return undefined; // positions, not functions: the derived links carry them
75
+ if (isFlightController(r.a.owner)) return [r.a, r.b];
76
+ if (isFlightController(r.b.owner)) return [r.b, r.a];
77
+ return undefined;
78
+ };
79
+
80
+ // --- target -------------------------------------------------------------
81
+ const fcDef = links.map(fcEnd).find(Boolean)?.[0].owner;
82
+ const target = fcDef ? /\b(MATEK[A-Z0-9]+|[A-Z0-9]{6,}(?=\b[^"]*target))/.exec(textOf(fcDef) + fcDef.description)?.[1] : undefined;
83
+
84
+ // --- serial ports ---------------------------------------------------------
85
+ for (const r of links) {
86
+ const ends = fcEnd(r);
87
+ if (!ends || r.protocol !== "uart") continue;
88
+ const [fc, other] = ends;
89
+ const n = uartNumber(fc.iface);
90
+ if (!Number.isFinite(n)) continue;
91
+ const kind = kindOf(other);
92
+ const why = `link ${r.link.id}: ${fc.path} ↔ ${other.path}`;
93
+ if (kind === "receiver") {
94
+ lines.push({ text: `serial UART${n} ${FUNCTION.RX_SERIAL} 115200 57600 0 115200`, why: `${why} (CRSF receiver → RX_SERIAL)` });
95
+ lines.push({ text: "set serialrx_provider = CRSF", why: `${other.path} speaks crsf` });
96
+ features.add("TELEMETRY");
97
+ buildOptions.add("SERIALRX_CRSF");
98
+ } else if (kind === "gnss") {
99
+ lines.push({ text: `serial UART${n} ${FUNCTION.GPS} 115200 115200 0 115200`, why: `${why} (GNSS → GPS)` });
100
+ lines.push({ text: "set gps_provider = UBLOX", why: `${other.owner.name}: u-blox receiver` });
101
+ lines.push({ text: "set gps_auto_config = ON", why: "auto-config sets the module's baud/protocol from its default" });
102
+ features.add("GPS");
103
+ buildOptions.add("GPS");
104
+ } else if (kind === "dji") {
105
+ lines.push({ text: `serial UART${n} ${FUNCTION.MSP + FUNCTION.VTX_MSP} 115200 57600 0 115200`, why: `${why} (DJI MSP DisplayPort → MSP + VTX_MSP)` });
106
+ lines.push({ text: "set osd_displayport_device = MSP", why: "DJI O4 OSD via MSP DisplayPort (onboard analog OSD chip must not win on AUTO)" });
107
+ lines.push({ text: "set vcd_video_system = HD", why: "HD digital video system" });
108
+ features.add("OSD");
109
+ buildOptions.add("OSD_HD");
110
+ } else {
111
+ warnings.push(`${why}: no Betaflight serial function derived for ${other.owner.name}`);
112
+ }
113
+ }
114
+
115
+ // Every other hardware UART the flight controller has is reset to no
116
+ // function, so a pasted configuration is complete: a port the model no
117
+ // longer uses (the GPS moved from UART1 to UART3) does not keep its old
118
+ // function from the board's saved settings. The baud fields are the
119
+ // per-port defaults (betaflight-reference.md §1).
120
+ const used = new Set(lines.map((l) => Number(/^serial UART(\d+) /.exec(l.text)?.[1])).filter(Number.isFinite));
121
+ for (const n of (fcDef?.interfaces ?? []).map(uartNumber).filter(Number.isFinite).sort((a, b) => a - b)) {
122
+ if (used.has(n)) continue;
123
+ lines.push({ text: `serial UART${n} 0 115200 57600 0 115200`, why: `${fcDef!.id}: UART${n} has no link in the model, reset to no function` });
124
+ }
125
+
126
+ // --- motors ---------------------------------------------------------------
127
+ const phaseLinks = links.filter((r) => r.protocol === "bldc_3phase");
128
+ const escDef = phaseLinks[0] && (param(phaseLinks[0].a.iface, "max_current") ? phaseLinks[0].a.owner : phaseLinks[0].b.owner);
129
+ const fcRates = fcDef?.interfaces.find((i) => i.capabilities?.includes("esc_signal"))?.parameters?.find((p) => p.id === "esc_signal_rate");
130
+ const escRates = escDef?.interfaces.find((i) => i.capabilities?.includes("esc_signal"))?.parameters?.find((p) => p.id === "esc_signal_rate");
131
+ const maxRate = (p?: { value?: number; range?: [number, number] }) => p?.range?.[1] ?? p?.value;
132
+ const rate = Math.min(maxRate(fcRates) ?? 0, maxRate(escRates) ?? 0);
133
+ if (rate >= 150) {
134
+ const protocol = rate >= 600 ? "DSHOT600" : rate >= 300 ? "DSHOT300" : "DSHOT150";
135
+ lines.push({ text: `set motor_pwm_protocol = ${protocol}`, why: `highest DShot rate both ${fcDef?.id} and ${escDef?.id} state (${rate} kbit/s)` });
136
+ } else {
137
+ warnings.push("no common DShot rate between the FC motor outputs and the ESC inputs");
138
+ }
139
+ const bidir = (def?: ModuleDef) => Boolean(def?.interfaces.some((i) => i.capabilities?.includes("dshot_bidirectional")));
140
+ if (bidir(fcDef) && bidir(escDef)) {
141
+ lines.push({ text: "set dshot_bidir = ON", why: `both ${fcDef?.id} and ${escDef?.id} state bidirectional DShot (source: DolphinRC review blog only — verify)` });
142
+ }
143
+ const motorEnd = phaseLinks[0] && (param(phaseLinks[0].a.iface, "max_current") ? phaseLinks[0].b : phaseLinks[0].a);
144
+ const config = motorEnd && /(\d+)N(\d+)P/.exec(textOf(motorEnd.owner));
145
+ if (config) {
146
+ lines.push({ text: `set motor_poles = ${config[2]}`, why: `${motorEnd.owner.id}: ${config[0]} stator (${config[2]} magnet poles)` });
147
+ }
148
+
149
+ // Quad-X motor order check (betaflight-reference.md §3)
150
+ const expected: Record<number, string> = { 1: "rr", 2: "fr", 3: "rl", 4: "fl" };
151
+ for (const r of phaseLinks) {
152
+ const escSide = param(r.a.iface, "max_current") ? r.a : r.b;
153
+ const armSide = escSide === r.a ? r.b : r.a;
154
+ const n = Number(/(\d+)$/.exec(escSide.iface.id)?.[1]);
155
+ const corner = /arm_(\w\w)/.exec(armSide.path)?.[1];
156
+ if (expected[n] && corner && expected[n] !== corner) {
157
+ warnings.push(`motor ${n} is wired to arm_${corner}; Betaflight Quad-X expects arm_${expected[n]} (remap with the resource command or rewire)`);
158
+ }
159
+ }
160
+
161
+ // Motor direction (betaflight-reference.md §3a): Quad-X "props in" is
162
+ // M1 CW, M2 CCW, M3 CCW, M4 CW from above with yaw_motors_reversed OFF
163
+ // (the default); "props out" is every motor reversed with it ON.
164
+ const propsIn: Record<number, SpinDirection> = { 1: "cw", 2: "ccw", 3: "ccw", 4: "cw" };
165
+ const spins = resolveSpins(system, lookup);
166
+ const motorSpin = new Map<number, SpinDirection | undefined>();
167
+ for (const r of phaseLinks) {
168
+ const escSide = param(r.a.iface, "max_current") ? r.a : r.b;
169
+ const armSide = escSide === r.a ? r.b : r.a;
170
+ const n = Number(/(\d+)$/.exec(escSide.iface.id)?.[1]);
171
+ const armPath = armSide.path.split(":")[0];
172
+ const motor = [...spins.values()].find((x) => x.path.startsWith(`${armPath}/`) && x.def.id === armSide.owner.id) ?? spins.get(armPath);
173
+ motorSpin.set(n, motor?.spin);
174
+ }
175
+ const known = [...motorSpin.entries()].filter(([n, sp]) => propsIn[n] && sp);
176
+ if (known.length && known.length === motorSpin.size) {
177
+ const inward = known.every(([n, sp]) => propsIn[n] === sp);
178
+ const outward = known.every(([n, sp]) => propsIn[n] !== sp);
179
+ const list = known.sort(([a], [b]) => a - b).map(([n, sp]) => `M${n} ${sp!.toUpperCase()}`).join(", ");
180
+ if (inward) lines.push({ text: "set yaw_motors_reversed = OFF", why: `motor spins in the model (${list}) are Quad-X "props in", the default` });
181
+ else if (outward) lines.push({ text: "set yaw_motors_reversed = ON", why: `motor spins in the model (${list}) are Quad-X "props out"` });
182
+ else warnings.push(`motor spins (${list}) are neither Quad-X props-in nor props-out: diagonal motors must turn the same way`);
183
+ } else if (phaseLinks.length) {
184
+ warnings.push("no spin direction on some motors: set ChildModuleRef.spin so the prop direction can be derived");
185
+ }
186
+
187
+ // --- current meter ----------------------------------------------------------
188
+ const scale = escDef && /scale[^0-9]{0,12}(\d{2,4})/i.exec(textOf(escDef));
189
+ if (scale) {
190
+ lines.push({ text: "set current_meter = ADC", why: `${escDef?.id}: analog current sensor on the FC connector` });
191
+ lines.push({ text: `set ibata_scale = ${scale[1]}`, why: `${escDef?.id}: manufacturer current scale` });
192
+ lines.push({ text: "set ibata_offset = 0", why: `${escDef?.id}: manufacturer current offset` });
193
+ }
194
+
195
+ // --- compass -----------------------------------------------------------------
196
+ const compass = links.find((r) => r.protocol === "i2c" && fcEnd(r));
197
+ if (compass) {
198
+ const [, other] = fcEnd(compass)!;
199
+ const address = param(other.iface, "i2c_address")?.value;
200
+ lines.push({ text: "set mag_hardware = AUTO", why: `link ${compass.link.id}: compass at 0x${address?.toString(16).toUpperCase()} on ${compass.a.path}` });
201
+ buildOptions.add("MAG");
202
+ if (address === 0x2c) {
203
+ minFirmware = "2025.12.1";
204
+ warnings.push(`${other.owner.id}: QMC5883P compass (0x2C) is detected only by Betaflight >= 2025.12.1`);
205
+ }
206
+ const align = /CW\s?(\d+)°?\s*Flip/i.exec(textOf(other.owner));
207
+ if (align) {
208
+ lines.push({ text: `set align_mag = CW${align[1]}FLIP`, why: `${other.owner.id}: manufacturer alignment for arrow-forward mounting — confirm in the Sensors tab` });
209
+ }
210
+ }
211
+
212
+ // --- features ------------------------------------------------------------------
213
+ const featureLines = [...features].map((f) => ({ text: `feature ${f}`, why: "required by the serial functions above" }));
214
+ return {
215
+ target,
216
+ minFirmware,
217
+ buildOptions: [...buildOptions].sort(),
218
+ lines: [
219
+ ...lines
220
+ .filter((l) => l.text.startsWith("serial"))
221
+ .sort((a, b) => Number(/UART(\d+)/.exec(a.text)?.[1]) - Number(/UART(\d+)/.exec(b.text)?.[1])),
222
+ ...featureLines,
223
+ ...lines.filter((l) => !l.text.startsWith("serial")),
224
+ ],
225
+ warnings,
226
+ };
227
+ }
228
+
229
+ export function betaflightCli(system: ModuleDef, cfg: BetaflightConfig): string {
230
+ const width = Math.max(...cfg.lines.map((l) => l.text.length)) + 2;
231
+ return [
232
+ `# Betaflight configuration — ${system.name}`,
233
+ `# Generated from the UHD model by @protoboardai/ext-drone (protoboard run betaflight-cli). Do not edit by hand.`,
234
+ `# Target: ${cfg.target ?? "unknown"} · firmware >= ${cfg.minFirmware} · cloud build options: ${cfg.buildOptions.join(", ")}`,
235
+ `# Syntax and values verified against @protoboardai/ext-drone skills/firmware-config/references/betaflight-reference.md.`,
236
+ `# NOT FLIGHT-TESTED. Verify motor order, directions and compass alignment on the bench before flight.`,
237
+ `# Every hardware UART is set below (unused ports reset to function 0), so pasting this file needs no prior reset.`,
238
+ ...cfg.warnings.map((w) => `# WARNING: ${w}`),
239
+ "",
240
+ ...cfg.lines.map((l) => `${l.text.padEnd(width)}# ${l.why}`),
241
+ "save",
242
+ "",
243
+ ].join("\n");
244
+ }
@@ -0,0 +1,16 @@
1
+ import type { OperationFn } from "@protoboardai/core";
2
+ import { betaflightCli, betaflightConfig } from "../lib/betaflight.ts";
3
+
4
+ /** Betaflight CLI from the resolved system; warnings are returned as data for the agent to act on. */
5
+ export const betaflightCliOp: OperationFn = (ctx) => {
6
+ const { rootDef, lookup } = ctx.project;
7
+ if (!rootDef) return { status: "failed", summary: "project has no root system" };
8
+ const cfg = betaflightConfig(rootDef, lookup);
9
+ const out = ctx.inputs.out ?? "firmware/betaflight/cli.txt";
10
+ ctx.writeOutput(out, betaflightCli(rootDef, cfg), `Betaflight CLI (min firmware ${cfg.minFirmware})`);
11
+ return {
12
+ status: "succeeded",
13
+ summary: `${cfg.lines.length} CLI lines for ${cfg.target ?? "unknown target"}, firmware ≥ ${cfg.minFirmware}${cfg.warnings.length ? `, ${cfg.warnings.length} warning(s)` : ""}`,
14
+ data: { target: cfg.target, minFirmware: cfg.minFirmware, buildOptions: cfg.buildOptions, warnings: cfg.warnings },
15
+ };
16
+ };
package/ops/package.ts ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Contributions to the Manufacturing Package (@protoboardai/ext-release section
3
+ * contract): the flight-controller configuration, in the root unit's work
4
+ * order (it depends on the whole system's wiring, so it is loaded at final
5
+ * assembly, once everything is connected) and its bench check in the root
6
+ * unit's test plan. Flashing and loading are contributed as "configure"
7
+ * operations: the release numbers them after the assembly steps, inside the
8
+ * bench test and before the propellers go on.
9
+ *
10
+ * The configuration file is the one `protoboard run betaflight-cli` wrote.
11
+ * It is regenerated here in memory and compared: a file that no longer
12
+ * matches the model stops the release.
13
+ */
14
+ import { existsSync, readFileSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { listOperationRecords, type Project } from "@protoboardai/core";
17
+ import type { SectionContribution, SectionFn } from "@protoboardai/ext-release";
18
+ import { betaflightCli, betaflightConfig } from "../lib/betaflight.ts";
19
+
20
+ const DEFAULT_OUT = "firmware/betaflight/cli.txt";
21
+
22
+ /** The configuration file: where the last betaflight-cli run wrote it. */
23
+ function cliFile(p: Project): string {
24
+ const rec = listOperationRecords(p).filter((r) => r.record.operation === "betaflight-cli" && r.record.status === "succeeded").pop();
25
+ return rec?.record.outputs[0]?.path ?? DEFAULT_OUT;
26
+ }
27
+
28
+ function configuration(p: Project) {
29
+ if (!p.rootDef) return undefined;
30
+ const cfg = betaflightConfig(p.rootDef, p.lookup);
31
+ if (!cfg.target && !cfg.lines.length) return undefined; // no flight controller in this system
32
+ return { cfg, text: betaflightCli(p.rootDef, cfg), file: cliFile(p) };
33
+ }
34
+
35
+ export const workOrder: SectionFn = ({ project: p, unit }) => {
36
+ if (unit?.kind !== "root") return undefined;
37
+ const c = configuration(p);
38
+ if (!c) return undefined;
39
+ const abs = join(p.root, c.file);
40
+ const rerun = "run `protoboard run betaflight-cli` and commit the result";
41
+ if (!existsSync(abs)) return { title: "Flight controller configuration", blocks: [], diagnostics: [{ code: "DRONE_CLI_MISSING", severity: "error", message: `${c.file} does not exist; ${rerun}` }] };
42
+ if (readFileSync(abs, "utf8") !== c.text) return { title: "Flight controller configuration", blocks: [], diagnostics: [{ code: "DRONE_CLI_STALE", severity: "error", message: `${c.file} no longer matches the model; ${rerun}` }] };
43
+ const out: SectionContribution = {
44
+ title: "Flight controller configuration",
45
+ order: 60,
46
+ blocks: [
47
+ { kind: "paragraph", text: "Load the configuration once the receiver, video transmitter and GNSS are connected, before the propellers go on: the operations above flash the firmware and load this file after the power-up checks and before the rest of the bench test. Every line of the file cites the link or part fact it comes from." },
48
+ {
49
+ kind: "keyvalues",
50
+ rows: [
51
+ { label: "Firmware", value: `Betaflight ${c.cfg.minFirmware} or later` },
52
+ { label: "Target", value: c.cfg.target ?? "unknown" },
53
+ { label: "Build options", value: c.cfg.buildOptions.join(", ") },
54
+ { label: "File", value: "files/firmware/betaflight-cli.txt", note: `${c.cfg.lines.length} settings, from ${c.file}` },
55
+ ],
56
+ },
57
+ ...c.cfg.warnings.map((w) => ({ kind: "note" as const, level: "caution" as const, text: w })),
58
+ ],
59
+ operations: [
60
+ { stage: "configure", title: "Flash the flight controller", actions: [`Propellers off. Flash Betaflight ${c.cfg.minFirmware} or later for ${c.cfg.target ?? "the flight controller's target"} with the cloud build options ${c.cfg.buildOptions.join(", ")}.`], tools: ["Betaflight Configurator", "USB-C cable"], inspect: "the configurator connects and shows the target", test: "the configurator connects and shows the target" },
61
+ { stage: "configure", title: "Load the flight controller configuration", actions: ["Open the CLI tab, paste files/firmware/betaflight-cli.txt and press Enter; the board saves and reboots."], tools: ["Betaflight Configurator", "USB-C cable"], inspect: "the CLI echoes no error lines", test: "the flight controller bench check (test plan)" },
62
+ ],
63
+ files: [{ path: "files/firmware/betaflight-cli.txt", from: c.file, role: "firmware-config", description: "Betaflight CLI configuration" }],
64
+ };
65
+ return out;
66
+ };
67
+
68
+ export const testPlan: SectionFn = ({ project: p, unit }) => {
69
+ if (unit?.kind !== "root" || !configuration(p)) return undefined;
70
+ return {
71
+ title: "Flight controller bench check",
72
+ order: 60,
73
+ blocks: [
74
+ { kind: "paragraph", text: "After bring-up and the configuration, before the propellers go on: props off, powered through a current-limited supply or a smoke stopper. The configuration is generated from the model and has not been flight-tested." },
75
+ {
76
+ kind: "table",
77
+ columns: [
78
+ { key: "check", label: "Check" },
79
+ { key: "how", label: "How" },
80
+ { key: "pass", label: "Pass" },
81
+ ],
82
+ rows: [
83
+ { check: "Motor order and direction", how: "Motors tab, spin each motor at low throttle", pass: "M1–M4 at the positions and directions of the model's Quad-X layout" },
84
+ { check: "Receiver", how: "Receiver tab with the transmitter bound", pass: "all channels follow the sticks" },
85
+ { check: "Video and OSD", how: "goggles on, power cycle", pass: "image and OSD elements shown" },
86
+ { check: "GNSS and compass", how: "outdoors, Sensors and GPS tabs", pass: "satellite fix; heading follows the frame's nose" },
87
+ { check: "Current sensor", how: "compare the OSD current with the supply's", pass: "within the supply's resolution at idle" },
88
+ ],
89
+ },
90
+ ],
91
+ };
92
+ };