# pfodParser / pfodWeb — AI Guide to Designing, Generating and Completing a Sketch Audience: an AI that must take a user's request ("add a menu that controls a relay and shows a temperature gauge") all the way to a working Arduino sketch, using **only this library and its docs** — no external pfod documentation. Companion documents (read these for field-by-field rules — this guide does not repeat them): * `pfodMenu_json-format.md` — how to write/edit a `.pfodMenu_json` menu design. * `pfodDwg_json-format.md` — how to write/edit a `.pfodDwg_json` drawing. This guide covers the parts those two don't: the library architecture, what happens between "design" and "code", the exact shape of the code the pfodWeb Designer generates, and — the part with no other documentation at all — how to correctly fill in the user-logic gaps in that generated code. Everything here is drawn from the actual sources in this repository: `src/`, `examples/pfodWeb/*` (real Designer output), and the two format docs. Where an example doesn't exist in this repo for some item type, that is said explicitly rather than invented. --- ## Two ways to work — decide this first Everything below describes the same three stages. What differs is **who presses the buttons in `pfodWeb.html`**, and that changes what you hand over and what you get back. Establish which one applies before designing anything: the deliverable is different, and finding out at the end wastes the design. > ## ⛔ There is no Python in this workflow. None. Anywhere. > > **Do not look for Python. Do not check whether it is installed. Do not > install it. Do not write a `.py` file. Do not reach for `zipfile`, > `http.server`, `json` or any other Python module.** If you have started > down that path, stop and re-read this box — nothing further along the > guide will need it. > > This is stated this bluntly because it keeps happening: an assistant > starting fresh reaches for Python out of habit for "write some files and > zip them", and every minute spent on it is wasted. There is no Python > anywhere in this project and none is wanted. > > The whole chain is **JavaScript and C++**: > > | Piece | Language | > |---|---| > | `pfodWeb.html` | pure JavaScript, self-contained, runs in the browser | > | The design files you write | JSON — write them with a **Node** script | > | The STORED-zip writer (§4.1.1) | JavaScript, Node built-ins, given in full | > | The static server (below) | JavaScript, Node built-ins, given in full | > | The generated sketch | C/C++ for Arduino | > > Both tools you could plausibly want are already written for you, in > JavaScript, with no dependency. Copy them. Do not reimplement either one > in another language. ### A. You can drive the browser A browser-automation extension is connected — Claude in Chrome or equivalent — so the same assistant that writes the json also loads it, presses **Generate Code**, and reads what the screen says. Stage 2 needs no human. §4.1 is the whole of it. **What this needs.** Check these before starting, not halfway through: the failure mode of a missing piece is a half-loaded design and a user who has to unpick it. | | Why | |---|---| | **Chrome, with a browser-automation extension connected** (e.g. Claude in Chrome) | The only way to press the buttons. Everything in §4.1 assumes you can click and read the page. | | **Node.js** | Not for pfodWeb — for you. Two jobs: writing the design files, and zipping them (§4.1.1). | | **`pfodWeb.html`**, **served over http** | The prebuilt single file from the pfodParser library, with a static server in front of it — a browser extension may refuse to drive a `file://` page at all. Fifteen lines of Node, in §4.1. | | **Somewhere to write and read files** | The `.zip` has to exist on disk before you can base64 it, and the generated sketch comes back through the download folder (§4.1.3). | ### B. You cannot No extension, or the user would rather drive it themselves. The assistant writes the json and stops; the user does stage 2 and reports back. That is not a lesser workflow — the hand-off is a review point, and the fine adjustments that make a drawing look right are usually quicker by hand than by another round of prompting. The loop: 1. **The assistant writes** the `.pfodMenu_json` and every `.pfodDwg_json`, and says which files there are and what each is for. 2. **The user loads them** — one press if they are zipped as a bundle (§4.1.1 describes the layout; it is worth building even when a human is doing the loading), or file by file. 3. **The user checks the preview and adjusts.** Nudging a label, resizing a zone, fixing a colour is a click here and a guess-and-retry over chat. 4. **The user sends back two things**: **Export PNG**, so the assistant can see what it actually produced rather than imagining it, and **Save Dwg** for any drawing they changed — that writes the corrected json, inserts included. 5. **The user re-prompts, pointing at the saved file, not the original.** This is the step that goes wrong. An assistant that keeps editing its own first draft silently discards every hand adjustment, and the next iteration arrives having undone the user's work. If a drawing was revised, the saved copy IS the drawing now. ### Both: stop after each iteration **Design, generate, then STOP and say what you produced.** Do not start the next round on your own initiative — not even when you can see something you would improve, and especially not in approach A, where nothing physically prevents you from looping. Two reasons, and the second is the one that bites: * **The preview is the review.** A drawing is judged by looking at it, and the user cannot look at anything while you are still going. Iterating past them turns a two-minute correction into an unpicking job. * **They are probably editing it.** Between iterations the user is nudging labels and fixing colours in the panel — the adjustments that are far quicker by hand than by another round of prompting. Anything you generate on top of your own last draft discards all of it, and it arrives looking like progress. So Point 5 above is not only for approach B: whenever the user has touched anything, the drawing you must build on is **their saved copy**, not the one you last wrote. When you are unsure whether they changed something, ask — one question is cheaper than a silent overwrite. ### Both: ask before adding any dependency **Never pull in a library, package or tool without asking first.** Say what you want, what it buys, and what it costs; then wait. This holds for both halves of the work, and they fail differently: * **In the sketch** — an Arduino library is not free. It costs flash and RAM on a target that may have very little of either, it has to compile for *that* board, and the user has to install it before anything builds at all. A sketch that needs a library they do not have does not degrade, it fails. `pfodParser` is already there and covers the whole protocol; a second library is a claim that it does not. * **In your own tooling** — a package installed to write the json or build the zip is a thing the user did not ask for and now has. It is rarely needed: §4.1.1 supplies a complete STORED-zip writer and a static server in a handful of lines of Node built-ins, precisely so that neither is a reason to install anything. If a dependency genuinely is the right answer, the case is easy to make and takes one sentence. Making it is the requirement — not the outcome. ### Both: build what was asked, and nothing more **Do not add menu items, drawings, sub-menus, charts, touch zones or device behaviour that the user did not ask for.** No "I also added a Settings sub-menu", no spare status label, no decorative extras around a gauge, no helpful third button beside the two that were requested. Unrequested scope is not a free bonus here. It is charged for immediately, in four ways: * **The user has to review every item of it**, and they cannot tell your guesses from their requirements by looking at the screen. * **They have to hand-adjust it too.** Layout tuning is per-item work (§"Two ways to work", approach B) — inventing items multiplies the one job that is already the slowest. * **It consumes budgets that are genuinely small.** A menu message is capped at 1024 wire bytes (§4 and §7); the Minimal C target runs out of cmd letters past 52 items; flash and RAM on the board are finite. Padding spends all three on something nobody wanted. * **It is hard to remove later** — once it is in the design, in the drawing and in the generated sketch, taking it out is a change to three things. The same applies to the generated sketch in stage 3: fill in the marked extension points for the behaviour that was specified, and leave the rest alone. Do not invent extra commands, states or safety features and wire them in. If you think something is genuinely missing — a stop button on a motor control, a units label on a bare number — **say so in one line and let the user decide**. Naming a gap costs them a moment; building it costs them a review, an adjustment pass, and an argument with a sketch that already compiles. ### Both: never modify the pfodParser library **Nothing under `src/` is yours to change.** Not `pfodParser.h/.cpp`, not `pfodDrawing`, not `pfodDwgs` or `src/dwgs/*.h`, not to add a helper, fix a signature, widen a buffer or "just add one method". §2's Library map marks every one of those files *No — library code*, and it means it. An edit there is worse than useless, because it is invisible and it does not last: * **It is shared.** One library serves every pfod sketch on that machine. A change made for this project silently alters the others. * **It is overwritten.** The next library update from the Arduino Library Manager or GitHub replaces the file and the change vanishes — usually long after anyone remembers making it, presenting as a sketch that used to build and now does not. * **It only works on one machine.** A sketch that needs a patched library is not portable, and nothing in it says so. The user finds out when they hand it to somebody else. **You do not need to.** The generated code is built to be extended from outside: every generated class is reached through a *weak*-symbol accessor, so you supply your own subclass and your own non-weak accessor in a file you create, and the linker prefers yours — without a single generated or library file changing (§4, §5.2, §5.3). The `.ino` carries marked extension points for anything with no natural class home (§5.1). That is the whole design; use it. If you are convinced the library itself is wrong — a real bug, not a missing convenience — **report it, do not patch it.** Say what breaks and where, and let the user take it upstream. --- ## 1. The three-stage workflow | Stage | You do | Output | |---|---|---| | **1. DESIGN** | Write/edit `.pfodMenu_json` and `.pfodDwg_json` files. The two format docs govern this stage. | The design files | | **2. GENERATE** | In `pfodWeb.html`, connection type **Designer**: import the design, pick the board, click Generate. | A sketch `.zip` | | **3. COMPLETE** | Write your own file(s) that subclass the generated classes and override their hooks; fill in the `.ino`'s few remaining placeholders. Never edit a generated file's body. | A working sketch | * **Stage 1** is pure JSON authoring against the two format docs. You can do this stage entirely offline, with no board and no browser. * **Stage 2** happens in a browser (`pfodWeb.html`, connection type **Designer** — see `pfodWeb-guide.html` §2, "Connection Setup"): open pfodWeb.html, pick **Designer**, import the design (or build it interactively), select the target board, and generate the sketch. Either hand a user a ready-to-import `.pfodMenu_json` (plus its `dwgs/*.pfodDwg_json`) that generates correctly on the first try if you follow the format docs' rules — or, if you can drive a browser, do this stage yourself: see §4.1 for `window.pfodWebFileHook`, which loads those files without the native file dialog that would otherwise stop you. * **Stage 3** is what this guide is mostly about: given the generated sketch, add the hardware/business logic the Designer cannot know (what pin does what, what a button press should actually do, how a label's text is computed). **Generation is safe to re-run, provided your logic lives in a subclass.** Every generated class — `pfodMainMenu` and every `Dwg_` — is reached everywhere else in the generated code through an accessor function (`get_pfodMainMenu()`, `get_dwg_()`) whose default body is a *weak* symbol. You define your own subclass, your own instance, and a same-named non-weak function returning it, all in **file(s) you create yourself** — one file (e.g. `App.cpp`) is simplest, but nothing requires it; one file per drawing works just as well and is the better choice when a drawing is meant to be reused across sketches (§4) — and the linker silently prefers your definition either way, no generated file needs to change at all. Re-running Generate then only overwrites `pfodMainMenu.h/.cpp` and `Dwg_.h/.cpp`; your own file is untouched and still compiles. See §5.2/§5.3 for the mechanism in full (with `examples/pfodWeb/LedOnOff_serial/LedOnOffApp.cpp` in this repo as the worked, ground-truth example) and §7 rule 1 for the two things that *can* still need attention after a re-generate: a structural design change renaming or removing a virtual hook your subclass overrides, and the `.ino`'s own placeholders (credentials, extension points) coming back blank. --- ## 2. Library map | Path | What it is | Do you edit it? | |---|---|---| | `src/pfodParser.h/.cpp` | Core parser: reads `{cmd\|args}` messages, writes menu/dwg wire format, owns the list of active drawings. | No — library code. | | `src/pfodDrawing.h/.cpp` | Base class every generated `Dwg_` inherits from. `init()`, `sendDwg()`, `processDwgCmds()`. | No — library code (your `Dwg_` subclasses it). | | `src/pfodDwgs.h/.cpp` + `src/dwgs/*.h` | The fluent builder API (`dwgsPtr->rectangle()...send()` etc.) used inside generated dwg code. One header per item type — see §5.4. | No — library code, but you'll call it directly inside your own subclass overrides, e.g. a `sendIndexedItems()` override (§5.3). | | `src/pfodSecurity*.h/.cpp` | Drop-in alternative to `pfodParser` adding 128-bit message security. Same menu/dwg API. | Only if the user asks for secured comms. | | `pfodWeb/pfodWeb.html` | The browser client, including the Designer (menu/dwg editor + Arduino code generator). | No — treat as a black box; it's what performs stage 2. | | `pfodWeb/docs/pfodMenu_json-format.md`, `pfodDwg_json-format.md` | Stage 1 references. | N/A | | `examples/pfodWeb/Hello_World_serial/`, `LedOnOff_serial/`, `LedOnOff_ble/`, `LedOnOff_tcp/`, `LedOnOff_http/`, `Menu_1/` | **Real Designer output.** `LedOnOff_serial/` additionally ships `LedOnOffApp.cpp` — a hand-written file, *not* Designer output — that completes the whole sketch by subclassing every generated class; it's the canonical worked example for the mechanism in §5.2/§5.3/§6. `Menu_1/` is a plain menu (no dwg) with `onoff`/`pwm`/`datadisplay`/`onoffdisplay`/`chart`/`submenu` items, all generated, including a `button` item *inside* the sub-menu — the ground truth for §6.3–§6.5. | The generated files are references, not templates to overwrite; `LedOnOffApp.cpp` is the pattern to copy for your own logic file. | | `examples/pfodWeb/*` (everything else) | Hand-written library-feature demos (not Designer output). Useful for learning the raw `pfodParser`/`pfodDwgs` API, but do not mimic their structure for a Designer-based sketch — they don't follow the generated file layout. | Reference only. | --- ## 3. Designing (stage 1) — quick decision guide Full rules are in the two format docs. Use this table to pick the right construct before writing JSON: | You want... | Use | |---|---| | A screen of text/numeric fields and simple controls, no custom graphics | A **menu** (`.pfodMenu_json`), built from `button`/`label`/`onoff`/`onoffdisplay`/`pwm`/`datadisplay`/`submenu`/`chart` items | | Custom graphics — shapes, gauges, custom-positioned touch buttons, live-updating drawn values | A **dwg** (`.pfodDwg_json`), referenced from the menu via a `drawing` item | | A control that is just "on/off" or "a slider", with no custom look | `onoff` / `pwm` menu items — don't build a dwg for this, it's a lot more code for the same result | | A gauge, custom button layout, LED indicator shape, or anything positioned/coloured precisely | A dwg — see the dwg doc's Recipes (§10), e.g. §10.4 push-button, §10.12 radial gauge | | Nested screens | `submenu` menu items (unlimited nesting) | | A live chart of sampled data | `chart` menu item (menu format) — up to 3 plots | | Reusable graphics (e.g. an LED shape used twice) | One dwg, embedded into others via `insertDwg` (dwg format §"insertDwg") | **An inserted dwg's header, except for version, is discarded — only its items are drawn.** Not just the background: on the wire, everything, except version, from `{+` up to the first `|` is parsed and thrown away for an inserted dwg — its `color`, its `x`/`y` size, and its refresh interval (dwg format §"insertDwg"). Only the child's `items` are merged into the parent, painted with the parent's own background behind them, clipped by the parent's region rather than their own. **The one header field that survives is the version**, which the client stores and sends back as `{V1:}` so the device can answer "nothing changed" instead of resending the child. **Refresh is the trap.** An inserted dwg's `dwgRefresh_ms` schedules nothing. Only two things drive an automatic re-request: the menu's own refresh, and the **top-level** dwg's — the one a Drawing menu item points at. A child is re-fetched only when its parent is, so it updates at the *parent's* rate, and a child under a parent whose refresh is `0` is fetched once and then left alone however short its own interval says it is. Nothing reports this: no error, no retry, just a drawing that never updates. **Put the refresh interval on the top-level dwg**, not on the inserted one that happens to hold the changing value. Because none of them has a background, inserted dwgs can freely overlap each other, or sit on top of the main dwg's own content — they don't need to be spaced apart on the canvas to keep one's background from covering another. If an inserted dwg does need a background of its own, add it explicitly as a filled `rectangle` — the child's first item, sized to the area it wants to own. If that background also has to cover the main dwg or an earlier-inserted sibling (not just its own child items), give the rectangle an `idxName`: indexed items always paint above un-indexed ones, and it's the only way to control stacking between one inserted dwg and another (dwg format §6.1; see the radial-gauge recipe, §10.12, for indexed masking in practice). **A dwg with no touch zones should usually have its Drawing menu item disabled.** A drawing that defines no `touchZone` has no active areas of its own, so a press on it is a press on the *menu item* it belongs to: the client sends that item's cmd — on the way down, as soon as a finger or mouse button lands anywhere on the picture. On a phone, where a drawing often fills the screen, that turns every stray touch and every failed scroll grab into a cmd the device has to answer. Set the item to **User input Disabled** (the designer's "Responds to User Input" toggle on Edit Menu Item; a `!` on the wire) and the drawing is still drawn, still refreshed on its own interval, but never sends anything. **Leave it enabled when you want exactly that behaviour** — a press on the picture sends the item's cmd like any other menu button, so answering it with the menu is a "tap the drawing to refresh the whole screen" affordance. That is a deliberate choice, not the default to fall into. **A link to a web page goes in a `label` or a prompt, as a Markdown link.** Write `[text](url)` in the text of a `label` menu item, or in a menu's prompt (the bar at the bottom of the menu, or of an input / numeric-input / selection screen), and pfodWeb shows `text` as a link that opens in a new browser tab. The rest of the text is ordinary pfod text, and the usual format tags work around and inside the link: ``` |!h~Read the [manual](https://www.forward.com.au/pfod/) first |!k~Help: [<+1>on this device](/help.html) or [online](https://www.forward.com.au/pfod/) {,<+2>Pool Pump\n<-2>[setup guide](/setup.html)~... ``` The url must begin `http://`, `https://`, or `/`. A `/path` is a page on the device's own web root — the same LittleFS that serves `pfodWeb.html`, so drop `help.html` in the sketch's `data/` next to the pfodWeb bundles — and only works on an http connection; over serial or BLE (and in the designer's preview) it renders as plain text. A url cannot contain spaces or parentheses, nor `|`, `~` or `}` like any pfod text, and its bytes count against the 1024-byte cap. **Never in a button.** Labels and prompts have no cmd, which is the whole reason they are the two places a link is rendered — a tap can never both open a page and send a cmd. Anywhere else — a button, a toggle, a selection row, a drawing label — the text is shown exactly as sent, `[..](..)` and all. pfodApp (Android) shows `[manual](https://…)` literally — readable, and the URL is visible, but there is no copy (the app's menu is drawn on a canvas that takes every touch), so the user retypes it. If a menu will be seen in pfodApp, keep such URLs short and typeable, and let the link *text* carry the meaning (`[setup guide](/setup.html)`, not `[/setup.html](/setup.html)`). **Drawing names drive the C++ identifiers in stage 3:** a dwg's `name`, its `cmdName` (touch zones / inserted dwgs) and its `idxName` (indexed items) become **literal C++ identifiers** in the generated code. **Menu items are different**: their identifiers are chosen by the generator from the item's *type* plus a per-type number, not from `autoCmd` (see the menu rows below). Always read them from the generated files. | JSON | Becomes, in generated code | |---|---| | dwg `name: "LedOn"` | class `Dwg_LedOn`, global instance `dwg_LedOn`, files `Dwg_LedOn.h/.cpp` | | dwg item `idxName: "idx_1"` | member `pfodAutoIdx idx_1;` in the `Dwg_` class | | dwg `touchZone.cmdName: "cmd_c1"` | member `pfodAutoCmd cmd_c1;` **and** a virtual hook `bool Dwg__cmd_c1(...)` you override in a stage-3 subclass | | menu item, any type | a base name from the item's type — `onoff` → `onOffOut`, `onoffdisplay` → `onOffIn`, `pwm` → `sliderIO`, `datadisplay` → `sliderDisplay`, `chart` → `chart`, `button` → `button`, `label` → `label`, `drawing` → `dwg`, `submenu` → `submenu` — with `_2`, `_3`, … for the second, third, … item of the same type in the design. From it: cmd member `_Cmd`, value/text variable `_var`, pin constant `_pin` (only if a `pin` was set) | | menu `button` (e.g. base `button`) | `button_Cmd`, displayed text `button_var` (same for a sub-menu-opening button — §6.3a), and a hook for the press: `button_Pressed(pfodParser&)` (§6.5) | | menu `onoff` (e.g. base `onOffOut`) | `onOffOut_Cmd`, `onOffOut_var`, `onOffOut_pin`, and a hook `onOffOut_Changed(int)` (§6.3) | | menu `label` (e.g. base `label`) | `label_Cmd`; no hook, but its displayed text is a variable, `label_var` (and a menu/sub-menu's own `promptText` likewise gets `mainMenuPromptText_var` / `SubMenu__promptText_var`) — §6.3a | The menu-item names in this guide's examples are what the generator produced for `examples/pfodWeb/Menu_1`; for any other design **read the names from the generated files**, never derive them from `autoCmd` or the item text. For drawings, **pick short, descriptive `cmdName`/`idxName` values at design time** — `cmd_setRelay`, `idx_tempLabel` — not the designer's auto-suggested `cmd_c1`, `idx_1`, if you want the generated code to read sensibly. Both are valid; only the human-readability differs. **Keep the wire message a device sends under 1024 bytes.** A drawing with many items, many indexed items, or long label/units text all add to the size of the single `{...}` message `sendFullDrawing()` produces. An `insertDwg` adds only its short reference; the child is sent separately. See §7 rule 11 for the exact limits. Going over does not fail loudly. The receiver auto-closes the message at the cap, so the item spanning the cut arrives in half and everything after it is gone. pfodWeb draws what it could read and names what it dropped in the console (`N item(s) could not be read and were left out`); the drawing on screen is simply missing its tail. The Dwg Controls Panel measures each drawing before you ever send it and shows the name and byte count in red, with *"This dwg too large to send without truncation"*, so the usual way to meet this is in the designer rather than on the wire. **A drawing too big for one message: split it into inserted dwgs.** Move groups of items into child drawings and `insertDwg` them into the parent. Each inserted dwg is fetched with its own request and sent as its own `{...}` message. The parent carries only the short `insertDwg` reference, so each child has its own 1023-byte budget, both for its full load and for its update. That second point is the advantage over the legacy method below. **When you create a dwg, check both its sizes, and split it yourself if either is over 1023 bytes.** Do this without waiting to be asked: 1. **The full load.** This is the `{+…}` message `sendFullDrawing()` sends: the header plus every item. Count it in UTF-8 bytes, not characters. The Dwg Controls Panel shows this count, and only this one. 2. **The update.** This is the `{+|…}` message `sendUpdate()` sends: every indexed item, re-sent on each refresh. Nothing measures it for you. Measure it with the longest values the items can carry at run time: the longest label text, the widest number, the units. Do not use the placeholder values in the json. A `{+|…}` update that fits with `0` can overflow with `-1234.56`. 3. **If either is over 1023 bytes,** move groups of items into new child dwgs and `insertDwg` each one into the parent. Keep going until every drawing, parent and children, is under the limit for both its full load and its update. Keep the refresh interval on the top-level dwg (see the refresh trap above). Keep `cmdName`/`idxName` unique per the dwg doc §5.2. Tell the user which drawings you created and why. When you split, follow these rules so the drawing still displays as designed: * **Keep the items in order.** Cut the item list into consecutive runs and keep each run in its original order. A child's un-indexed items are drawn at its `insertDwg`'s place in the parent's list. Its indexed items are different: they always paint above **all** of the parent's indexed items, wherever the `insertDwg` sits, and siblings stack in `insertDwg` order (dwg doc §6.1). So the parent keeps only the **first** run, followed by one `insertDwg` per later run, in order. Never leave parent items after an `insertDwg`: an indexed one would drop beneath the children's indexed items. Split this way, both un-indexed and indexed items stack exactly as they did in the single drawing. * **Never separate a `touchZone` from its `touchAction`s and `touchActionInput`s.** They must immediately follow their touchZone in the same drawing, or the loader deletes them (dwg doc §6). Move the whole group into the same run. * **Keep every `idxName` reference in the same drawing as its target.** An `idxName` resolves only inside its own drawing (dwg doc §5.3). A `touchAction`, `touchActionInput` or `hide`/`unhide`/`erase` that names an indexed item must go in the same run as that item. So must an `index` placeholder for it, and every other item sharing that `idxName` (dwg doc §5.2): split across drawings, they become different indices. A `hide`/`unhide`/`erase` that names a touchZone's `cmdName` must likewise go in that touchZone's run. The run must also put any `hide`/`unhide`/`erase` after its target, as before. * **Leave no `pushZero` open at the end of a drawing.** If a run ends inside a `pushZero` … `popZero` block, end that child with a `popZero` for each `pushZero` still open. Then start the next child with the same `pushZero`s, in the same order, before its first item, so its items keep the same origin and scale. Every drawing must have as many `popZero`s as `pushZero`s. * **Put each `insertDwg` at the parent's base transform**, outside any `pushZero`, with `xOffset`/`yOffset` of `0`. A child inherits the transform in force at its `insertDwg`, so an open `pushZero` there would be applied twice: once in the parent and once by the child's own reopened `pushZero`. * **Move the stage-3 code with the items.** Each moved `cmdName`/`idxName` becomes a member of the child's `Dwg_` class. A hook for a moved touchZone becomes `Dwg__()`, and any override for it moves to a subclass of the child. **Do not use the `~m` multi-part load.** pfod also has an older way to send a large drawing. The initial load cmd for a drawing always asks for the first part: ``{`0}``, or ``{:`0}`` when the client has a cached version. If the response carries the `~m` option, the client asks for the next part, ``{`1}``, then ``{`2}`` and so on. Each later part is an update, `{+~m|…}` while more parts follow. The client stops at an empty response `{}`, or at a part without `~m`. The full load can then span several messages, but the drawing's **update** (the refresh reply) is still one response under 1023 bytes for the whole drawing, and it may not carry `~m`. This method is **deprecated**. pfodWeb still follows it when a device sends it. The pfodWeb Designer does not generate it, and generated code never sends `~m`. The `moreData` argument of `pfodDwgs::start()` and `pfodDwgs::startUpdate()` exists only for this method: always leave it at its default of `0`. Use inserted dwgs instead. --- ## 4. Generating (stage 2) — what comes out For a menu with `connection: "serial"` (or ble/tcp/http) and one or more `drawing` items, Generate produces: ``` / .ino the pfod-agnostic connection setup; rarely edited now (see §5.1) pfodMainMenu.h pfodMainMenu.cpp one pair, always — the top of the menu tree Dwg_.h Dwg_.cpp one pair per drawing reachable from the menu Dwg_.h Dwg_.cpp ... menujson/ _menuJson.zip the design that produced this sketch ``` **`menujson/` holds one file**, the same artifact *Save Design to File* downloads, so a generated sketch travels with a design that can be loaded straight back: * `.pfodMenu_json` — when the design links no drawings. **Edit existing Menu → Load Design from File** takes it. * `_menuJson.zip` — when there are dwgs. Inside: ``` .pfodMenu_json dwgs/.pfodDwg_json one per linked drawing ``` The same **Edit existing Menu → Load Design from File** takes it — one button offers both shapes, since which one a design was saved as depends on whether it links a drawing rather than on anything you chose. The Dwg Controls Panel's **Load Dwg** takes it too. Both accept the whole generated sketch zip as well — they look inside `menujson/` for the bundle, so there is no need to extract it first. **Generate does not export a `data/` folder.** For an HTTP connection that serves pfodWeb from the micro's own filesystem (`useLittleFSToServe_pfodWeb = true` in the `.ino`), the required files come from the library's own `pfodWeb/data/` directory — copy that in alongside the sketch yourself; it is not part of what Generate produces per-sketch. **`pfodMainMenu.*` and every `Dwg_.*` are identical regardless of connection type** (serial/ble/tcp/http). All the connection-specific code (BLE GATT service, WiFi/HTTP server, TCP socket, Serial baud) lives **only** in the `.ino`, and you should never need to touch it beyond the placeholders in §5.1. **Generate never creates a file for your own logic.** You add that yourself, and there is no required layout for it. One file (e.g. `App.cpp`, the pattern `LedOnOffApp.cpp` demonstrates) holding every subclass and every `get_...()` override is the simplest option for a small sketch — note that file needs no header of its own, since nothing outside it ever names `MyLedOn` or `MyMainMenu` directly; every other file only ever calls the `get_...()` accessor. Equally valid: **one `.cpp` per drawing you're subclassing** — e.g. `Dwg_LedOnApp.cpp`, with its own `MyLedOn` class, instance, and `get_dwg_LedOn()` override (add a header only if something else genuinely needs to name the subclass type). Splitting this way is the better choice once a drawing is meant to be reused across sketches: the drawing's subclassed behaviour then travels with it as one file, and a new sketch that wants that same behaviour just adds it (plus the generated `Dwg_.h/.cpp`) rather than copying logic out of some other sketch's combined file. See §5.2–§5.3 for the mechanism. ### 4.1 AI Driving stage 2, through a browser Stage 2 is a browser step, but it is not necessarily a *human* step. If you can drive Chrome, you can do it — subject to the two things a page-level automation cannot touch, both covered below: the native file dialog, and the native `alert()`. This is **approach A** — see "Two ways to work" above for what it needs before you start, and for what to do instead when the browser is not yours to drive. > **Re-confirm a button's position immediately before every click — never > reuse a coordinate from an earlier screenshot.** This screen scrolls and > re-renders between actions (a status label appears, a list grows by a > row, a dialog opens on top of another), so a coordinate that was correct > one screenshot ago can land on the wrong element the next. A miss is not > always silent: clicking a few pixels off a real "Load Design from File" > or "Generate Code" button can land on something else on the page > entirely, and if that happens to be a file input or a download, it can > trigger the native dialog this section exists to avoid — after which the > session is stuck until a human dismisses it (§4.1.2/§4.1.3). Re-locate > the element (by ref/selector, not a remembered x/y pair) right before > each click, and take a fresh screenshot after any action that can change > layout — a load, a generate, a dialog open/close — before clicking again. Node earns its place twice over. **Write the json with a script, not by hand:** a drawing is a long list of items whose coordinates are usually computed from each other (a gauge's ticks, a bar's segments), and a generating script is both shorter than the file it emits and re-runnable when the user asks for twelve ticks instead of ten. It also parses what it writes, so a design reaches the browser already known to be valid JSON — the alternative is finding out through a `alert('Invalid JSON file')` you cannot dismiss. **Then zip what it wrote:** one press loads a whole design plus every drawing, and Node has no zip writer, so §4.1.1 supplies one. Both are covered there. **Serving the page.** Put `pfodWeb.html` in a directory of its own and run this beside it. Node built-ins only, so there is nothing to install: ```js // serve.js — one directory over http. node serve.js [port] const http = require('http'); const fs = require('fs'); const path = require('path'); const root = path.resolve(process.argv[2] || '.'); const port = Number(process.argv[3] || 8137); const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8' }; http.createServer((req, res) => { const rel = decodeURIComponent(req.url.split('?')[0]); const file = path.join(root, rel === '/' ? 'pfodWeb.html' : rel); // The path came off a socket: keep it inside root. if (file !== root && !file.startsWith(root + path.sep)) { res.writeHead(403).end(); return; } fs.readFile(file, (err, body) => { if (err) { res.writeHead(404).end(); return; } res.writeHead(200, { 'Content-Type': TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream' }); res.end(body); }); }).listen(port, '127.0.0.1', () => console.log('http://127.0.0.1:' + port + '/')); ``` It binds to `127.0.0.1`, so it is reachable from that machine's browser and nowhere else. Open `http://127.0.0.1:8137/` and drive that. > **`file://` is the human's route, not yours.** Someone opening the page > themselves just double-clicks it — loading their own json through the file > dialog, editing a drawing, exporting a `.png`. All of that works from > `file://` and needs no server. None of it is what §4.1 is about; > everything here assumes the served page. Nothing here requires a build of pfodWeb itself. Node is a prerequisite of *this repository's* build scripts too, but that is a separate matter — for design work you download the prebuilt `pfodWeb.html` and never run a build. #### 4.1.1 `window.pfodWebFileHook` — loading without the file dialog Every Load button in pfodWeb ends in a hidden `` and a `click()`, which opens a **native OS file-open dialog**. That dialog is outside the page and modal at the OS level, so no amount of clicking in the DOM gets past it, and until someone dismisses it by hand the session is stuck. `window.pfodWebFileHook` is the way through. Arm the file contents, then press the real button: the click delivers what you armed instead of opening the dialog. Everything after that — parse, validate, repair, dedup, the missing-drawing prompts — is the ordinary load path, unchanged, so what you exercise is the real thing and not a side door. | Call | Does | |---|---| | `arm({name, text})` | Queue one file. Returns the queue length. | | `arm([{…}, {…}])` | Queue several, in order. | | `arm({name, base64})` | Queue a **binary** file — a `.zip` design bundle. | | `armed()` | Names still queued, in the order they will be handed out. | | `clear()` | Drop the queue. Returns how many were discarded. | | `deleteAllDwgs()` | Save a snapshot of every drawing, then remove them all. Returns the names removed. | **Build a bundle and load it in ONE press.** This is the quick, reliable route, and the one to reach for by default. You are authoring the design json and every drawing json anyway; zip them into a `_menuJson.zip` yourself and arm that. One press of **Load Design from File** brings in the design and every drawing together — no per-file arming, no walking the missing-drawings block, and nothing left half-loaded if you lose count. The bundle layout is the one the app itself writes (§4): ``` .pfodMenu_json the design, at the root dwgs/.pfodDwg_json one per drawing it references ``` If you only want the DRAWINGS loaded and have no design to go with them, put a trivial one at the root anyway — a single Drawing item pointing at whichever drawing is the top of the set. That is exactly what the panel's own **Save Dwg** writes, and it is what makes the zip loadable in one press instead of needing a per-drawing route: ```json { "format": "pfodDesigner", "schema": 12, "name": "Gauge", "rootMenu": { "promptText": "", "refresh_ms": 0, "items": [ { "type": "drawing", "dwgName": "Gauge", "autoCmd": "drawing_Gauge_Cmd", "text": "Gauge" } ] } } ``` > **Node has no zip writer of its own, and you do not need one.** A STORED > zip — no compression — is just the files with headers around them, which > is a few lines and no dependency. Compressing a few hundred bytes of json > would gain nothing, so don't. > > pfodWeb reads STORE and DEFLATE both, so a zip from any other tool is > fine too if you have one to hand. This is here because Node does not. > > **This is the moment the guide keeps losing people to Python.** "Zip some > files" is the one step where reaching for `zipfile` feels natural. The > function below is the answer — copy it. No Python, no package, no shelling > out to `zip`. > > ```js > const { crc32 } = require('zlib'); // Node 20.12+ > const u16 = (n) => { const b = Buffer.alloc(2); b.writeUInt16LE(n); return b; }; > const u32 = (n) => { const b = Buffer.alloc(4); b.writeUInt32LE(n >>> 0); return b; }; > > /// entries: [{ path, data: Buffer }] -> one STORED zip Buffer > function storeZip(entries) { > const parts = [], central = []; > let offset = 0; > for (const { path, data } of entries) { > const name = Buffer.from(path, 'utf8'); > // flags, method=0 (STORE), time, date, crc, compressed, uncompressed > const meta = Buffer.concat([u16(0), u16(0), u16(0), u16(0), > u32(crc32(data)), u32(data.length), u32(data.length)]); > parts.push(Buffer.concat([Buffer.from('PK\x03\x04'), u16(20), meta, > u16(name.length), u16(0), name]), data); > central.push(Buffer.concat([Buffer.from('PK\x01\x02'), u16(20), u16(20), meta, > u16(name.length), u16(0), u16(0), u16(0), u16(0), u32(0), u32(offset), name])); > offset += 30 + name.length + data.length; > } > const cd = Buffer.concat(central); > return Buffer.concat([...parts, cd, > Buffer.concat([Buffer.from('PK\x05\x06'), u16(0), u16(0), > u16(entries.length), u16(entries.length), u32(cd.length), u32(offset), u16(0)])]); > } > ``` > > Paths go in with forward slashes and no leading `./`, exactly as the > layout above shows them — the reader matches on position, so > `dwgs/Gauge.pfodDwg_json` is a drawing and `./dwgs/Gauge.pfodDwg_json` is > nothing it recognises. > **Re-loading a bundle does NOT update what is already there.** Nothing in > this app overwrites a loaded drawing — a name already in DwgLibrary is > left exactly as it is and reported as *"already loaded, so left > unchanged"*. That is deliberate (it is usually the user's own edited > copy), but it makes the edit-rebuild-reload loop a trap: press Load a > second time and you keep the OLD drawings while the design comes in > beside its predecessor as `_2`, so the screen looks like it worked. > > So on every reload after the first, clear the drawings first: > > ```js > pfodWebFileHook.deleteAllDwgs(); // → ['Gauge', 'Needle', 'Tick'] > ``` > > That is the hook point for it, and it is **deliberately not a button** — > wiping the library in one press is not something to leave in the UI beside > Create Dwg. It returns the names it removed, so log them; it is > idempotent, so calling it on an empty library is a harmless `[]`. > > **Before the FIRST load, ask the user.** The browser's library persists > between sessions, so it usually already holds drawings from earlier work — > look at the Dwg Controls Panel's list (or `DwgLibrary`) before arming > anything. If it is not empty, stop and ask the user, yes or no, whether > to clear it with `deleteAllDwgs()` first, naming a few of the drawings > found and saying that a snapshot of them all is saved to the download > folder before anything is removed. Do not decide this yourself in either > direction: those drawings are the user's own, and leaving them in place > mixes earlier work into this session's design. Only reloads after the > first need no question — the rule above already says clear. > > **It saves a snapshot first.** Before anything is removed, every drawing > in the library goes into one `AllDwgs__menuJson.zip` in your > download folder — an ordinary design bundle, so loading it back restores > the lot. That matters because the library is where a drawing edited in > this session lives, and often the only place it lives; the panel's own > per-row delete saves a copy out for the same reason. If the snapshot > cannot be written, nothing is deleted. > > The snapshot design is ONE menu with one Drawing **row** per drawing — > not several menus. The rows are the top-level drawings, meaning the ones > no other drawing pulls in via `insertDwg`. So for a library of `Gauge` > (which inserts `Needle`) and `Standalone`, the menu has two rows, > `Gauge` and `Standalone`; `Needle` gets no row of its own because you > already see it inside `Gauge`. All three are in `dwgs/` and all three > load — the row list only decides what the menu shows. > > Designs are untouched. The panel does not repaint by itself — it shows the > change on its next render (any row click, or leaving and re-entering the > screen). > > For one drawing rather than all of them, `DwgLibrary.remove('Gauge')`. > `DwgLibrary` is a top-level `const`, so it answers to its bare name in > the console — there is no `window.DwgLibrary`. > > Read the result label or notice after loading — it names what it skipped, > and that is how you catch a reload that quietly kept stale drawings. ```js // The whole design in one press. A zip is binary, so it arms as base64. pfodWebFileHook.arm({ name: 'Menu_1_menuJson.zip', base64: '…' }); // Drawings only, out of that same bundle: press "Load Dwg" in the Dwg // Controls Panel instead. That one button takes a single .pfodDwg_json or // any bundle, so the same file serves both screens. pfodWebFileHook.arm({ name: 'Menu_1_menuJson.zip', base64: '…' }); // A design that references no drawing needs no zip — arm the json. pfodWebFileHook.arm({ name: 'Menu_1.pfodMenu_json', text: '…the JSON…' }); ``` **Loose files, when a bundle is not worth building.** One drawing to add, or files you were handed rather than authored: ```js pfodWebFileHook.arm([ { name: 'LedOn.pfodDwg_json', text: '…' }, { name: 'LedOff.pfodDwg_json', text: '…' }, ]); ``` **How much one press takes.** A `multiple` input ("Load Several Dwgs") takes the whole queue. A single-file input takes **one** and leaves the rest queued — which is what "Load next dwg" wants: arm the set once, then press repeatedly until the screen says everything is loaded. That works, but it is several presses and several screen-reads where a bundle is one of each, so prefer the bundle whenever you are producing the files. **It is inert until armed.** An un-armed click, and any click on a non-file input, goes straight to the real `click()`. So arming is per-press: if you arm nothing and press Load, the native dialog opens and you are stuck. `armed()` before pressing is the cheap way to be sure. Every file picker in the app is covered, because the hook wraps the shared `HTMLInputElement.prototype.click` rather than any one screen: | Screen | Button | |---|---| | Edit existing Menu | Load Design from File (`.pfodMenu_json` or `.zip`) | | Edit existing Menu, missing-drawings block | Load Several Dwgs · Load next dwg | | Dwg Controls Panel | Load Dwg (`.pfodDwg_json` or `.zip`) | | Dwg Controls Panel, missing-insertDwg prompt | Load File… | | Select Dwg for a menu item | Load Dwg from File | | Connection prompt, page loaded with `?replay` | Replay Raw Msg File (`pfod-messages-.json`, or a pfodApp debug log `.txt`) — scripts use `pfodReplay` instead, see below | > **If `pfodWebFileHook` is `undefined` from your JavaScript tool, you are > in an isolated world, not the page.** Some browser-automation tools > (Claude in Chrome's `javascript_tool` among them) run your code beside > the page: the DOM is shared, the page's globals are not, so > `pfodWebFileHook`, `ConnectionManager`, `messageCollector` and every > other pfodWeb global all read as `undefined` — and a click you then make > opens the native dialog, because nothing was armed in the page itself. > Run the call in the page by injecting it as a `