diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..22d925aaac8e671693db850c4a66adf69e0021a2 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
+screenshots/Screenshot[[:space:]]2026-11-26[[:space:]]024554.png filter=lfs diff=lfs merge=lfs -text
+screenshots/Screenshot[[:space:]]2026-11-26[[:space:]]024937.png filter=lfs diff=lfs merge=lfs -text
diff --git a/.github/workflows/jekyll-gh-pages.yml b/.github/workflows/jekyll-gh-pages.yml
new file mode 100644
index 0000000000000000000000000000000000000000..9c82e9461272351e770be5a1756d9a18e6a1ed6c
--- /dev/null
+++ b/.github/workflows/jekyll-gh-pages.yml
@@ -0,0 +1,51 @@
+# Sample workflow for building and deploying a Jekyll site to GitHub Pages
+name: Deploy Jekyll with GitHub Pages dependencies preinstalled
+
+on:
+ # Runs on pushes targeting the default branch
+ push:
+ branches: ["main"]
+
+ # Allows you to run this workflow manually from the Actions tab
+ workflow_dispatch:
+
+# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
+permissions:
+ contents: read
+ pages: write
+ id-token: write
+
+# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
+# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
+concurrency:
+ group: "pages"
+ cancel-in-progress: false
+
+jobs:
+ # Build job
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Setup Pages
+ uses: actions/configure-pages@v5
+ - name: Build with Jekyll
+ uses: actions/jekyll-build-pages@v1
+ with:
+ source: ./
+ destination: ./_site
+ - name: Upload artifact
+ uses: actions/upload-pages-artifact@v3
+
+ # Deployment job
+ deploy:
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ runs-on: ubuntu-latest
+ needs: build
+ steps:
+ - name: Deploy to GitHub Pages
+ id: deployment
+ uses: actions/deploy-pages@v5
diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml
new file mode 100644
index 0000000000000000000000000000000000000000..95973149f222662ee55673d72cabee64b89f6d39
--- /dev/null
+++ b/.github/workflows/static.yml
@@ -0,0 +1,43 @@
+# Simple workflow for deploying static content to GitHub Pages
+name: Deploy static content to Pages
+
+on:
+ # Runs on pushes targeting the default branch
+ push:
+ branches: ["main"]
+
+ # Allows you to run this workflow manually from the Actions tab
+ workflow_dispatch:
+
+# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
+permissions:
+ contents: read
+ pages: write
+ id-token: write
+
+# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
+# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
+concurrency:
+ group: "pages"
+ cancel-in-progress: false
+
+jobs:
+ # Single deploy job since we're just deploying
+ deploy:
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Setup Pages
+ uses: actions/configure-pages@v5
+ - name: Upload artifact
+ uses: actions/upload-pages-artifact@v3
+ with:
+ # Upload entire repository
+ path: '.'
+ - name: Deploy to GitHub Pages
+ id: deployment
+ uses: actions/deploy-pages@v5
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..3bbca42d332ec9bd83b01602b1b39f5c8bd96ffc
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 M. M. Shamshiri
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/PROPOSAL.md b/PROPOSAL.md
new file mode 100644
index 0000000000000000000000000000000000000000..eb0567a668f88cd51f805eefa16d3ceacaf8b13d
--- /dev/null
+++ b/PROPOSAL.md
@@ -0,0 +1,87 @@
+# NLCL — Natural Language as a Computational Language
+
+**Author of the idea:** M. M. Shamshiri, independent researcher (concept first developed in 2019)
+**Status:** working software prototype, released openly so that others can continue it
+
+## The idea in one paragraph
+
+Today's language models break text into statistical sub-word tokens and learn meaning afterwards from data.
+This proposal starts from the other end: **meaning is the unit of computation from the first step.** A sentence
+is reduced to semantic tokens, the tokens form a computational structure, and that structure — not the text —
+is what gets executed, stored and translated into code. Natural language is then not an interface placed in
+front of a programming language; it is the programming language. The long-term vision is that such a language
+could sit at the core of an operating system, and eventually be accelerated by dedicated hardware.
+
+## What makes it different from "natural language to code"
+
+1. **Three kinds of semantic tokens in one vocabulary** — atomic (`CREATE`, `OBJECT`, `CONNECT`), composite
+ (`CREATE + OBJECT → CREATE_OBJECT`), and adaptive (new words and commands learned at run time, each
+ validated by a dry run before it is accepted).
+2. **A universal, language-independent representation.** Every instruction becomes an operation on entities,
+ properties, behaviours and links, e.g.
+ `CREATE(domain=GAME, type=object, properties={health: 100, movable: true})`.
+3. **A universal concept of "object".** "Create an object" is not guessed: the system asks which domain is
+ meant, because the same object is a GameObject, a Python class, a register in hardware or a CAD part.
+4. **Persistent state.** Each sentence modifies the same system; it does not generate a new unrelated program.
+5. **Several domains at once.** One description can produce firmware, hardware description, a server, a 3D
+ model and an application, with a shared contract for every connection between them.
+6. **A deterministic path.** For supported sentences the same input always gives the same structure, with no
+ model in the loop.
+
+## What the prototype does today
+
+- Offline pipeline for English: semantic tokens → composite tokens → IR → persistent state → code.
+- Eight pluggable domain modules: Python, game (Unity / Godot / HTML5 preview), embedded (Arduino / ESP32 /
+ MicroPython / Wokwi), hardware (Verilog + testbench), C++, 3D (three.js / Blender), CAD (OpenSCAD), and
+ applications (desktop GUI for Windows / macOS / Linux plus an installable web app for Android / iOS).
+- Multi-module systems: links such as `connect the sensor to the dashboard via http` become one channel
+ contract implemented on both sides.
+- Behaviour rules in plain sentences (`when ghost touches bob, decrease bob lives by 1`), attached to the
+ entity whose state they change.
+- Other human languages (for example Persian) through an online agent that rewrites the sentence into the
+ language's own English commands.
+- A bug-fix command for any file, folder or generated module: real diagnostics first, then an online agent
+ that proposes small edits, with backup, re-check and rollback.
+- Only free tools and free model APIs; the core needs nothing but the Python standard library.
+- 111 automated tests pass.
+
+## What it does not do yet (stated plainly)
+
+- The offline parser covers common sentence shapes, not all of English. It still misreads some sentences.
+- Modules are written by hand. The system learns new words and commands, not new modules.
+- The online features (other languages, bug fixing) were tested only with a stand-in model, not a real one.
+- Generated C++, Verilog and Arduino code has not been compiled; only Python, JavaScript and the desktop/web
+ application output were actually executed.
+- The operating-system core and the dedicated hardware from the original concept are not started. The software
+ prototype is the baseline the concept asked for first.
+
+## Open research questions
+
+1. Can semantic tokens replace or complement statistical tokens inside a language model, rather than only in
+ front of it?
+2. Can a system extend its own semantic vocabulary and rules safely and consistently at scale?
+3. How far can one universal object representation stretch across software, games, 3D, hardware and devices?
+4. Would a natural-language runtime with persistent computational state be a sound basis for an operating
+ system shell or kernel interface?
+5. Is there any workload where dedicated hardware for semantic operations pays off?
+
+## Why it is being shared
+
+I do not have the funding or the time to build the full architecture. I am publishing the idea and this
+prototype so that people and organisations with more resources can evaluate it, improve it, or take it
+further. I am not claiming that every component is new; I am proposing the combined architecture and asking
+for it to be judged on its merits.
+
+## How it was built
+
+The prototype was written with the help of **Claude** (Anthropic), through Claude Code. Most of the code was
+written by **Claude Opus 5.5**; later features and fixes were written by **Claude Fable 5.2**. The idea,
+its goals and the design decisions are mine; this does not imply any endorsement by Anthropic.
+
+## Licence
+
+Released under the MIT licence (see `LICENSE`): anyone may use, change and build on it, including commercially.
+
+---
+
+*M. M. Shamshiri — Independent Researcher*
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..2b8f25eb3ae7f916556af3f0447494e97a125398
--- /dev/null
+++ b/README.md
@@ -0,0 +1,216 @@
+# NLCL — Natural Language Computational Language
+
+**NLCL is an open-source prototype exploring natural language as a computational language.** It turns English instructions into semantic operations, applies them to a persistent intermediate representation (IR), and generates code for multiple domains.
+
+> Natural language is not merely an interface: it can be the programming language itself. Sentences become semantic tokens, tokens become computational structures, and those structures become a language-independent IR that can be compiled into cooperating modules.
+
+This project is an independent research prototype shared to invite feedback. It is not affiliated with or endorsed by Anthropic.
+
+## Screenshots
+
+A look at NLCL’s interface and workflow:
+
+
+
+
+
+
+
+
+
+
+
+
+## What NLCL does
+
+```text
+Natural-language instruction
+ → semantic tokens and candidate interpretations
+ → dry-run against a persistent state
+ → universal intermediate representation (IR)
+ → domain-specific code generation
+ → build, run, or simulate
+```
+
+The core runs offline using only the Python standard library. English instructions are handled by the offline parser. Optional language-model backends can help with non-Latin languages, interpretation, and code repair.
+
+## Quick start
+
+```bash
+python -m nlcl
+python -m nlcl examples/game.nl --run
+python -m nlcl examples/smart_greenhouse.nl --build
+python -m unittest discover -s tests
+```
+
+A short interactive example:
+
+```text
+> create an object
+System: What kind of object would you like to create? (game / python / embedded / ...)
+? a game object
+ created game object 'object'
+System: What properties should object have? (e.g. health, speed, movable, ...)
+> give it 100 health, make it movable, and add collision detection
+ object: {health: 100}
+ object: {movable: True}
+ object: {collision: True}
+> when health drops below 1, destroy it
+> build it
+```
+
+The same state can be represented in NLCL's IR:
+
+```text
+CREATE(domain=GAME, type=object, properties={"health": 100, "movable": true, "collision": true})
+BEHAVIOR(target=hero, behavior={"on": "update", "if": "health < 1", "do": [{"op": "destroy"}]})
+CONNECT(target=temp, dst=monitor, via=http, properties={"fields": ["temperature"], "interval_ms": 2000})
+```
+
+## Architecture
+
+NLCL combines three vocabulary mechanisms:
+
+| Mechanism | Description |
+|---|---|
+| Atomic tokens | Core operations such as `CREATE`, `DELETE`, and `CONNECT` (`nlcl/tokens.py`) |
+| Composite tokens | Ordered patterns that combine tokens into higher-level operations |
+| Adaptive vocabulary | Teach aliases and define commands; definitions are dry-run against a copy of the state before acceptance |
+
+The interpreter applies operations to a persistent state and asks for clarification when it cannot confidently determine the intended domain or operation. The knowledge base stores ontology, learned reliability, safety rules, and learned vocabulary. The weighting model uses measurable interpretation features to estimate confidence; `:why` explains a score.
+
+| Component | Location | Role |
+|---|---|---|
+| Parser | `nlcl/parser.py` | Offline English rule parser |
+| IR and interpreter | `nlcl/ir.py`, `nlcl/interpreter.py` | State, operations, and interpretation |
+| Knowledge base | `nlcl/kb/`, `nlcl/knowledge.py` | Ontology, reliability, and learned facts |
+| Learning and weighting | `nlcl/learn.py`, `nlcl/weights.py` | Learn rewrite rules and calibrate confidence |
+| Modules | `nlcl/modules/` | Domain-specific generators and tools |
+| Terminal | `nlcl/shell.py` | Interpret terminal requests and verify command effects in a sandbox |
+| Benchmark | `nlcl/bench/` | Reproducible evaluation suites |
+
+## Code-generation domains
+
+| Domain | Example output | Free tools and runtimes |
+|---|---|---|
+| `app` | Tkinter desktop app, packaging scripts, installable PWA | CPython, PyInstaller, browser |
+| `python` | Objects, services, hubs, and bridges | CPython |
+| `game` | Unity C#, Godot GDScript, HTML5 preview | Unity Personal, Godot, browser |
+| `embedded` | Arduino C++, MicroPython, PlatformIO projects | Arduino IDE, PlatformIO, Wokwi |
+| `hardware` | Verilog RTL, testbench, synthesis scripts | Icarus Verilog, GTKWave, Yosys |
+| `cpp` | C++17 classes, main loop, channels, CMake | g++, Clang, MSVC Build Tools |
+| `3d` | Three.js digital twin and Blender script | Browser, Blender |
+| `cad` | OpenSCAD parts and CadQuery models | OpenSCAD, CadQuery, FreeCAD |
+
+Modules are plugins: a module in `nlcl/modules/` that provides a `MODULE` can add a domain. Different domain entities can be connected with channel contracts such as HTTP, MQTT, serial, SPI, or I²C. A composed system can include `system.json` and a `SYSTEM.md` guide.
+
+## Example instructions
+
+The offline parser supports common instruction patterns, including:
+
+```text
+create 3 enemies with health 30 and color red
+create a platform called floor at position 0, 0
+create a state machine called door with states closed, open and locked
+make wheel a child of robot
+hero's speed should be 9
+when hero touches gold, increase hero score by 10 and destroy gold
+every 3 seconds, if state is red, set state to green
+```
+
+It is a rule-based prototype, not a general natural-language understanding system. It supports common sentence forms rather than all of English.
+
+## Optional language-model backends
+
+Backends are optional. Without a configured backend, the offline English parser still works. A backend can be used for non-Latin input, online interpretation, and assisted code fixes.
+
+| Backend | Environment variable |
+|---|---|
+| Ollama | Local configuration |
+| Groq | `GROQ_API_KEY` |
+| Gemini | `GEMINI_API_KEY` |
+| OpenRouter | `OPENROUTER_API_KEY` |
+| Cerebras | `CEREBRAS_API_KEY` |
+| Mistral | `MISTRAL_API_KEY` |
+| Hugging Face | `HF_TOKEN` |
+| GitHub Models | `GITHUB_TOKEN` |
+
+The first available backend is selected automatically. Set a model with `NLCL__MODEL` (for example, `NLCL_GROQ_MODEL`) or inspect the configuration with `:backend status`. Backend availability and free-tier limits depend on the provider.
+
+## Terminal assistance and safety
+
+NLCL can interpret requests such as listing files, copying or renaming files, and searching project contents. The terminal suite compares generated command effects with a reference operation in a sandbox. File-changing operations are designed to require confirmation and show proposed changes before they are applied.
+
+Code diagnostics can use installed tools such as Python, Node.js, C/C++ compilers, Icarus Verilog, Verilator, OpenSCAD, and Godot. Online code repair requires a configured language-model backend; without one, `:check` can still diagnose issues.
+
+## Benchmark results
+
+The latest supplied offline report is dated **2026-11-24 16:23** and evaluates held-out sentences. A result counts as correct when it produces the same resulting system state as the canonical instruction. The benchmark used knowledge-base version `9d1d36fffb91`.
+
+| Metric | Untrained | Trained | Trained, unseen intents only |
+|---|---:|---:|---:|
+| Test sentences | 184 | 184 | 24 |
+| Interpretation accuracy | 58.08% (95% CI: 50.5–65.3%) | 59.88% (95% CI: 52.3–67.0%) | 62.5% (95% CI: 42.7–78.8%) |
+| Silent error rate | 34.24% (95% CI: 27.8–41.4%) | 14.67% (95% CI: 10.3–20.5%) | 16.67% (95% CI: 6.7–35.9%) |
+| Precision when executing | 60.62% (95% CI: 52.9–67.9%) | 78.74% (95% CI: 70.8–85.0%) | 78.95% (95% CI: 56.7–91.5%) |
+| Out-of-scope inputs refused | 1/17 | 13/17 | — |
+| Asked instead of executing | 24 | 57 | 5 |
+| Calibration error (ECE; lower is better) | 0.302 | 0.1112 | 0.2023 |
+| AUROC for separating right from wrong | 0.9252 | 0.9469 | 0.8778 |
+| Median latency per sentence | 0.66 ms | 1.05 ms | 1.22 ms |
+| Area under risk-coverage curve (lower is better) | 0.1733 | 0.1577 | 0.1696 |
+
+Wilson 95% confidence intervals are shown for accuracy, silent error rate, and precision. The unseen-intent subset contains no out-of-scope examples, so refusal is not applicable (`0/0` in the raw report).
+
+### Learning curve
+
+| Training paraphrases per intent | Rules learned | Accuracy | Silent errors | Out-of-scope refused | ECE |
+|---:|---:|---:|---:|---:|---:|
+| 0 | 0 | 58.08% | 34.24% | 1/17 | 0.302 |
+| 1 | 1 | 58.08% | 23.37% | 12/17 | 0.2119 |
+| 2 | 1 | 58.08% | 18.48% | 13/17 | 0.1844 |
+| 3 | 3 | 59.88% | 14.67% | 13/17 | 0.1292 |
+
+### Terminal benchmark
+
+| Metric | Result |
+|---|---:|
+| Same file-system effect as the intended command | 59.46% (22/37 sentences) |
+| Executed with the wrong effect | 0/37 |
+| Generated Bash and PowerShell checks passed in a sandbox | 24/44 |
+| Unconfirmed destructive file actions | 0 |
+
+The `24/44` figure is the number of shell checks that passed, not a 100% verification rate. The report notes that `llm-direct` and `nlcl+teacher` were **not run** because no language-model backend was configured. NLCL produced identical interpretations on repeated runs for all **184/184** benchmark sentences across five runs. Offline token cost was zero; trained median latency was **1.05 ms** per sentence.
+
+These are prototype benchmark results on a small, author-created corpus. They show lower silent error rates and improved refusal and calibration after training in this run, but do not establish broad real-world performance. See the [pre-registered hypotheses](bench/HYPOTHESES.md), [latest benchmark report](bench/results/report.md), and [machine-readable results](bench/results/results.json) for methodology and full details.
+
+Run the offline benchmark with:
+
+```bash
+python -m nlcl.bench --backend off
+```
+
+To attempt the language-model comparisons, configure a supported backend and run:
+
+```bash
+python -m nlcl.bench --backend auto
+```
+
+## REPL commands
+
+Useful commands include `:help`, `:show`, `:ir`, `:trace on`, `:build`, `:run`, `:undo`, `:domains`, `:vocab`, `:teach `, `:backend status`, and `:quit`.
+
+## Limitations
+
+- The offline parser covers common English patterns, not unrestricted natural language.
+- Persian and other non-Latin input require an online backend.
+- Generated code is a starting point, not a verified production product. Toolchains may be needed to build or simulate non-Python targets.
+- Online interpretation and code repair depend on the selected model, provider availability, and API limits.
+- The benchmark is small and was created by the project author; its results should be treated as preliminary.
+- Dedicated hardware for semantic operations is outside the scope of this software prototype.
+
+## Credits and license
+
+The concept and design goals are by M. M. Shamshiri (2019); see [`PROPOSAL.md`](PROPOSAL.md). The prototype was developed with assistance from Claude through Claude Code. This does not imply endorsement by Anthropic.
+
+Released under the [MIT License](LICENSE).
diff --git a/bench/HYPOTHESES.md b/bench/HYPOTHESES.md
new file mode 100644
index 0000000000000000000000000000000000000000..b2827af66eff5dd53d76e0db3d68f4a279c934f8
--- /dev/null
+++ b/bench/HYPOTHESES.md
@@ -0,0 +1,55 @@
+# Pre-registered hypotheses (written 2026-11-16, before the first full benchmark run)
+
+The question this benchmark asks is **not** "does the system finish the task" (Terminal-Bench style) but
+**"when a person writes what they mean, does the system do exactly that — and does it know when it
+doesn't understand?"**. Results are reported whichever way they come out.
+
+Systems compared on the same sentences:
+
+| id | system |
+|---|---|
+| `nlcl-untrained` | NLCL rule interpreter, empty knowledge base |
+| `nlcl-trained` | NLCL after `train` on the training paraphrases (rules + evidence + weights learned into Prolog) |
+| `llm-direct` | a language model turns the sentence straight into the same IR / a shell command (needs an API key) |
+| `nlcl+teacher` | NLCL; below the execution weight it asks the language model and distils the answer into a rule (needs an API key) |
+
+## Predictions
+
+**H1 - silent errors.** `nlcl-trained` has a lower *silent error rate* (executed something that is not what was
+meant) than `nlcl-untrained` on held-out sentences, and lower than `llm-direct`.
+*Expected: strong effect against untrained; against llm-direct the effect may be small or reversed,
+because a good model rarely misreads simple instructions.*
+
+**H2 - nonsense.** `nlcl-trained` refuses to execute at least 2/3 of out-of-scope / meaningless sentences;
+`llm-direct` executes more of them (it tends to produce *some* program for any input).
+
+**H3 - calibration.** The NLCL weight is calibrated after training (ECE < 0.15 on held-out sentences) and
+separates right from wrong interpretations (AUROC > 0.85). A direct model gives no comparable number.
+
+**H4 - accuracy (expected loss).** On free paraphrases `llm-direct` has **higher** interpretation accuracy than
+any offline NLCL variant. NLCL's offline accuracy on unseen paraphrases is expected to be well below 70%.
+`nlcl+teacher` should approach `llm-direct` accuracy while executing fewer wrong things than `llm-direct`.
+
+**H5 - determinism.** NLCL produces byte-identical interpretations on repeated runs (100%). A model at
+temperature 0 is expected to be below 100% on at least some sentences.
+
+**H6 - verified terminal commands.** Every terminal command NLCL executes is verified: running the generated
+bash and PowerShell text in a sandbox gives exactly the file-system effect of the reference meaning (100%).
+A model writing shell text directly has no such guarantee; its commands are scored by the same sandbox check.
+
+**H7 - destructive actions.** NLCL never changes or deletes files without first showing the exact diff and
+getting confirmation (0 unconfirmed destructive actions).
+
+**H8 - learning.** Held-out accuracy and nonsense refusal increase with the amount of training data, without
+any model retraining; every learned rule is a readable Prolog fact.
+
+**H9 - cost.** NLCL offline: 0 tokens, median latency < 5 ms per sentence. `llm-direct`: tokens > 0, latency in
+seconds.
+
+## Known threats to validity
+
+- The NLCL parser and the corpus were written by the same author (with Claude); training paraphrases were
+ phrased without filtering, but bias toward the parser's style cannot be excluded. The held-out split was
+ not used to change the parser.
+- Small corpus (35 intents, ~6 paraphrases each, 24 nonsense sentences): report effect sizes, not significance.
+- One language model per run; results depend on the model chosen.
diff --git a/bench/results/report.md b/bench/results/report.md
new file mode 100644
index 0000000000000000000000000000000000000000..7c9cd5154ac29e0eac7158699273593357fe2ec4
--- /dev/null
+++ b/bench/results/report.md
@@ -0,0 +1,118 @@
+# NLCL benchmark report (2026-11-17 15:57)
+
+Held-out sentences only (never used for training). Correct = same resulting system state as the canonical sentence. Pre-registered hypotheses: `bench/HYPOTHESES.md`.
+
+> **Note:** llm-direct and nlcl+teacher were NOT run: no language-model backend (set a free API key, see ':backend status', then run again).
+
+## Fidelity
+
+| metric | nlcl-untrained | nlcl-trained |
+|---|---|---|
+| interpretation accuracy (valid sentences) | 0.4476 | 0.4667 |
+| executed something not meant (silent error rate) | 0.4103 | 0.2393 |
+| precision when it executes | 0.4947 | 0.6364 |
+| nonsense / out-of-scope refused | 1/12 | 9/12 |
+| asked instead of executing | 22 | 40 |
+| all paraphrases of an intent right | 0.0571 | 0.0857 |
+| calibration error of the weight (ECE, lower is better) | 0.3816 | 0.1926 |
+| weight separates right/wrong (AUROC) | 0.8966 | 0.9146 |
+| median latency per sentence (ms) | 0.87 | 0.8 |
+
+## Risk / coverage of the trained weight
+
+Executing only sentences whose weight reaches the threshold (the rest are asked about):
+
+| weight threshold | share executed | precision of what is executed | wrong executions |
+|---|---|---|---|
+| 0.0 | 0.889 | 0.471 | 55 |
+| 0.35 | 0.658 | 0.636 | 28 |
+| 0.5 | 0.641 | 0.64 | 27 |
+| 0.6 | 0.573 | 0.716 | 19 |
+| 0.7 | 0.547 | 0.75 | 16 |
+| 0.8 | 0.538 | 0.762 | 15 |
+| 0.9 | 0.47 | 0.745 | 14 |
+
+## Learning curve (no model retraining: rules, evidence and weights in Prolog)
+
+| training paraphrases per intent | rules learned | accuracy | silent errors | nonsense refused | ECE |
+|---|---|---|---|---|---|
+| 0 | 0 | 0.4476 | 0.4103 | 1/12 | 0.3816 |
+| 1 | 1 | 0.4476 | 0.2479 | 9/12 | 0.2654 |
+| 2 | 1 | 0.4476 | 0.2479 | 9/12 | 0.2358 |
+| 3 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
+| 4 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
+| 5 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
+| 6 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
+| 7 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
+| 8 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
+| 9 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
+
+## Terminal
+
+| metric | nlcl-trained |
+|---|---|
+| same file-system effect as the meant command | 0.5758 |
+| executed with the wrong effect | 0.0 |
+| generated bash + PowerShell verified in a sandbox | 21/38 |
+| files changed/deleted without showing a diff first | 0 |
+
+## Determinism
+
+Identical interpretation on every repeated run: nlcl: 117/117
+
+## Cost
+
+NLCL offline: 0 tokens, median 0.8 ms per sentence.
+
+## What the trained interpreter learned (Prolog facts)
+
+```prolog
+% NLCL learned knowledge - written 2026-11-17 15:57:33
+% (plain Prolog facts: edit, delete or load them in SWI-Prolog)
+
+% rewrite/3
+rewrite(['store\'s'],[store],1).
+rewrite([get,rid,of],[delete],1).
+rewrite([the,game],[],1).
+
+% reliability/3
+reliability(frame(behavior),18,1).
+reliability(frame(connect_to),2,0).
+reliability(frame(create_object),22,4).
+reliability(frame(delete_object),5,0).
+reliability(frame(move_object),0,1).
+reliability(frame(rename_object),2,0).
+reliability(frame(set_property),12,13).
+reliability(frame(special),11,0).
+reliability(intent(archive),3,0).
+reliability(intent(copy),3,0).
+reliability(intent(count_files),3,0).
+reliability(intent(count_lines),3,0).
+reliability(intent(delete),3,0).
+reliability(intent(list_files),3,0).
+reliability(intent(make_dir),3,0).
+reliability(intent(move),3,0).
+reliability(intent(replace_text),3,0).
+reliability(intent(search_text),3,0).
+reliability(intent(show_file),3,0).
+
+% param/2
+param(bias,-1.11072).
+param(coverage,2.257904).
+param(dry_errors,-2.4).
+param(errors,-2.2).
+param(frame_rel,0.858535).
+param(fuzzy,-0.9).
+param(inferred,-0.404714).
+param(llm,0.4).
+param(missing_paths,-1.8).
+param(n_ops,-0.292096).
+param(notes,-0.65517).
+param(novel,-1.853353).
+param(question,-0.6).
+param(reliability,0.957997).
+param(shell,1.213662).
+param(unknown,-0.9).
+param(verbless,-1.796907).
+param(warnings,-0.25).
+```
diff --git a/bench/results/results.json b/bench/results/results.json
new file mode 100644
index 0000000000000000000000000000000000000000..70d0027cc5aee73041e4b3763d836d52e181c4bf
--- /dev/null
+++ b/bench/results/results.json
@@ -0,0 +1,484 @@
+{
+ "date": "2026-11-17 15:57",
+ "systems": {
+ "nlcl-untrained": {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4476,
+ "executed": 95,
+ "precision_when_executed": 0.4947,
+ "silent_error_rate": 0.4103,
+ "asked": 22,
+ "nonsense_caught": "1/12",
+ "median_ms": 0.87,
+ "calibration_ece": 0.3816,
+ "calibration_brier": 0.3414,
+ "calibration_auroc": 0.8966,
+ "paraphrase_consistency": 0.0571
+ },
+ "nlcl-trained": {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4667,
+ "executed": 77,
+ "precision_when_executed": 0.6364,
+ "silent_error_rate": 0.2393,
+ "asked": 40,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.8,
+ "calibration_ece": 0.1926,
+ "calibration_brier": 0.1658,
+ "calibration_auroc": 0.9146,
+ "paraphrase_consistency": 0.0857,
+ "rules_learned": 3
+ }
+ },
+ "learning_curve": [
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4476,
+ "executed": 95,
+ "precision_when_executed": 0.4947,
+ "silent_error_rate": 0.4103,
+ "asked": 22,
+ "nonsense_caught": "1/12",
+ "median_ms": 0.62,
+ "calibration_ece": 0.3816,
+ "calibration_brier": 0.3414,
+ "calibration_auroc": 0.8966,
+ "paraphrases_per_intent": 0,
+ "rules_learned": 0
+ },
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4476,
+ "executed": 76,
+ "precision_when_executed": 0.6184,
+ "silent_error_rate": 0.2479,
+ "asked": 41,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.89,
+ "calibration_ece": 0.2654,
+ "calibration_brier": 0.2147,
+ "calibration_auroc": 0.881,
+ "paraphrases_per_intent": 1,
+ "rules_learned": 1
+ },
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4476,
+ "executed": 76,
+ "precision_when_executed": 0.6184,
+ "silent_error_rate": 0.2479,
+ "asked": 41,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.75,
+ "calibration_ece": 0.2358,
+ "calibration_brier": 0.1884,
+ "calibration_auroc": 0.9061,
+ "paraphrases_per_intent": 2,
+ "rules_learned": 1
+ },
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4667,
+ "executed": 77,
+ "precision_when_executed": 0.6364,
+ "silent_error_rate": 0.2393,
+ "asked": 40,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.84,
+ "calibration_ece": 0.1926,
+ "calibration_brier": 0.1658,
+ "calibration_auroc": 0.9146,
+ "paraphrases_per_intent": 3,
+ "rules_learned": 3
+ },
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4667,
+ "executed": 77,
+ "precision_when_executed": 0.6364,
+ "silent_error_rate": 0.2393,
+ "asked": 40,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.88,
+ "calibration_ece": 0.1926,
+ "calibration_brier": 0.1658,
+ "calibration_auroc": 0.9146,
+ "paraphrases_per_intent": 4,
+ "rules_learned": 3
+ },
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4667,
+ "executed": 77,
+ "precision_when_executed": 0.6364,
+ "silent_error_rate": 0.2393,
+ "asked": 40,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.97,
+ "calibration_ece": 0.1926,
+ "calibration_brier": 0.1658,
+ "calibration_auroc": 0.9146,
+ "paraphrases_per_intent": 5,
+ "rules_learned": 3
+ },
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4667,
+ "executed": 77,
+ "precision_when_executed": 0.6364,
+ "silent_error_rate": 0.2393,
+ "asked": 40,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.79,
+ "calibration_ece": 0.1926,
+ "calibration_brier": 0.1658,
+ "calibration_auroc": 0.9146,
+ "paraphrases_per_intent": 6,
+ "rules_learned": 3
+ },
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4667,
+ "executed": 77,
+ "precision_when_executed": 0.6364,
+ "silent_error_rate": 0.2393,
+ "asked": 40,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.78,
+ "calibration_ece": 0.1926,
+ "calibration_brier": 0.1658,
+ "calibration_auroc": 0.9146,
+ "paraphrases_per_intent": 7,
+ "rules_learned": 3
+ },
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4667,
+ "executed": 77,
+ "precision_when_executed": 0.6364,
+ "silent_error_rate": 0.2393,
+ "asked": 40,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.81,
+ "calibration_ece": 0.1926,
+ "calibration_brier": 0.1658,
+ "calibration_auroc": 0.9146,
+ "paraphrases_per_intent": 8,
+ "rules_learned": 3
+ },
+ {
+ "sentences": 117,
+ "interpretation_accuracy": 0.4667,
+ "executed": 77,
+ "precision_when_executed": 0.6364,
+ "silent_error_rate": 0.2393,
+ "asked": 40,
+ "nonsense_caught": "9/12",
+ "median_ms": 0.81,
+ "calibration_ece": 0.1926,
+ "calibration_brier": 0.1658,
+ "calibration_auroc": 0.9146,
+ "paraphrases_per_intent": 9,
+ "rules_learned": 3
+ }
+ ],
+ "notes": [
+ "llm-direct and nlcl+teacher were NOT run: no language-model backend (set a free API key, see ':backend status', then run again)."
+ ],
+ "learned_kb": "% NLCL learned knowledge - written 2026-11-17 15:57:33\n% (plain Prolog facts: edit, delete or load them in SWI-Prolog)\n\n% rewrite/3\nrewrite(['store\\'s'],[store],1).\nrewrite([get,rid,of],[delete],1).\nrewrite([the,game],[],1).\n\n% reliability/3\nreliability(frame(behavior),18,1).\nreliability(frame(connect_to),2,0).\nreliability(frame(create_object),22,4).\nreliability(frame(delete_object),5,0).\nreliability(frame(move_object),0,1).\nreliability(frame(rename_object),2,0).\nreliability(frame(set_property),12,13).\nreliability(frame(special),11,0).\nreliability(intent(archive),3,0).\nreliability(intent(copy),3,0).\nreliability(intent(count_files),3,0).\nreliability(intent(count_lines),3,0).\nreliability(intent(delete),3,0).\nreliability(intent(list_files),3,0).\nreliability(intent(make_dir),3,0).\nreliability(intent(move),3,0).\nreliability(intent(replace_text),3,0).\nreliability(intent(search_text),3,0).\nreliability(intent(show_file),3,0).\n\n% param/2\nparam(bias,-1.11072).\nparam(coverage,2.257904).\nparam(dry_errors,-2.4).\nparam(errors,-2.2).\nparam(frame_rel,0.858535).\nparam(fuzzy,-0.9).\nparam(inferred,-0.404714).\nparam(llm,0.4).\nparam(missing_paths,-1.8).\nparam(n_ops,-0.292096).\nparam(notes,-0.65517).\nparam(novel,-1.853353).\nparam(question,-0.6).\nparam(reliability,0.957997).\nparam(shell,1.213662).\nparam(unknown,-0.9).\nparam(verbless,-1.796907).\nparam(warnings,-0.25).\n\n",
+ "selective": [
+ {
+ "threshold": 0.0,
+ "coverage": 0.889,
+ "precision": 0.471,
+ "wrong_executions": 55
+ },
+ {
+ "threshold": 0.35,
+ "coverage": 0.658,
+ "precision": 0.636,
+ "wrong_executions": 28
+ },
+ {
+ "threshold": 0.5,
+ "coverage": 0.641,
+ "precision": 0.64,
+ "wrong_executions": 27
+ },
+ {
+ "threshold": 0.6,
+ "coverage": 0.573,
+ "precision": 0.716,
+ "wrong_executions": 19
+ },
+ {
+ "threshold": 0.7,
+ "coverage": 0.547,
+ "precision": 0.75,
+ "wrong_executions": 16
+ },
+ {
+ "threshold": 0.8,
+ "coverage": 0.538,
+ "precision": 0.762,
+ "wrong_executions": 15
+ },
+ {
+ "threshold": 0.9,
+ "coverage": 0.47,
+ "precision": 0.745,
+ "wrong_executions": 14
+ }
+ ],
+ "determinism": {
+ "nlcl": "117/117",
+ "runs": 5
+ },
+ "terminal": {
+ "nlcl-trained": {
+ "sentences": 33,
+ "effect_accuracy": 0.5758,
+ "silent_error_rate": 0.0,
+ "commands_verified": "21/38",
+ "unconfirmed_destructive_actions": 0,
+ "rows": [
+ {
+ "text": "display all python files in the folder src",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "ls the python files in src",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "which python files are in src",
+ "right": false,
+ "weight": 0.0,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "count all .log files in logs",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "how many log files does logs have",
+ "right": false,
+ "weight": 0.0,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "tell me how many log files are in logs",
+ "right": false,
+ "weight": 0.0,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "create a new directory named backup",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "add a folder called backup",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "I need a folder called backup",
+ "right": false,
+ "weight": 0.517,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "erase all .tmp files in all subfolders",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "clean up the temporary files everywhere",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "wipe all .tmp files recursively",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "copy the file notes.txt to backup.txt",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "copy notes.txt into backup.txt",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "clone notes.txt to backup.txt",
+ "right": false,
+ "weight": 0.019,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "mv data.csv to people.csv",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "rename data.csv as people.csv",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "data.csv should be renamed to people.csv",
+ "right": false,
+ "weight": 0.019,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "show me the first 2 lines in notes.txt",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "head 2 lines of notes.txt",
+ "right": false,
+ "weight": 0.017,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "read the first 2 lines of notes.txt",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "grep 'TODO' in python files",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "search all python files for 'TODO'",
+ "right": false,
+ "weight": 0.017,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "where does 'TODO' appear in python files",
+ "right": false,
+ "weight": 0.0,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "how many lines does data.csv have",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "line count of data.csv",
+ "right": false,
+ "weight": 0.017,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "tell me the number of lines in data.csv",
+ "right": false,
+ "weight": 0.017,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "change 'apple' to 'pear' in notes.txt",
+ "right": false,
+ "weight": 0.433,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "swap 'apple' for 'pear' in notes.txt",
+ "right": false,
+ "weight": 0.0,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "replace every 'apple' by 'pear' in the file notes.txt",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "make a zip of src called src.zip",
+ "right": false,
+ "weight": 0.517,
+ "source": "rules",
+ "executed": false
+ },
+ {
+ "text": "pack src into src.zip",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ },
+ {
+ "text": "compress the folder src to src.zip",
+ "right": true,
+ "weight": 0.971,
+ "source": "shell",
+ "executed": true
+ }
+ ]
+ }
+ },
+ "cost": {
+ "nlcl_median_ms": 0.8,
+ "nlcl_tokens": 0
+ }
+}
\ No newline at end of file
diff --git a/examples/counter_app.nl b/examples/counter_app.nl
new file mode 100644
index 0000000000000000000000000000000000000000..6f46e8d6f38d5f2fc985fe54e6308e28972da3e7
--- /dev/null
+++ b/examples/counter_app.nl
@@ -0,0 +1,16 @@
+# A desktop + mobile application described in natural language.
+# Output: app.py (Windows/macOS/Linux, Tkinter) and web/ (installable PWA for Android/iOS).
+:name tally
+create an app called tally with title "Tally Counter" and size 360 by 320
+add a label called display to tally with value 0
+add a button called plus to tally with text "+1"
+add a button called reset to tally with text "Reset"
+add an input called step to tally with value 1 and label "Step"
+add a checkbox called auto to tally with text "Count automatically"
+add a progress called bar to tally with max 20
+when plus is pressed, increase value of display by value of step
+when reset is pressed, set value of display to 0
+every 1 second, if checked of auto is on, increase value of display by 1
+when value of display changes, set value of bar to value of display
+when value of display is above 19, print 'limit reached: {value}'
+build it and run it
diff --git a/examples/fpga_blinker.nl b/examples/fpga_blinker.nl
new file mode 100644
index 0000000000000000000000000000000000000000..dc34219102bcd79a45f663992d5a62e0aeedbe3a
--- /dev/null
+++ b/examples/fpga_blinker.nl
@@ -0,0 +1,9 @@
+# Hardware description in natural language (Verilog + testbench)
+:name blinky
+use hardware
+create a counter called tick with width 8
+create a register called leds with width 4
+every 500 ms, increase leds by 1
+when leds is 15, set leds to 0
+connect tick to leds via wire
+build and run it
diff --git a/examples/game.nl b/examples/game.nl
new file mode 100644
index 0000000000000000000000000000000000000000..b91b9a4870be934c40fb2828913295c92f209f07
--- /dev/null
+++ b/examples/game.nl
@@ -0,0 +1,15 @@
+# The interaction from the proposal, then a small playable game.
+:name arena
+create an object
+a game object called hero
+give it 100 health, make it movable, and add collision detection
+set speed to 5 and score 0
+color blue
+when health drops below 1, destroy it
+when space is pressed, jump
+every 2 seconds, print 'hero health {health}, score {score}'
+create 3 enemies with health 30 and color red
+when an enemy touches hero, decrease hero health by 10
+create a coin called gold with value 10
+when hero touches gold, increase hero score by 10 and destroy gold
+build and run it
diff --git a/examples/smart_greenhouse.nl b/examples/smart_greenhouse.nl
new file mode 100644
index 0000000000000000000000000000000000000000..7be6027016a77de01b822b4870d3651e130f960d
--- /dev/null
+++ b/examples/smart_greenhouse.nl
@@ -0,0 +1,23 @@
+# A multi-module system described in natural language:
+# ESP32 firmware + FPGA fan PWM + Python monitor + 3D digital twin + 3D-printed enclosure.
+:name greenhouse
+add an esp32 called board
+add a temperature sensor called temp to the board on pin 4 with temperature 20
+add a fan called fan to the board on pin 5
+add a button called btn to the board on pin 0
+when temperature is above 30, turn on the fan
+when temperature is below 25, turn off the fan
+when the btn is pressed, toggle the fan
+
+create a python dashboard called monitor with threshold 30
+connect temp to monitor via http sending temperature every 2 seconds
+when temperature is above threshold, print 'ALERT: greenhouse at {temperature} C'
+
+create a 3d tank called twin with color green
+connect monitor to twin via http sending temperature
+
+create a hardware pwm called fan_pwm with duty 0 and width 8
+connect board to fan_pwm via spi sending duty
+
+create an enclosure called case for the board with wall 2
+build and run it
diff --git a/nlcl/__init__.py b/nlcl/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..918b5d1bed8fd6d67b945d7ba734fac48e58259c
--- /dev/null
+++ b/nlcl/__init__.py
@@ -0,0 +1,6 @@
+"""NLCL - Natural Language Computational Language.
+
+Natural language -> semantic tokens -> computational structure -> universal IR
+-> multi-module code generation -> execution.
+"""
+__version__ = "0.1.0"
diff --git a/nlcl/__main__.py b/nlcl/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..126c891aa1f32dad94a7c87cc256480da89813e9
--- /dev/null
+++ b/nlcl/__main__.py
@@ -0,0 +1,78 @@
+"""python -m nlcl [script.nl] [options]"""
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+from . import __version__
+from .runtime import HELP, Session
+
+
+def main(argv=None) -> int:
+ for s in (sys.stdout, sys.stderr):
+ try:
+ s.reconfigure(encoding="utf-8")
+ except (AttributeError, ValueError):
+ pass
+ ap = argparse.ArgumentParser(prog="nlcl", description="Natural Language Computational Language runtime")
+ ap.add_argument("script", nargs="?", help="file with one natural-language instruction per line")
+ ap.add_argument("-p", "--project", default="project", help="system/project name")
+ ap.add_argument("-o", "--out", help="build directory (default ./build/)")
+ ap.add_argument("-b", "--backend", help="LLM backend: auto|off|ollama|groq|gemini|openrouter|cerebras|mistral|huggingface|github")
+ ap.add_argument("-m", "--mode", default="hybrid", choices=["rules", "hybrid", "llm"])
+ ap.add_argument("--vocab", default=str(Path.home() / ".nlcl" / "vocab.json"), help="adaptive vocabulary file")
+ ap.add_argument("--trace", action="store_true", help="show tokens, composite tokens and IR for each line")
+ ap.add_argument("--yes", action="store_true", help="auto-accept vocabulary proposals")
+ ap.add_argument("--build", action="store_true", help="build after running the script")
+ ap.add_argument("--run", action="store_true", help="build and run after the script")
+ ap.add_argument("-c", "--command", action="append", help="instruction to execute (repeatable)")
+ a = ap.parse_args(argv)
+
+ s = Session(a.project, backend=a.backend, mode=a.mode, outdir=a.out, vocab_path=a.vocab,
+ trace=a.trace, auto_yes=a.yes)
+
+ def emit(lines):
+ for ln in lines:
+ print(ln, flush=True)
+
+ lines = []
+ if a.script:
+ lines = Path(a.script).read_text(encoding="utf-8-sig").splitlines()
+ if a.command:
+ lines += a.command
+ if lines:
+ for ln in lines:
+ if ln.strip() and not ln.strip().startswith("#"):
+ print(f"> {ln.strip()}")
+ try:
+ emit(s.handle(ln))
+ except EOFError:
+ return 0
+ if s.pending:
+ print(f"(unanswered question: {s.pending.text})")
+ if a.run:
+ emit(s.run())
+ elif a.build and s.dirty: # a script ending in "build it" is not built twice
+ emit(s.build())
+ return 0
+
+ print(f"NLCL {__version__} - natural language computational language. ':help' for help, ':quit' to exit.")
+ print(f"backend: {s.backend or 'offline rules'} domains: {', '.join(s.modules)}")
+ while True:
+ try:
+ prompt = "? " if s.pending or s.llm_question else "> "
+ line = input(prompt)
+ except (EOFError, KeyboardInterrupt):
+ print()
+ return 0
+ try:
+ emit(s.handle(line))
+ except EOFError:
+ return 0
+ except Exception as e: # never crash the REPL
+ print(f"! internal error: {type(e).__name__}: {e}")
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/nlcl/bench/__init__.py b/nlcl/bench/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86
--- /dev/null
+++ b/nlcl/bench/__init__.py
@@ -0,0 +1 @@
+
diff --git a/nlcl/bench/__main__.py b/nlcl/bench/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8660ee6ba4c6b62a4a23e7a085bc19095ec8884
--- /dev/null
+++ b/nlcl/bench/__main__.py
@@ -0,0 +1,3 @@
+from .run import main
+import sys
+sys.exit(main())
diff --git a/nlcl/bench/corpus.py b/nlcl/bench/corpus.py
new file mode 100644
index 0000000000000000000000000000000000000000..51a62bbdd5d2df3b6faa655dbcf70e91cf465557
--- /dev/null
+++ b/nlcl/bench/corpus.py
@@ -0,0 +1,206 @@
+"""Benchmark corpus: intents with a canonical sentence, training paraphrases and HELD-OUT test paraphrases,
+plus out-of-scope / nonsense sentences for which the right behaviour is to NOT execute (ask instead).
+
+The paraphrases were written as different people would phrase the request; they were not filtered by
+whether the parser already understands them. Test paraphrases are never used for training.
+"""
+from __future__ import annotations
+
+HERO = ["create a game player called hero with health 100"]
+STORE = ["create a python service called store with stock 10 and price 5"]
+BOARD = ["add an esp32 called board", "add a led called lamp to board on pin 2",
+ "add a temperature sensor called temp to board with temperature 20"]
+FSM = ["create a hardware state machine called door with states closed, open and locked"]
+APP = ['create an app called tally with title "Tally"', "add a label called display to tally with value 0",
+ 'add a button called plus to tally with text "+1"']
+TWIN = ["create a 3d cube called box with color red"]
+
+INTENTS = [
+ # ------------------------------------------------------------------ creation
+ dict(id="mk_player", context=[], gold=HERO,
+ train=["make a game player named hero with 100 health",
+ "I want a game player called hero that has 100 health",
+ "spawn a game player called hero, health 100"],
+ test=["please create a player for the game called hero with a health of 100",
+ "new game player hero with health 100",
+ "build a game player called hero and give it 100 health"]),
+ dict(id="mk_enemies", context=[], gold=["create 3 game enemies with health 30"],
+ train=["make three game enemies with 30 health",
+ "spawn 3 game enemies having health 30",
+ "add 3 enemies to the game with health 30"],
+ test=["create three game enemies, each with health 30",
+ "I need 3 game enemies with 30 health",
+ "generate 3 game foes with health 30"]),
+ dict(id="mk_service", context=[], gold=STORE,
+ train=["make a python service named store with 10 stock and price 5",
+ "create a store service in python with stock 10 and price 5",
+ "new python service called store, stock 10, price 5"],
+ test=["I'd like a python service called store with a stock of 10 and a price of 5",
+ "set up a python service called store with stock 10 and price 5",
+ "please make a python service store with stock 10 and price 5"]),
+ dict(id="mk_board", context=[], gold=["add an esp32 called board"],
+ train=["create an esp32 named board", "I need an esp32 called board", "make an esp32 board called board"],
+ test=["add a new esp32 called board", "put an esp32 called board in the project", "get an esp32 named board"]),
+ dict(id="mk_led", context=["add an esp32 called board"], gold=["add a led called lamp to board on pin 2"],
+ train=["connect a led called lamp to board on pin 2", "create a led named lamp on board at pin 2",
+ "add an led called lamp to the board on pin 2"],
+ test=["put a led called lamp on the board using pin 2", "attach a led named lamp to board on pin 2",
+ "the board needs a led called lamp on pin 2"]),
+ dict(id="mk_fsm", context=[], gold=FSM,
+ train=["make a hardware state machine named door with states closed, open and locked",
+ "create a state machine in hardware called door with the states closed, open, locked",
+ "new hardware state machine door with states closed, open and locked"],
+ test=["build a hardware state machine called door having states closed, open and locked",
+ "create a hardware fsm called door with states closed, open and locked",
+ "define a hardware state machine door whose states are closed, open and locked"]),
+ dict(id="mk_cube", context=[], gold=TWIN,
+ train=["make a red 3d cube called box", "create a 3d cube named box with red color",
+ "add a 3d cube called box, color red"],
+ test=["create a red cube in 3d called box", "new 3d cube box colored red",
+ "I want a 3d cube called box that is red"]),
+ dict(id="mk_enclosure", context=[], gold=["create a cad enclosure called case with wall 2"],
+ train=["make a cad enclosure named case with wall 2", "create an enclosure in cad called case, wall 2",
+ "new cad enclosure case with a wall of 2"],
+ test=["design a cad enclosure called case with wall 2", "create a cad enclosure called case with 2 mm walls",
+ "I need a cad enclosure named case whose wall is 2"]),
+ dict(id="mk_app", context=[], gold=['create an app called tally with title "Tally"'],
+ train=['make an app named tally with title "Tally"', 'create a new app called tally titled "Tally"',
+ 'I want an app called tally with the title "Tally"'],
+ test=['build an application called tally with title "Tally"', 'create an app tally with title "Tally"',
+ 'please create an app named tally whose title is "Tally"']),
+ # ------------------------------------------------------------------ properties
+ dict(id="set_speed", context=HERO, gold=["set speed of hero to 20"],
+ train=["give hero 20 speed", "hero's speed should be 20", "change the speed of hero to 20"],
+ test=["make hero's speed 20", "the speed of hero is 20", "set hero speed to 20"]),
+ dict(id="set_health", context=HERO, gold=["set health of hero to 50"],
+ train=["set hero's hp to 50", "change hero's health to 50", "give hero 50 health"],
+ test=["hero's health should be 50", "update the health of hero to 50", "set the hit points of hero to 50"]),
+ dict(id="set_color", context=TWIN, gold=["set color of box to blue"],
+ train=["make box blue", "change the color of box to blue", "box's color should be blue"],
+ test=["paint box blue", "set the colour of box to blue", "turn box blue"]),
+ dict(id="set_movable", context=HERO, gold=["make hero movable"],
+ train=["hero should be movable", "make the hero movable", "let hero move"],
+ test=["allow hero to move", "hero must be movable", "set hero movable"]),
+ dict(id="remove_prop", context=HERO + ["set speed of hero to 20"], gold=["remove speed from hero"],
+ train=["delete the speed of hero", "remove hero's speed", "take the speed off hero"],
+ test=["get rid of hero's speed", "drop speed from hero", "erase the speed of hero"]),
+ dict(id="rename", context=HERO, gold=["rename hero to knight"],
+ train=["call hero knight", "change hero's name to knight", "rename the hero to knight"],
+ test=["hero should be called knight", "name hero knight", "change the name of hero to knight"]),
+ dict(id="delete_entity", context=HERO, gold=["delete hero"],
+ train=["remove hero", "destroy the hero", "get rid of hero"],
+ test=["erase hero", "remove the hero from the game", "throw away hero"]),
+ # ------------------------------------------------------------------ behaviours
+ dict(id="beh_die", context=HERO, gold=["when health of hero is below 1, destroy hero"],
+ train=["when hero's health drops below 1, destroy it", "destroy hero when its health is below 1",
+ "if hero's health is less than 1, destroy hero"],
+ test=["when the health of hero goes below 1 destroy hero", "hero dies when its health is under 1",
+ "kill hero once its health falls below 1"]),
+ dict(id="beh_timer", context=STORE, gold=["every 2 seconds, decrease stock of store by 1"],
+ train=["every two seconds, reduce store's stock by 1", "decrease the stock of store by 1 every 2 seconds",
+ "every 2 seconds lower stock of store by 1"],
+ test=["each 2 seconds, decrease store's stock by 1", "every 2000 ms, decrease stock of store by 1",
+ "take 1 from the stock of store every 2 seconds"]),
+ dict(id="beh_key", context=HERO, gold=["when space is pressed, hero jumps"],
+ train=["when the player presses space, hero jumps", "hero jumps when space is pressed",
+ "if space is pressed, hero jumps"],
+ test=["when I press space, hero jumps", "pressing space makes hero jump", "on space, hero jumps"]),
+ dict(id="beh_button", context=APP, gold=["when plus is pressed, increase value of display by 1"],
+ train=["when plus is clicked, increase value of display by 1", "if plus is pressed, add 1 to value of display",
+ "increase display's value by 1 when plus is pressed"],
+ test=["clicking plus adds 1 to the value of display", "when plus is pressed, raise value of display by 1",
+ "when the plus button is pressed, increment value of display by 1"]),
+ dict(id="beh_sensor", context=BOARD, gold=["when temperature of temp is above 30, turn on lamp"],
+ train=["when temp's temperature is above 30, turn on lamp", "turn on lamp when temperature of temp is above 30",
+ "if the temperature of temp is greater than 30, turn on lamp"],
+ test=["when temp reads more than 30 degrees, switch on lamp", "when temperature of temp exceeds 30, turn lamp on",
+ "lamp should turn on when temp's temperature is over 30"]),
+ dict(id="beh_fsm", context=FSM, gold=["every 3 seconds, if state of door is closed, set state of door to open"],
+ train=["every 3 seconds, if door's state is closed, set door's state to open",
+ "every three seconds, when state of door is closed, set state of door to open",
+ "every 3 s, if state of door is closed, set door state to open"],
+ test=["each 3 seconds, if the door is closed, open it", "every 3 seconds, change door's state from closed to open",
+ "every 3 seconds if state of door equals closed set state of door to open"]),
+ # ------------------------------------------------------------------ links
+ dict(id="connect", context=BOARD + ["create a python dashboard called monitor"],
+ gold=["connect temp to monitor via http sending temperature every 2 seconds"],
+ train=["link temp to monitor via http sending temperature every 2 seconds",
+ "connect temp to monitor over http, sending temperature every 2 seconds",
+ "send temperature from temp to monitor via http every 2 seconds"],
+ test=["wire temp to monitor via http sending temperature every 2 seconds",
+ "hook up temp to monitor over http sending temperature every 2 seconds",
+ "connect the temp sensor to monitor via http, sending temperature every 2 seconds"]),
+ dict(id="parent", context=["create a cpp object called robot", "create a cpp object called wheel"],
+ gold=["put wheel inside robot"],
+ train=["make wheel a child of robot", "wheel is part of robot", "place wheel in robot"],
+ test=["attach wheel to robot", "wheel belongs inside robot", "move wheel into robot"]),
+ # ------------------------------------------------------------------ terminal
+ dict(id="t_list_py", context=[], gold=["list all python files in src"],
+ train=["show me the python files in src", "list the .py files in src", "what python files are in src"],
+ test=["display all python files in the folder src", "ls the python files in src", "which python files are in src"]),
+ dict(id="t_count_logs", context=[], gold=["count the log files in logs"],
+ train=["how many log files are in logs", "how many .log files are there in logs", "number of log files in logs"],
+ test=["count all .log files in logs", "how many log files does logs have", "tell me how many log files are in logs"]),
+ dict(id="t_mkdir", context=[], gold=["create a folder called backup"],
+ train=["make a new folder named backup", "make a directory called backup", "mkdir backup"],
+ test=["create a new directory named backup", "add a folder called backup", "I need a folder called backup"]),
+ dict(id="t_delete_tmp", context=[], gold=["delete all .tmp files recursively"],
+ train=["remove all temporary files recursively", "delete every .tmp file including subfolders",
+ "get rid of all tmp files recursively"],
+ test=["erase all .tmp files in all subfolders", "clean up the temporary files everywhere",
+ "wipe all .tmp files recursively"]),
+ dict(id="t_copy", context=[], gold=["copy notes.txt to backup.txt"],
+ train=["duplicate notes.txt to backup.txt", "make a copy of notes.txt called backup.txt", "cp notes.txt to backup.txt"],
+ test=["copy the file notes.txt to backup.txt", "copy notes.txt into backup.txt", "clone notes.txt to backup.txt"]),
+ dict(id="t_rename", context=[], gold=["rename data.csv to people.csv"],
+ train=["rename the file data.csv to people.csv", "move data.csv to people.csv", "change the name of data.csv to people.csv"],
+ test=["mv data.csv to people.csv", "rename data.csv as people.csv", "data.csv should be renamed to people.csv"]),
+ dict(id="t_head", context=[], gold=["show the first 2 lines of notes.txt"],
+ train=["print the first 2 lines of notes.txt", "display the top 2 lines of notes.txt", "first 2 lines of notes.txt"],
+ test=["show me the first 2 lines in notes.txt", "head 2 lines of notes.txt", "read the first 2 lines of notes.txt"]),
+ dict(id="t_grep", context=[], gold=["search for 'TODO' in all python files"],
+ train=["find 'TODO' in all python files", "which python files contain 'TODO'", "look for 'TODO' in the python files"],
+ test=["grep 'TODO' in python files", "search all python files for 'TODO'", "where does 'TODO' appear in python files"]),
+ dict(id="t_lines", context=[], gold=["count the lines in data.csv"],
+ train=["how many lines are in data.csv", "number of lines in data.csv", "count lines of data.csv"],
+ test=["how many lines does data.csv have", "line count of data.csv", "tell me the number of lines in data.csv"]),
+ dict(id="t_replace", context=[], gold=["replace 'apple' with 'pear' in notes.txt"],
+ train=["replace all 'apple' with 'pear' in notes.txt", "replace the word 'apple' with 'pear' in notes.txt",
+ "in notes.txt replace 'apple' with 'pear'"],
+ test=["change 'apple' to 'pear' in notes.txt", "swap 'apple' for 'pear' in notes.txt",
+ "replace every 'apple' by 'pear' in the file notes.txt"]),
+ dict(id="t_zip", context=[], gold=["zip the folder src into src.zip"],
+ train=["compress src into src.zip", "archive the folder src as src.zip", "zip src to src.zip"],
+ test=["make a zip of src called src.zip", "pack src into src.zip", "compress the folder src to src.zip"]),
+]
+
+# Out-of-scope or meaningless: the right behaviour is to NOT execute (ask).
+INVALID_TRAIN = ["flibber the wobble", "frobnicate hero quickly", "the weather is nice today", "tell me a joke",
+ "blorp", "make it better", "do the thing", "sing a song about the board", "why is the sky blue",
+ "hero sparkle mode engage", "zap zap", "optimize everything magically"]
+INVALID_TEST = ["glorp the snizzle", "what time is it", "make it awesome", "please do something cool",
+ "hero feels sad", "the quick brown fox", "fix my life", "teleport hero to mars instantly",
+ "wobble wobble", "do what I mean", "turn the frobnitz", "be smarter"]
+
+
+def build_examples(extended: bool = True):
+ import copy
+ from ..learn import Example
+ from .corpus2 import extend
+ intents, inv_tr, inv_te = copy.deepcopy(INTENTS), list(INVALID_TRAIN), list(INVALID_TEST)
+ if extended:
+ extend(intents, inv_tr, inv_te)
+ out = []
+ for it in intents:
+ for split in ("train", "test"):
+ for i, text in enumerate(it[split]):
+ out.append(Example(id=f"{it['id']}:{split}{i}", text=text, split=split, context=list(it["context"]),
+ gold=list(it["gold"]), valid=True, intent=it["id"], holdout=bool(it.get("holdout"))))
+ out.append(Example(id=f"{it['id']}:gold", text=it["gold"][-1], split="gold", context=list(it["context"]) + it["gold"][:-1],
+ gold=list(it["gold"]), valid=True, intent=it["id"]))
+ ctx = HERO
+ for i, t in enumerate(inv_tr):
+ out.append(Example(id=f"invalid:train{i}", text=t, split="train", context=ctx, gold=[], valid=False, intent="invalid"))
+ for i, t in enumerate(inv_te):
+ out.append(Example(id=f"invalid:test{i}", text=t, split="test", context=ctx, gold=[], valid=False, intent="invalid"))
+ return out
diff --git a/nlcl/bench/corpus2.py b/nlcl/bench/corpus2.py
new file mode 100644
index 0000000000000000000000000000000000000000..5477e1fbd782e1a9f64d79f9a80ba2703f7661c8
--- /dev/null
+++ b/nlcl/bench/corpus2.py
@@ -0,0 +1,102 @@
+"""100 further corpus sentences (added 2026-11-22).
+
+* 10 intents with vague words (fuzzy meanings): 60 sentences. Four of these intents are HELD OUT
+ entirely ("unseen intents"): none of their sentences is used for training, so the score on them
+ measures generalisation to new meanings, not to new wordings of trained meanings.
+* 30 additional paraphrases for 10 existing intents (10 training, 20 test).
+* 10 additional out-of-scope / risky sentences (5 training, 5 test) that must NOT be executed.
+Written as people phrase things; not filtered by whether the parser already understands them.
+"""
+from __future__ import annotations
+
+HERO = ["create a game player called hero with health 100"]
+HERO10 = HERO + ["set speed of hero to 10"]
+BOARD = ["add an esp32 called board", "add a led called lamp to board on pin 2"]
+TAXI = ["create a game car called taxi"]
+
+FUZZY_INTENTS = [
+ dict(id="fz_fast", context=HERO, gold=["make hero fast"],
+ train=["hero should be fast", "make the hero fast", "I want hero to be fast"],
+ test=["set hero to fast", "hero needs to be fast", "make hero speedy"]),
+ dict(id="fz_very_fast", context=HERO, gold=["make hero very fast"],
+ train=["hero should be very fast", "make the hero really fast", "I want hero to be very fast"],
+ test=["make hero really quick", "hero must be very fast", "make the hero very speedy"]),
+ dict(id="fz_slow", context=HERO, gold=["make hero slow"],
+ train=["hero should be slow", "make the hero slow", "I want the hero to be slow"],
+ test=["hero needs to be slow", "make hero sluggish", "set hero to slow"]),
+ dict(id="fz_bit_slower", context=HERO10, gold=["make hero a bit slower"],
+ train=["make hero slightly slower", "make the hero a little slower", "hero should be a bit slower"],
+ test=["slow hero down a bit", "make hero a tad slower", "make hero just a little slower"]),
+ dict(id="fz_much_faster", context=HERO10, gold=["make hero much faster"],
+ train=["make hero a lot faster", "hero should be much faster", "make the hero a lot faster"],
+ test=["make hero much quicker", "hero needs to be a lot faster", "speed hero up a lot"]),
+ dict(id="fz_cond_low", context=HERO, gold=["when health of hero is low, print 'help'"],
+ train=["when hero's health is low, print 'help'", "print 'help' when the health of hero is low",
+ "if health of hero gets low, print 'help'"],
+ test=["when the hero's health becomes low, print 'help'", "if hero's health is low print 'help'",
+ "print 'help' whenever hero's health is low"]),
+ # ---- held out entirely: never trained on
+ dict(id="fz_taxi_fast", context=TAXI, gold=["make taxi fast"], holdout=True, train=[],
+ test=["taxi should be fast", "make the taxi fast", "I want taxi to be fast",
+ "set taxi to fast", "taxi needs to be fast", "make taxi quick"]),
+ dict(id="fz_lamp_bright", context=BOARD, gold=["make lamp bright"], holdout=True, train=[],
+ test=["lamp should be bright", "make the lamp bright", "I want lamp to be bright",
+ "set lamp to bright", "the lamp needs to be bright", "make lamp very bright"]),
+ dict(id="fz_lamp_dimmer", context=BOARD + ["set brightness of lamp to 200"], gold=["make lamp a bit dimmer"],
+ holdout=True, train=[],
+ test=["make lamp slightly dimmer", "make the lamp a little dimmer", "lamp should be a bit dimmer",
+ "make lamp a bit darker", "dim the lamp a bit", "make lamp just a little dimmer"]),
+ dict(id="fz_twice", context=HERO + ["set speed of hero to 5"], gold=["make hero twice as fast"], holdout=True,
+ train=[],
+ test=["hero should be twice as fast", "make the hero twice as fast", "make hero two times as fast",
+ "double hero's speed", "hero needs to be twice as fast", "make hero twice as fast as before"]),
+]
+# "make lamp very bright" in fz_lamp_bright is deliberately a DIFFERENT meaning (should not match): it tests
+# that the interpreter does not confuse 'very bright' with 'bright'.
+
+# extra paraphrases for existing intents (intent id -> (train, test))
+EXTRA = {
+ "mk_player": (["add a player to the game called hero with 100 health"],
+ ["create a game player hero, give it 100 health", "make me a game player named hero with health 100"]),
+ "mk_enemies": (["create 3 enemies for the game with health 30"],
+ ["spawn three game monsters with health 30", "add 3 game opponents with 30 health"]),
+ "set_speed": (["set the speed of hero to 20"],
+ ["hero should have speed 20", "change hero speed to 20"]),
+ "set_color": (["set the color of box to blue"],
+ ["box should be blue", "make the box blue"]),
+ "rename": (["change the name of hero to knight"],
+ ["rename hero as knight", "hero is now called knight"]),
+ "delete_entity": (["delete the hero"],
+ ["remove hero completely", "eliminate hero"]),
+ "beh_timer": (["each 2 seconds, decrease stock of store by 1"],
+ ["every 2 secs, decrease stock of store by 1", "reduce the stock of store by 1 every two seconds"]),
+ "beh_sensor": (["when the temperature of temp is above 30, switch on lamp"],
+ ["if temp's temperature exceeds 30, turn on lamp", "turn on the lamp whenever temperature of temp is above 30"]),
+ "t_mkdir": (["create a directory called backup"],
+ ["new folder backup", "make the folder backup"]),
+ "t_delete_tmp": (["delete all tmp files recursively"],
+ ["remove every .tmp file recursively", "delete the temporary files in all subfolders"]),
+}
+
+# out-of-scope / risky: must not be executed
+INVALID_TRAIN2 = ["make everything better", "delete the universe", "hero go brrr", "compute the meaning of life",
+ "make the code nicer somehow"]
+INVALID_TEST2 = ["please read my mind", "launch the missiles", "make it pop", "hero dance dance", "be creative"]
+
+
+def extend(intents: list, invalid_train: list, invalid_test: list) -> None:
+ """Merge into the base corpus (in place)."""
+ by_id = {it["id"]: it for it in intents}
+ for iid, (tr, te) in EXTRA.items():
+ it = by_id[iid]
+ it["train"] = list(it["train"]) + tr
+ it["test"] = list(it["test"]) + te
+ intents.extend(FUZZY_INTENTS)
+ invalid_train.extend(INVALID_TRAIN2)
+ invalid_test.extend(INVALID_TEST2)
+
+
+def count() -> int:
+ n = sum(len(it["train"]) + len(it["test"]) for it in FUZZY_INTENTS)
+ n += sum(len(a) + len(b) for a, b in EXTRA.values())
+ return n + len(INVALID_TRAIN2) + len(INVALID_TEST2)
diff --git a/nlcl/bench/fixture.py b/nlcl/bench/fixture.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ee4ac04a8fdd9a836039e8978cfbd05d17fe2b3
--- /dev/null
+++ b/nlcl/bench/fixture.py
@@ -0,0 +1,27 @@
+"""Builds the small project folder used by the terminal tests and the benchmark."""
+from pathlib import Path
+
+FILES = {
+ "README.md": "# demo\nA small project.\n",
+ "notes.txt": "banana\napple\nCherry\napple pie\n",
+ "data.csv": "id,name\n1,ann\n2,bob\n3,cy\n",
+ "src/main.py": "import util\nprint('hello')\n# TODO: refactor\n",
+ "src/util.py": "def add(a, b):\n return a + b\n# TODO: tests\n",
+ "src/app.js": "console.log('hi');\n",
+ "src/old.tmp": "scratch\n",
+ "logs/run1.log": "ok\nwarning: disk\nok\n",
+ "logs/run2.log": "error: crash\n",
+ "cache.tmp": "x\n",
+ "docs/guide.md": "Guide\nTODO: write\n",
+ "big.bin": "0" * 5000 + "\n",
+}
+
+
+def build(root: Path) -> Path:
+ root = Path(root)
+ for rel, text in FILES.items():
+ p = root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_bytes(text.encode("utf-8"))
+ (root / "empty_dir").mkdir(exist_ok=True)
+ return root
diff --git a/nlcl/bench/run.py b/nlcl/bench/run.py
new file mode 100644
index 0000000000000000000000000000000000000000..ead5c76c040c3773c7b92e62d9936aa4fe627e6d
--- /dev/null
+++ b/nlcl/bench/run.py
@@ -0,0 +1,428 @@
+"""NLCL benchmark: python -m nlcl.bench [--out DIR] [--backend NAME|auto|off] [--quick]
+
+Suites (all on the same corpus, held-out sentences only for scoring):
+ fidelity interpretation accuracy, silent errors, nonsense refusal, calibration, consistency
+ learning the same metrics after training on 0 / 1 / 2 / 3 paraphrases per intent
+ terminal effect-equivalence of terminal sentences + verification of every generated bash / PowerShell
+ command in a sandbox + unconfirmed destructive actions
+ determinism identical interpretations across repeated runs
+ cost latency and tokens
+Systems: nlcl-untrained, nlcl-trained, and (with an API key) llm-direct and nlcl+teacher.
+Writes report.md and results.json.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+from .. import modules as modreg
+from .. import weights as wmod
+from ..interpreter import Interpreter
+from ..knowledge import Knowledge
+from ..learn import Evaluator, Example, consistency, load_corpus, metrics, signature, train
+from ..shell import crosscheck, execute, snapshot, ShellError
+
+HERE = Path(__file__).resolve().parent
+
+
+def _fixture() -> Path:
+ from .fixture import build
+ return build(Path(tempfile.mkdtemp(prefix="nlcl_bench_fs_")) / "proj")
+
+
+def _fresh_kb() -> Knowledge:
+ return Knowledge(tempfile.mkdtemp(prefix="nlcl_bench_kb_"), modreg.load_modules())
+
+
+def _subset(examples: list[Example], k: int) -> list[Example]:
+ """Training set with only the first k training paraphrases of every intent (invalid: first 4k)."""
+ out = []
+ count: dict[str, int] = {}
+ for e in examples:
+ if e.split != "train":
+ out.append(e)
+ continue
+ lim = 4 * k if e.intent == "invalid" else k
+ count[e.intent] = count.get(e.intent, 0) + 1
+ if count[e.intent] <= lim:
+ out.append(e)
+ return out
+
+
+# ---------------------------------------------------------------------- LLM baselines
+class LLMDirect:
+ """The model reads the sentence and writes the IR itself (no weighting, no abstention except questions)."""
+
+ def __init__(self, backend):
+ from ..llm import LLMParser
+ self.backend = backend
+ self.p = LLMParser(backend)
+ self.tokens = 0
+
+ def run(self, ev: Evaluator, ex: Example) -> dict:
+ from ..llm import LLMError
+ st = ev.context_state(ex.context)
+ t0 = time.perf_counter()
+ try:
+ ops, question = self.p.parse(ex.text, st, list(modreg.load_modules()))
+ except LLMError as e:
+ from ..llm import QuotaExceeded
+ if isinstance(e, QuotaExceeded):
+ raise
+ ops, question = [], f"error: {e}"
+ dt = time.perf_counter() - t0
+ self.tokens += (len(ex.text) + 4000) // 4 # prompt + sentence, rough
+ executed = bool(ops)
+ shell = []
+ try:
+ Interpreter(st).apply_all([o for o in ops if o.action != "SHELL"])
+ except Exception:
+ pass
+ shell = [o.props for o in ops if o.action == "SHELL"]
+ right = signature(st, shell) == ev.gold_signature(ex) and executed == ex.valid
+ return {"id": ex.id, "text": ex.text, "valid": ex.valid, "right": right, "weight": 1.0 if executed else 0.0,
+ "decision": "execute" if executed else "ask", "executed": executed, "features": {},
+ "source": "llm", "summary": " ; ".join(map(str, ops)) or (question or ""), "seconds": dt,
+ "frames": [], "intent": None}
+
+
+def _teacher_run(kb, backend, ev: Evaluator, ex: Example) -> dict:
+ """NLCL with the model as a teacher below the execution weight (and distillation into the KB)."""
+ from ..runtime import Session
+ from .. import discover
+ s = Session("bench", backend=backend, kb=kb)
+ s.interactive, s.auto_yes = False, True
+ s.state = ev.context_state(ex.context)
+ s.interp = Interpreter(s.state)
+ t0 = time.perf_counter()
+ best = s.interpret(ex.text)[0]
+ source = "nlcl"
+ ops = best.ops
+ if best.score < s.execute_at:
+ from ..llm import LLMError
+ try:
+ ops2, q = s.llm.parse(ex.text, s.state, list(modreg.load_modules()))
+ except LLMError as e:
+ from ..llm import QuotaExceeded
+ if isinstance(e, QuotaExceeded):
+ raise
+ ops2, q = [], None
+ if ops2:
+ dry = wmod.llm_features(ops2, s.state)
+ if wmod.score(dry, kb.params()) >= s.ask_below:
+ rule = discover.distill(s, ex.text, ops2)
+ if rule:
+ kb.add_rewrite(rule[0], rule[1], 1)
+ ops, source = ops2, "teacher"
+ else:
+ ops = []
+ else:
+ ops = []
+ executed = bool(ops) and (source == "teacher" or wmod.decision(best.score) != "ask")
+ shell = []
+ if executed:
+ Interpreter(s.state).apply_all([o for o in ops if o.action != "SHELL"])
+ shell = [o.props for o in ops if o.action == "SHELL"]
+ right = signature(s.state, shell) == ev.gold_signature(ex) and executed == ex.valid
+ return {"id": ex.id, "text": ex.text, "valid": ex.valid, "right": right, "weight": best.score,
+ "decision": "execute" if executed else "ask", "executed": executed, "features": best.features,
+ "source": source, "summary": " ; ".join(map(str, ops)), "seconds": time.perf_counter() - t0,
+ "frames": [], "intent": None}
+
+
+# ---------------------------------------------------------------------- terminal suite
+def terminal_suite(kb, fs: Path, examples: list[Example]) -> dict:
+ ev = Evaluator(kb, fs)
+ from ..runtime import Session
+ term = [e for e in examples if e.split == "test" and e.intent.startswith("t_")]
+ rows, verified, checked, unconfirmed = [], 0, 0, 0
+ for ex in term:
+ s = Session("bench", backend="off", kb=kb)
+ s.cwd = fs
+ s.interactive, s.auto_yes = True, False
+ best = s.interpret(ex.text)[0]
+ gold = s.interpret(ex.gold[-1])[0]
+ ok = False
+ if best.source == "shell" and best.ops and gold.source == "shell":
+ ok = _same_effect(best.ops[0], gold.ops[0], fs)
+ for sh in ("bash", "powershell"):
+ try:
+ good, _why = crosscheck(best.ops[0], fs, sh)
+ except Exception:
+ good = False
+ checked += 1
+ verified += int(good)
+ # would the runtime change files without confirmation?
+ out = s._shell(best)
+ if any(line.strip() == "done" or line.startswith(" done") for line in out):
+ if kb.needs_confirmation(best.ops[0].props["intent"]):
+ unconfirmed += 1
+ s.confirm = None
+ rows.append({"text": ex.text, "right": ok, "weight": round(best.score, 3), "source": best.source,
+ "executed": wmod.decision(best.score) != "ask" and best.source == "shell"})
+ n = len(rows)
+ return {"sentences": n,
+ "effect_accuracy": round(sum(r["right"] for r in rows) / max(1, n), 4),
+ "silent_error_rate": round(sum(1 for r in rows if r["executed"] and not r["right"]) / max(1, n), 4),
+ "commands_verified": f"{verified}/{checked}",
+ "unconfirmed_destructive_actions": unconfirmed,
+ "rows": rows}
+
+
+def _same_effect(a, b, fs: Path) -> bool:
+ with tempfile.TemporaryDirectory() as td:
+ import shutil
+ pa, pb = Path(td) / "a", Path(td) / "b"
+ shutil.copytree(fs, pa)
+ shutil.copytree(fs, pb)
+ try:
+ oa = execute(a, pa)
+ except ShellError:
+ return False
+ try:
+ ob = execute(b, pb)
+ except ShellError:
+ return False
+ return snapshot(pa) == snapshot(pb) and oa.replace(str(pa), "") == ob.replace(str(pb), "")
+
+
+def llm_terminal_suite(backend, fs: Path, examples: list[Example], limit: int = 0) -> dict:
+ """The model writes a bash command directly; scored by the same sandbox effect check."""
+ import shutil
+ import subprocess
+ from ..llm import LLMError
+ from ..runtime import Session
+ term = [e for e in examples if e.split == "test" and e.intent.startswith("t_")]
+ if limit and limit < len(term):
+ term = [term[int(i * len(term) / limit)] for i in range(limit)]
+ right = executed = 0
+ kb = _fresh_kb()
+ for ex in term:
+ s = Session("bench", backend="off", kb=kb)
+ gold = s.interpret(ex.gold[-1])[0]
+ try:
+ cmd = backend.chat([{"role": "system", "content": "Reply with ONLY one bash command, no explanation, "
+ "no code fences. Working directory is the project folder."},
+ {"role": "user", "content": ex.text}], json_mode=False).strip().strip("`")
+ except LLMError as e:
+ from ..llm import QuotaExceeded
+ if isinstance(e, QuotaExceeded):
+ raise
+ continue
+ executed += 1
+ with tempfile.TemporaryDirectory() as td:
+ pa, pb = Path(td) / "a", Path(td) / "b"
+ shutil.copytree(fs, pa)
+ shutil.copytree(fs, pb)
+ try:
+ ref = execute(gold.ops[0], pa)
+ p = subprocess.run(["bash", "-c", cmd], cwd=str(pb), capture_output=True, text=True, timeout=60)
+ same_fs = snapshot(pa) == snapshot(pb)
+ same_out = sorted(x.strip().lstrip("./") for x in ref.splitlines() if x.strip()) == \
+ sorted(x.strip().lstrip("./") for x in p.stdout.splitlines() if x.strip())
+ right += int(same_fs and (same_out or ref == ""))
+ except Exception:
+ pass
+ n = len(term)
+ return {"sentences": n, "effect_accuracy": round(right / max(1, n), 4), "executed": executed}
+
+
+# ---------------------------------------------------------------------- main
+def run_bench(out: Path, backend_name: str | None = "off", quick: bool = False, log=print, sample_n: int = 0) -> dict:
+ from ..llm import autodetect
+ out.mkdir(parents=True, exist_ok=True)
+ examples = load_corpus()
+ fs = _fixture()
+ results: dict = {"date": time.strftime("%Y-%m-%d %H:%M"), "systems": {}, "learning_curve": [], "notes": []}
+ test = [e for e in examples if e.split == "test"]
+
+ log("== fidelity: untrained")
+ kb0 = _fresh_kb()
+ ev0 = Evaluator(kb0, fs)
+ r0 = [ev0.run(e) for e in test]
+ m0 = metrics(r0)
+ m0["paraphrase_consistency"] = consistency(r0, test)
+ results["systems"]["nlcl-untrained"] = m0
+
+ log("== learning curve")
+ for k in ([0, 3] if quick else [0, 1, 2, 3]):
+ kb = _fresh_kb()
+ if k:
+ train(kb, _subset(examples, k), log=lambda *a: None, cwd=fs)
+ ev = Evaluator(kb, fs)
+ res = [ev.run(e, kb.rewrites(), kb.params() or None) for e in test]
+ m = metrics(res)
+ m["paraphrases_per_intent"] = k
+ m["rules_learned"] = kb.stats()["rewrites"]
+ results["learning_curve"].append(m)
+ log(f" k={k}: accuracy {m['interpretation_accuracy']} silent {m['silent_error_rate']} "
+ f"nonsense {m['nonsense_caught']} ece {m['calibration_ece']}")
+ kb_t = _fresh_kb()
+ tr = train(kb_t, examples, log=lambda *a: None, cwd=fs)
+ ev_t = Evaluator(kb_t, fs)
+ rt = [ev_t.run(e, kb_t.rewrites(), kb_t.params()) for e in test]
+ mt = metrics(rt)
+ mt["paraphrase_consistency"] = consistency(rt, test)
+ mt["rules_learned"] = tr["rules_learned"]
+ results["systems"]["nlcl-trained"] = mt
+ results["learned_kb"] = kb_t.learned_text()
+ # risk / coverage: what share it executes at each weight threshold, and how often that is right
+ sel = []
+ for th in (0.0, 0.35, 0.5, 0.6, 0.7, 0.8, 0.9):
+ ex_ = [r for r in rt if r["weight"] >= th and r["summary"] != "(nothing)"]
+ sel.append({"threshold": th, "coverage": round(len(ex_) / len(rt), 3),
+ "precision": round(sum(r["right"] for r in ex_) / max(1, len(ex_)), 3),
+ "wrong_executions": sum(1 for r in ex_ if not r["right"])})
+ results["selective"] = sel
+
+ log("== determinism")
+ runs = []
+ for _ in range(2 if quick else 5):
+ evd = Evaluator(kb_t, fs)
+ runs.append([evd.run(e, kb_t.rewrites(), kb_t.params())["summary"] for e in test])
+ same = sum(1 for i in range(len(test)) if len({r[i] for r in runs}) == 1)
+ results["determinism"] = {"nlcl": f"{same}/{len(test)}", "runs": len(runs)}
+
+ log("== terminal")
+ results["terminal"] = {"nlcl-trained": terminal_suite(kb_t, fs, examples)}
+
+ backend = None
+ if backend_name not in ("off", "none"):
+ backend = autodetect(None if backend_name in (None, "auto") else backend_name)
+ if backend is None:
+ results["notes"].append("llm-direct and nlcl+teacher were NOT run: no language-model backend "
+ "(set a free API key, see ':backend status', then run again).")
+ else:
+ from ..llm import QuotaExceeded
+ # the same sample of held-out sentences for every system (free tiers allow few requests a day)
+ def spread(items, k):
+ return [items[int(i * len(items) / k)] for i in range(k)] if k < len(items) else list(items)
+ if not sample_n or sample_n >= len(test):
+ sample = test
+ else: # keep the share of nonsense sentences, spread over all intents
+ bad = [e for e in test if not e.valid]
+ good = [e for e in test if e.valid]
+ k_bad = max(1, round(sample_n * len(bad) / len(test)))
+ sample = spread(good, sample_n - k_bad) + spread(bad, k_bad)
+ ids = {e.id for e in sample}
+ if len(sample) < len(test):
+ results["notes"].append(f"language-model systems were scored on a sample of {len(sample)} of {len(test)} "
+ "held-out sentences; the NLCL columns in the comparison table use the same sample.")
+ for name, rows in (("nlcl-untrained", r0), ("nlcl-trained", rt)):
+ sub = [r for r in rows if r["id"] in ids]
+ ms = metrics(sub)
+ ms["paraphrase_consistency"] = consistency(sub, sample)
+ results["systems"][name + " (sample)"] = ms
+ n_term = 33 if len(sample) == len(test) else max(3, len(sample) // 3)
+ n_rep = 10 if len(sample) == len(test) else 4
+ log(f"== llm-direct ({backend}) on {len(sample)} sentences; at most about "
+ f"{len(sample) + n_rep + len(sample) // 2 + n_term} requests in total")
+ try:
+ lp = LLMDirect(backend)
+ ev_l = Evaluator(_fresh_kb(), fs)
+ rl = [lp.run(ev_l, e) for e in sample]
+ ml = metrics(rl)
+ ml["paraphrase_consistency"] = consistency(rl, sample)
+ ml["approx_tokens"] = lp.tokens
+ for k in ("calibration_ece", "calibration_brier", "calibration_auroc"):
+ ml[k] = "n/a"
+ results["systems"]["llm-direct"] = ml
+ rep_n = min(10 if len(sample) == len(test) else 4, len(sample))
+ rl2 = [lp.run(ev_l, e)["summary"] for e in sample[:rep_n]]
+ same_l = sum(1 for a, b in zip([r["summary"] for r in rl], rl2) if a == b)
+ results["determinism"]["llm-direct"] = f"{same_l}/{rep_n}"
+ log("== nlcl+teacher")
+ kb_h = _fresh_kb()
+ train(kb_h, examples, log=lambda *a: None, cwd=fs)
+ ev_h = Evaluator(kb_h, fs)
+ rh = [_teacher_run(kb_h, backend, ev_h, e) for e in sample]
+ mh = metrics(rh)
+ mh["paraphrase_consistency"] = consistency(rh, sample)
+ mh["rules_distilled"] = kb_h.stats()["rewrites"] - tr["rules_learned"]
+ results["systems"]["nlcl+teacher"] = mh
+ log("== llm terminal")
+ results["terminal"]["llm-direct"] = llm_terminal_suite(
+ backend, fs, examples, limit=0 if len(sample) == len(test) else max(3, len(sample) // 3))
+ except QuotaExceeded as e:
+ results["notes"].append(f"stopped early: {e}. Systems not listed were not completed.")
+ log(f" stopped: {e}")
+
+ results["cost"] = {"nlcl_median_ms": mt["median_ms"], "nlcl_tokens": 0}
+ (out / "results.json").write_text(json.dumps(results, indent=1, default=str), encoding="utf-8")
+ (out / "report.md").write_text(report(results), encoding="utf-8")
+ return results
+
+
+def report(r: dict) -> str:
+ systems = r["systems"]
+ cols = list(systems)
+ rows = [("interpretation accuracy (valid sentences)", "interpretation_accuracy"),
+ ("executed something not meant (silent error rate)", "silent_error_rate"),
+ ("precision when it executes", "precision_when_executed"),
+ ("nonsense / out-of-scope refused", "nonsense_caught"),
+ ("asked instead of executing", "asked"),
+ ("all paraphrases of an intent right", "paraphrase_consistency"),
+ ("calibration error of the weight (ECE, lower is better)", "calibration_ece"),
+ ("weight separates right/wrong (AUROC)", "calibration_auroc"),
+ ("median latency per sentence (ms)", "median_ms")]
+ L = [f"# NLCL benchmark report ({r['date']})", "",
+ "Held-out sentences only (never used for training). Correct = same resulting system state as the canonical "
+ "sentence. Pre-registered hypotheses: `bench/HYPOTHESES.md`.", ""]
+ for n in r.get("notes", []):
+ L.append(f"> **Note:** {n}")
+ L += ["", "## Fidelity", "", "| metric | " + " | ".join(cols) + " |", "|---|" + "---|" * len(cols)]
+ for label, key in rows:
+ L.append(f"| {label} | " + " | ".join(str(systems[c].get(key, "")) for c in cols) + " |")
+ if r.get("selective"):
+ L += ["", "## Risk / coverage of the trained weight", "",
+ "Executing only sentences whose weight reaches the threshold (the rest are asked about):", "",
+ "| weight threshold | share executed | precision of what is executed | wrong executions |",
+ "|---|---|---|---|"]
+ for s in r["selective"]:
+ L.append(f"| {s['threshold']} | {s['coverage']} | {s['precision']} | {s['wrong_executions']} |")
+ L += ["", "## Learning curve (no model retraining: rules, evidence and weights in Prolog)", "",
+ "| training paraphrases per intent | rules learned | accuracy | silent errors | nonsense refused | ECE |",
+ "|---|---|---|---|---|---|"]
+ for m in r["learning_curve"]:
+ L.append(f"| {m['paraphrases_per_intent']} | {m['rules_learned']} | {m['interpretation_accuracy']} | "
+ f"{m['silent_error_rate']} | {m['nonsense_caught']} | {m['calibration_ece']} |")
+ t = r["terminal"]
+ L += ["", "## Terminal", "", "| metric | " + " | ".join(t) + " |", "|---|" + "---|" * len(t)]
+ for key, label in (("effect_accuracy", "same file-system effect as the meant command"),
+ ("silent_error_rate", "executed with the wrong effect"),
+ ("commands_verified", "generated bash + PowerShell verified in a sandbox"),
+ ("unconfirmed_destructive_actions", "files changed/deleted without showing a diff first")):
+ L.append(f"| {label} | " + " | ".join(str(t[s].get(key, "n/a")) for s in t) + " |")
+ L += ["", "## Determinism", "", f"Identical interpretation on every repeated run: " +
+ ", ".join(f"{k}: {v}" for k, v in r["determinism"].items() if k != "runs"), "",
+ "## Cost", "", f"NLCL offline: {r['cost']['nlcl_tokens']} tokens, median {r['cost']['nlcl_median_ms']} ms per sentence.",
+ "", "## What the trained interpreter learned (Prolog facts)", "", "```prolog", r.get("learned_kb", "").strip(), "```", ""]
+ return "\n".join(L)
+
+
+def main(argv=None) -> int:
+ for s in (sys.stdout, sys.stderr):
+ try:
+ s.reconfigure(encoding="utf-8")
+ except (AttributeError, ValueError):
+ pass
+ ap = argparse.ArgumentParser(prog="nlcl.bench")
+ ap.add_argument("--out", default=str(Path.cwd() / "bench" / "results"))
+ ap.add_argument("--backend", default="off", help="off | auto | groq | gemini | ... (for llm-direct and nlcl+teacher)")
+ ap.add_argument("--quick", action="store_true")
+ ap.add_argument("--sample", type=int, default=0, help="score language-model systems on N held-out sentences")
+ a = ap.parse_args(argv)
+ res = run_bench(Path(a.out), a.backend, a.quick, sample_n=a.sample)
+ print(f"\nreport: {Path(a.out) / 'report.md'}")
+ for name, m in res["systems"].items():
+ print(f" {name:16} accuracy {m['interpretation_accuracy']} silent errors {m['silent_error_rate']} "
+ f"nonsense refused {m['nonsense_caught']}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/nlcl/composer.py b/nlcl/composer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7ae5459db81a6560e28721cff5970abc13aaa82
--- /dev/null
+++ b/nlcl/composer.py
@@ -0,0 +1,270 @@
+"""Multi-module system composer.
+
+Groups entities by domain, resolves every Link into a Channel with a concrete
+protocol + configuration that BOTH sides agree on, then lets each domain
+module generate its part. Writes system.json (IR), SYSTEM.md (architecture,
+wiring and how to run everything with free tools).
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from . import modules as modreg
+from .ir import SystemState, ident
+from .modules.base import BuildContext, Channel, RunResult
+
+# default protocol by (domain, domain) pair (order-insensitive)
+DEFAULT_PROTOCOL = {
+ frozenset({"embedded", "python"}): "serial",
+ frozenset({"embedded"}): "serial",
+ frozenset({"embedded", "hardware"}): "spi",
+ frozenset({"hardware"}): "wire",
+ frozenset({"hardware", "python"}): "serial",
+ frozenset({"python", "3d"}): "http",
+ frozenset({"python", "game"}): "http",
+ frozenset({"python"}): "http",
+ frozenset({"python", "cpp"}): "http",
+ frozenset({"cpp", "embedded"}): "serial",
+ frozenset({"game", "3d"}): "http",
+ frozenset({"embedded", "3d"}): "http",
+ frozenset({"embedded", "game"}): "http",
+}
+NON_DATA_PROPS = {"pin", "pins", "position", "rotation", "scale", "size", "color", "subtype", "baud", "port",
+ "address", "width", "height", "depth", "radius", "length", "thickness", "board", "mass",
+ "model", "wifi_ssid", "wifi_password", "interval_ms", "clock_hz", "on_pin", "movable",
+ "collision", "gravity", "visible", "shape", "material", "texture", "units", "divide_by",
+ "stable_ms", "frequency_hz", "active_low", "for_entity", "states", "wall", "lid", "vents"}
+
+
+def data_fields(state: SystemState, src) -> list[str]:
+ """Default fields of a link: real data props of the source (or of its child sensors when the
+ source is a board), never config, flags named after other things, or flattened references."""
+ names = {"esp32", "esp8266", "arduino", "uno", "nano", "mega", "pico", "pico_w", "stm32", "raspberry_pi",
+ "arduino_uno", "arduino_nano", "arduino_mega"}
+ for e in state.entities.values():
+ if e.id != src.id:
+ names |= {e.ident, ident(e.kind)}
+
+ def ok(k, v):
+ if k in NON_DATA_PROPS or k.startswith("_") or not isinstance(v, (int, float, bool)):
+ return False
+ if k in names or any(k.startswith(n + "_") for n in names if n):
+ return False # 'esp32': True, 'alu1_result', 'bob_lives'
+ return True
+ fields = [k for k, v in src.props.items() if ok(k, v)]
+ if not fields:
+ for c in state.children(src.id):
+ fields += [k for k, v in c.props.items() if ok(k, v) and k not in fields]
+ return fields
+
+
+def resolve_channels(state: SystemState) -> list[Channel]:
+ chans = []
+ for l in state.links.values():
+ src, dst = state.entities.get(l.src), state.entities.get(l.dst)
+ if not src or not dst:
+ continue
+ proto = (l.via or DEFAULT_PROTOCOL.get(frozenset({src.domain, dst.domain})) or "http").lower()
+ if proto == "uart":
+ proto = "serial"
+ requested = None
+ if proto == "websocket":
+ # every module implements this as HTTP polling on the hub: say so in the contract
+ proto, requested = "http", "websocket"
+ fields = list(l.props.get("fields") or [])
+ if not fields:
+ fields = data_fields(state, src)
+ if not fields:
+ fields = ["value"]
+ cfg = {"interval_ms": int(l.props.get("interval_ms", 1000))}
+ if requested:
+ cfg["requested_protocol"] = requested
+ # field types + enum tables so both sides (and simulators) agree on the encoding
+ types, enums = {}, {}
+ for f in fields:
+ holder = src if f in src.props else next((c for c in state.children(src.id) if f in c.props), None)
+ v = holder.props.get(f) if holder else None
+ types[f] = ("bool" if isinstance(v, bool) else "int" if isinstance(v, int) else
+ "string" if isinstance(v, str) else "float")
+ if holder and f == "state" and isinstance(holder.props.get("states"), list):
+ enums[f] = [str(s) for s in holder.props["states"]]
+ types[f] = "enum"
+ cfg["types"] = types
+ if enums:
+ cfg["enums"] = enums
+ if proto == "serial":
+ cfg["baud"] = int(l.props.get("baud", 115200))
+ cfg["port"] = l.props.get("port_name", "auto")
+ elif proto in ("http", "websocket"):
+ cfg["hub_url"] = f"http://localhost:{int(l.props.get('port', 8765))}"
+ cfg["path"] = f"/channel/{l.id}"
+ elif proto == "mqtt":
+ cfg["broker"] = l.props.get("broker", "broker.hivemq.com")
+ cfg["broker_port"] = int(l.props.get("broker_port", 1883))
+ cfg["topic"] = l.props.get("topic", f"nlcl/{ident(state.name)}/{l.id}")
+ elif proto == "udp":
+ cfg["port"] = int(l.props.get("port", 9876))
+ elif proto in ("spi", "i2c", "gpio", "wire"):
+ cfg["bus"] = proto
+ if proto == "i2c":
+ cfg["address"] = l.props.get("address", "0x42")
+ chans.append(Channel(l.id, proto, src, dst, fields, cfg))
+ return chans
+
+
+def needs_hub(chans: list[Channel]) -> bool:
+ return any(c.protocol in ("http", "websocket") for c in chans) or \
+ any(c.protocol == "serial" and "python" not in (c.src.domain, c.dst.domain) for c in chans)
+
+
+class Composer:
+ def __init__(self, state: SystemState, outdir: Path, llm=None):
+ self.state = state
+ self.outdir = Path(outdir)
+ self.llm = llm
+ self.modules = modreg.load_modules()
+
+ def contexts(self) -> list[BuildContext]:
+ chans = resolve_channels(self.state)
+ ctxs = []
+ for dom in self.state.domains():
+ ents = self.state.in_domain(dom)
+ mine = [c for c in chans if dom in (c.src.domain, c.dst.domain)]
+ ctxs.append(BuildContext(self.state, dom, ents, mine, self.outdir / dom,
+ project=ident(self.state.name) or "project", llm=self.llm))
+ # cross-domain http links need the python hub even if there are no python entities
+ if needs_hub(chans) and "python" not in self.state.domains():
+ ctxs.append(BuildContext(self.state, "python", [], [c for c in chans if c.protocol in ("http", "websocket", "serial")],
+ self.outdir / "python", project=ident(self.state.name) or "project", llm=self.llm))
+ return ctxs
+
+ def build(self) -> tuple[dict[str, list[str]], list[str]]:
+ """Generate everything. Returns ({domain: [files]}, warnings)."""
+ written: dict[str, list[str]] = {}
+ warnings: list[str] = []
+ self.outdir.mkdir(parents=True, exist_ok=True)
+ ctxs = self.contexts()
+ for ctx in ctxs:
+ mod = modreg.get(ctx.domain)
+ if not mod:
+ warnings.append(f"no module for domain '{ctx.domain}'")
+ continue
+ ctx.outdir.mkdir(parents=True, exist_ok=True)
+ try:
+ files = mod.generate(ctx)
+ except Exception as e: # report, keep building other domains
+ import traceback
+ warnings.append(f"{ctx.domain}: generator failed: {e}\n{traceback.format_exc(limit=3)}")
+ continue
+ for rel, content in files.items():
+ p = ctx.outdir / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(content, encoding="utf-8", newline="\n")
+ written.setdefault(ctx.domain, []).append(str(p.relative_to(self.outdir)))
+ for e in ctx.entities:
+ warnings += [f"{e.name}: {w}" for w in mod.validate(e)]
+ self._cleanup(written, warnings)
+ warnings += self._reapply_patches()
+ chans = resolve_channels(self.state)
+ (self.outdir / "system.json").write_text(json.dumps({
+ "ir": self.state.to_dict(),
+ "channels": [c.to_dict() for c in chans],
+ }, ensure_ascii=False, indent=2), encoding="utf-8")
+ (self.outdir / "SYSTEM.md").write_text(self.report(chans, written), encoding="utf-8")
+ return written, warnings
+
+ def _reapply_patches(self) -> list[str]:
+ """Bug fixes made to generated files (state.patches) survive a rebuild when they still apply."""
+ notes, kept = [], 0
+ for pt in getattr(self.state, "patches", []):
+ p = (self.outdir / pt["file"]).resolve()
+ if self.outdir.resolve() not in p.parents or not p.is_file():
+ continue
+ txt = p.read_text(encoding="utf-8", errors="replace")
+ if pt["replace"] in txt and pt["search"] not in txt:
+ kept += 1
+ elif pt["search"] in txt:
+ p.write_text(txt.replace(pt["search"], pt["replace"], 1), encoding="utf-8", newline="")
+ kept += 1
+ else:
+ notes.append(f"an earlier fix in {pt['file']} no longer applies to the regenerated code")
+ if kept:
+ notes.append(f"re-applied {kept} earlier fix(es) to the generated code")
+ return notes
+
+ MANIFEST = ".nlcl_manifest.json"
+
+ def _cleanup(self, written: dict[str, list[str]], warnings: list[str]) -> None:
+ """Delete files that a previous build generated but this build no longer does.
+ Only files listed in the previous manifest are touched (never user files)."""
+ mpath = self.outdir / self.MANIFEST
+ now = sorted(f.replace("\\", "/") for fs in written.values() for f in fs)
+ try:
+ before = json.loads(mpath.read_text(encoding="utf-8")).get("files", [])
+ except (OSError, ValueError):
+ before = []
+ removed = 0
+ for f in set(before) - set(now):
+ p = (self.outdir / f).resolve()
+ if self.outdir.resolve() in p.parents and p.is_file():
+ p.unlink()
+ removed += 1
+ try:
+ p.parent.rmdir() # only if now empty
+ except OSError:
+ pass
+ if removed:
+ warnings.append(f"removed {removed} stale file(s) from the previous build")
+ mpath.write_text(json.dumps({"files": now}, indent=1), encoding="utf-8")
+
+ def run(self, domain: str | None = None) -> list[tuple[str, RunResult]]:
+ results = []
+ for ctx in self.contexts():
+ if domain and ctx.domain != domain:
+ continue
+ mod = modreg.get(ctx.domain)
+ if not mod:
+ continue
+ r = mod.run(ctx)
+ if r is not None:
+ results.append((ctx.domain, r))
+ return results
+
+ # -------------------------------------------------------------- report
+ def report(self, chans: list[Channel], written: dict[str, list[str]]) -> str:
+ st = self.state
+ L = [f"# System: {st.name}", "",
+ "Generated by NLCL (Natural Language Computational Language).", "",
+ "## Architecture", "", "```mermaid", "flowchart LR"]
+ for dom in st.domains():
+ L.append(f" subgraph {ident(dom)}[{dom}]")
+ for e in st.in_domain(dom):
+ L.append(f" {e.ident}[\"{e.name} {e.kind}\"]")
+ L.append(" end")
+ for e in st.entities.values():
+ if e.parent in st.entities:
+ L.append(f" {st.entities[e.parent].ident} -.contains.- {e.ident}")
+ for c in chans:
+ L.append(f" {c.src.ident} -->|{c.protocol}: {', '.join(c.fields)}| {c.dst.ident}")
+ L += ["```", "", "## Entities", ""]
+ L.append("```")
+ L.append(st.summary())
+ L.append("```")
+ if chans:
+ L += ["", "## Channels (cross-module contracts)", "",
+ "| id | protocol | from | to | fields | config |", "|---|---|---|---|---|---|"]
+ for c in chans:
+ L.append(f"| {c.id} | {c.protocol} | {c.src.name} ({c.src.domain}) | {c.dst.name} ({c.dst.domain}) "
+ f"| {', '.join(c.fields)} | {json.dumps(c.config)} |")
+ L += ["", "Every message is a flat JSON object: `{\"channel\": id, \"from\": src, : value, ...}` "
+ "terminated by a newline on stream transports (serial/udp)."]
+ L += ["", "## Generated files and free toolchains", ""]
+ for dom, files in written.items():
+ mod = modreg.get(dom)
+ L.append(f"### {dom} — {mod.title if mod else ''}")
+ for f in files:
+ L.append(f"- `{f}`")
+ if mod and mod.toolchain:
+ L += ["", mod.toolchain.strip(), ""]
+ return "\n".join(L) + "\n"
diff --git a/nlcl/discover.py b/nlcl/discover.py
new file mode 100644
index 0000000000000000000000000000000000000000..788bb5de08ef741a06fc51f57f311cc0f9310211
--- /dev/null
+++ b/nlcl/discover.py
@@ -0,0 +1,248 @@
+"""Self-structuring: what the interpreter does when a word or a whole module does not exist yet.
+
+1. Unknown verb / word -> close forms in the KB vocabulary (typos, inflections) are tried; a candidate
+ is accepted only if it makes the sentence interpretable with a high weight.
+2. Online teacher -> if an LLM backend exists, its interpretation of the sentence is used as gold
+ and *distilled* into a rewrite rule in the Prolog KB, so the next time the
+ same kind of sentence is understood offline, deterministically, for free.
+3. Unknown module -> a language / platform the KB knows (language/3) but no module implements is
+ grown into a new domain module at run time, registered, and remembered
+ (learned_module/3). Its code is written by the online agent and checked by the
+ bug-fix diagnostics; offline it produces a precise spec instead.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from pathlib import Path
+
+from . import modules as modreg
+from .ir import Entity
+from .modules.base import BuildContext, DomainModule, RunResult
+
+VERB_WORDS_CACHE: list[str] | None = None
+
+
+def _dl(a: str, b: str) -> int:
+ """Damerau-Levenshtein distance (optimal string alignment)."""
+ d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
+ for i in range(len(a) + 1):
+ d[i][0] = i
+ for j in range(len(b) + 1):
+ d[0][j] = j
+ for i in range(1, len(a) + 1):
+ for j in range(1, len(b) + 1):
+ c = 0 if a[i - 1] == b[j - 1] else 1
+ d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + c)
+ if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
+ d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1)
+ return d[-1][-1]
+
+
+def _vocabulary(kb) -> list[str]:
+ words = {r["W"] for r in kb.query("atomic(W, _)", limit=5000)}
+ words |= {r["K"] for r in kb.query("kind_of(K, _, _)", limit=5000)}
+ return sorted(w for w in words if isinstance(w, str) and len(w) >= 3)
+
+
+def word_candidates(word: str, kb) -> list[str]:
+ """Known words this unknown word may stand for: inflections first, then typos."""
+ w = word.lower()
+ vocab = _vocabulary(kb)
+ out = []
+ for suf, rep in (("ing", ""), ("ing", "e"), ("ed", ""), ("ed", "e"), ("es", ""), ("s", ""), ("ies", "y")):
+ if w.endswith(suf) and len(w) > len(suf) + 2:
+ base = w[: -len(suf)] + rep
+ if base in vocab and base not in out:
+ out.append(base)
+ if len(w) >= 4:
+ limit = 1 if len(w) < 7 else 2
+ near = sorted((_dl(w, v), v) for v in vocab if abs(len(v) - len(w)) <= limit and v != w)
+ out += [v for dist, v in near if dist <= limit and v not in out][:3]
+ return out
+
+
+def repair_sentence(session, text: str, min_weight: float | None = None) -> tuple[str, str, str, float] | None:
+ """Try replacing one unknown word by a close known word. -> (new text, old, new, weight) or None."""
+ min_weight = session.execute_at if min_weight is None else min_weight
+ base = session.interpret(text)[0].score
+ known = set(_vocabulary(session.kb))
+ best = None
+ for m in re.finditer(r"[A-Za-z][A-Za-z\-]{2,}", text):
+ w = m.group(0)
+ if w.lower() in known or session.vocab.atomic(w.lower()):
+ continue
+ for cand in word_candidates(w, session.kb):
+ new = text[:m.start()] + cand + text[m.end():]
+ sc = session.interpret(new)[0].score
+ if sc >= min_weight and sc > base + 0.15 and (best is None or sc > best[3]):
+ best = (new, w.lower(), cand, sc)
+ return best
+
+
+def distill(session, text: str, gold_ops: list, max_trials: int = 2500) -> tuple[list[str], list[str]] | None:
+ """Find a rewrite rule (phrase -> known word or nothing) that makes the offline interpreter produce
+ the same state as the teacher's interpretation. Stores nothing; the caller decides."""
+ from .learn import signature
+ from .interpreter import Interpreter
+ clone = session.state.clone()
+ Interpreter(clone).apply_all(list(gold_ops))
+ shell = [op.props for op in gold_ops if op.action == "SHELL"]
+ gold_sig = signature(clone, shell)
+ words = re.findall(r"[A-Za-z][\w'\-]*", text.lower())
+ verbs = sorted({r["W"] for r in session.kb.query("atomic(W, T)", limit=5000)
+ if r["T"] in ("CREATE", "DELETE", "SET", "CONNECT", "MOVE", "RENAME", "SHOW")})
+ targets = [""] + verbs
+ grams = []
+ for n in (1, 2, 3):
+ for i in range(len(words) - n + 1):
+ grams.append(words[i:i + n])
+ base = list(session.rules.rewrites)
+ tried = 0
+ for g in grams:
+ if all(session.vocab.atomic(w) for w in g):
+ continue
+ for t in targets:
+ tried += 1
+ if tried > max_trials:
+ return None
+ session.rules.rewrites = sorted(base + [(g, [t] if t else [], 1)], key=lambda r: -len(r[0]))
+ try:
+ c = session.interpret(text)[0]
+ if c.ops:
+ st = session.state.clone()
+ sh = []
+ if c.source == "shell":
+ sh = [c.ops[0].props]
+ else:
+ Interpreter(st).apply_all(c.ops)
+ if signature(st, sh) == gold_sig:
+ return g, ([t] if t else [])
+ finally:
+ session.rules.rewrites = base
+ return None
+
+
+# ======================================================================= module discovery
+GENERIC_KINDS = {"object": {}, "program": {}, "app": {}, "service": {}, "library": {}, "script": {}, "cli": {},
+ "tool": {}, "class": {}, "function": {}, "module": {}, "server": {"port": 8080}, "game": {},
+ "calculator": {}, "counter": {"count": 0}}
+
+
+class GeneratedModule(DomainModule):
+ """A domain the system grew by itself for a language it has no hand-written module for."""
+
+ def __init__(self, language: str, ext: str, run_hint: str, home: Path | None = None):
+ self.name = language
+ self.language = language
+ self.ext = ext
+ self.run_hint = run_hint
+ self.home = home
+ self.title = f"{language} (discovered module: code written by the online agent, checked by diagnostics)"
+ self.aliases = (language,)
+ self.keywords = (language,)
+ self.kinds = dict(GENERIC_KINDS)
+ self.suggested_props = ("purpose", "inputs", "outputs")
+ self.protocols = ("http",)
+ self.toolchain = f"Run with: `{run_hint}`"
+
+ def spec(self, ctx: BuildContext) -> dict:
+ return {"language": self.language, "project": ctx.project,
+ "entities": [{"name": e.name, "kind": e.kind, "props": e.props, "behaviors": e.behaviors,
+ "parent": next((x.name for x in ctx.entities if x.id == e.parent), None)}
+ for e in ctx.entities],
+ "channels": [c.to_dict() for c in ctx.channels]}
+
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
+ spec = self.spec(ctx)
+ blob = json.dumps(spec, sort_keys=True, ensure_ascii=False)
+ key = hashlib.sha1(blob.encode()).hexdigest()[:16]
+ files = {"spec.json": json.dumps(spec, indent=2, ensure_ascii=False)}
+ cache = (self.home / "modules" / self.name / f"{key}.json") if self.home else None
+ if cache and cache.exists(): # deterministic: same IR -> same code
+ files.update(json.loads(cache.read_text(encoding="utf-8")))
+ return files
+ llm = ctx.llm
+ if llm is None or not hasattr(llm, "backend"):
+ files["README.md"] = (f"# {ctx.project} ({self.language})\n\nNLCL discovered the `{self.language}` module, "
+ "but writing code in it needs the online agent (set a free API key, see "
+ "`:backend status`) and then `build it` again.\n\nThe exact specification "
+ "the agent will implement is in `spec.json`.\n")
+ return files
+ from .llm import extract_json
+ prompt = [{"role": "system", "content":
+ f"You write complete, runnable {self.language} programs from a JSON specification produced by "
+ "a natural-language programming system. Every entity is a part of the program; its props are "
+ "its data; its behaviors are event rules (on: start|update|timer:|input:|change:"
+ "|message:|collision, if: condition, do: actions). Reply with ONLY JSON: "
+ '{"files": {"": ""}}. Include a README.md with the run '
+ f"command ({self.run_hint}). No placeholders, no TODOs."},
+ {"role": "user", "content": blob}]
+ try:
+ data = extract_json(llm.backend.chat(prompt))
+ gen = {str(k): str(v) for k, v in (data.get("files") or {}).items()}
+ except Exception as e:
+ files["README.md"] = f"# {ctx.project}\n\nThe online agent failed to write the code: {e}\n"
+ return files
+ files.update(gen)
+ if cache:
+ cache.parent.mkdir(parents=True, exist_ok=True)
+ cache.write_text(json.dumps(gen, ensure_ascii=False), encoding="utf-8")
+ return files
+
+ def run(self, ctx: BuildContext) -> RunResult | None:
+ from .fixer import diagnose
+ diags = diagnose(ctx.outdir)
+ return RunResult(not diags, "diagnostics: " + ("no problems" if not diags else "; ".join(map(str, diags[:5]))),
+ "nlcl check")
+
+
+def register(kb, home: Path | None, name: str) -> DomainModule | None:
+ """Grow a module for a language listed in the KB and remember it."""
+ lang = kb.language(name)
+ if not lang:
+ return None
+ reg = modreg.load_modules()
+ if name in reg:
+ return reg[name]
+ ext, hint = lang
+ m = GeneratedModule(name, ext, hint, home)
+ reg[name] = m
+ kb.add_learned_module(name, name, ext)
+ kb.load_modules(reg)
+ kb.save()
+ return m
+
+
+def restore(kb, home: Path | None) -> list[str]:
+ """Re-register modules discovered in earlier sessions."""
+ out = []
+ reg = modreg.load_modules()
+ for name, lang, ext in kb.learned_modules():
+ if name not in reg:
+ hint = (kb.language(lang) or (ext, ""))[1]
+ reg[name] = GeneratedModule(name, ext, hint, home)
+ out.append(name)
+ if out:
+ kb.load_modules(reg)
+ return out
+
+
+PROGRAM_NOUNS = r"(?:program|app|application|service|script|cli|tool|library|code|module|project|server|class|function|game|calculator|counter|object)"
+
+
+def languages_in(text: str, kb) -> list[str]:
+ """Languages the sentence clearly asks for ("a rust program", "in kotlin", "use dart") with no module yet."""
+ known = set(kb.languages())
+ reg = modreg.load_modules()
+ low = text.lower()
+ out = []
+ for lang in sorted(known, key=len, reverse=True):
+ if lang in reg or modreg.get(lang):
+ continue
+ l = re.escape(lang)
+ if re.search(rf"\b(?:in|use|using|with|written\s+in)\s+{l}\b", low) or \
+ re.search(rf"\b{l}\s+{PROGRAM_NOUNS}s?\b", low):
+ out.append(lang)
+ return out
diff --git a/nlcl/fixer.py b/nlcl/fixer.py
new file mode 100644
index 0000000000000000000000000000000000000000..35429bf06bfec8c124b5a2f307aaf497ded9382a
--- /dev/null
+++ b/nlcl/fixer.py
@@ -0,0 +1,576 @@
+"""Smart bug fixing for any module and any existing code.
+
+ diagnose -> real tools per file type (offline): Python compile, node --check (JS / HTML scripts),
+ JSON parse, C/C++ (g++/clang++), Verilog (iverilog/verilator), Arduino (arduino-cli),
+ OpenSCAD, GDScript (godot), C# (dotnet), plus bracket balance for every C-like file.
+ fix -> online agent loop: code + diagnostics + the user's description go to the LLM, which
+ returns search/replace edits; edits are applied with a backup, the code is re-checked,
+ and a round that makes things worse is rolled back. Works on files the user wrote
+ earlier as well as on generated output.
+
+Without an LLM backend only ``diagnose`` is available (problems are located and reported, not fixed).
+"""
+from __future__ import annotations
+
+import difflib
+import json
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+
+SOURCE_EXT = {".py", ".js", ".mjs", ".ts", ".html", ".htm", ".css", ".json", ".c", ".h", ".cpp", ".hpp", ".cc",
+ ".ino", ".cs", ".gd", ".v", ".sv", ".scad", ".java", ".kt", ".swift", ".go", ".rs", ".sh", ".ps1",
+ ".bat", ".toml", ".ini", ".yml", ".yaml", ".md", ".txt", ".nl", ".tscn", ".godot", ".cmake"}
+CODE_EXT = SOURCE_EXT - {".md", ".txt"}
+SKIP_DIRS = {".git", "__pycache__", "node_modules", ".nlcl_backup", ".venv", "venv", "dist", "build_out", ".pio"}
+MAX_FILE = 60_000 # bytes sent per file
+MAX_TOTAL = 160_000 # bytes sent per round
+
+
+@dataclass
+class Diag:
+ file: str
+ line: int | None
+ message: str
+ tool: str
+ severity: str = "error"
+
+ def __str__(self):
+ loc = f"{self.file}:{self.line}" if self.line else self.file
+ return f"{loc}: {self.severity}: {self.message} [{self.tool}]"
+
+
+@dataclass
+class FixReport:
+ ok: bool
+ summary: str
+ before: list[Diag] = field(default_factory=list)
+ after: list[Diag] = field(default_factory=list)
+ changed: dict[str, str] = field(default_factory=dict) # rel path -> unified diff
+ edits: list[dict] = field(default_factory=list) # applied {file, search, replace}
+ backup: str | None = None
+ notes: list[str] = field(default_factory=list)
+ pending: dict = field(default_factory=dict) # real path -> (new text, crlf) waiting for confirmation
+ root: str | None = None
+
+ def lines(self) -> list[str]:
+ out = [f" {self.summary}"]
+ out += [f" note: {n}" for n in self.notes]
+ if self.before:
+ out.append(f" problems found: {len(self.before)}")
+ out += [f" {d}" for d in self.before[:12]]
+ for f, d in self.changed.items():
+ out.append(f" --- fixed {f}")
+ out += [" " + ln for ln in d.splitlines()[2:42]]
+ if self.changed:
+ out.append(f" remaining problems: {len(self.after)}")
+ out += [f" {d}" for d in self.after[:12]]
+ if self.backup:
+ out.append(f" originals saved in {self.backup} (':fix undo' restores them)")
+ if self.pending:
+ out.append(f" nothing has been written yet: {len(self.pending)} file(s) waiting for your confirmation")
+ return out
+
+
+# --------------------------------------------------------------------------
+# diagnostics
+# --------------------------------------------------------------------------
+
+def _run(cmd: list[str], cwd: Path | None = None, timeout: int = 40) -> tuple[int, str]:
+ try:
+ p = subprocess.run(cmd, cwd=str(cwd) if cwd else None, capture_output=True, text=True,
+ timeout=timeout, encoding="utf-8", errors="replace")
+ return p.returncode, (p.stdout + "\n" + p.stderr).strip()
+ except subprocess.TimeoutExpired:
+ return 124, f"timed out after {timeout}s"
+ except OSError as e:
+ return 127, str(e)
+
+
+def _tool(*names: str) -> str | None:
+ for n in names:
+ p = shutil.which(n)
+ if p:
+ return p
+ return None
+
+
+def _line_of(text: str, pat: str = r"(?:line |:)(\d+)") -> int | None:
+ m = re.search(pat, text)
+ return int(m.group(1)) if m else None
+
+
+def check_python(path: Path, rel: str) -> list[Diag]:
+ src = path.read_text(encoding="utf-8", errors="replace")
+ try:
+ compile(src, str(path), "exec")
+ except SyntaxError as e:
+ return [Diag(rel, e.lineno, f"{e.msg}: {(e.text or '').strip()}", "python")]
+ except ValueError as e:
+ return [Diag(rel, None, str(e), "python")]
+ return []
+
+
+def _node_check(code: str, rel: str, module: bool, offset: int = 0, tool: str = "node") -> list[Diag]:
+ node = _tool("node")
+ if not node:
+ return []
+ with tempfile.TemporaryDirectory() as td:
+ f = Path(td) / ("x.mjs" if module else "x.cjs")
+ f.write_text(code, encoding="utf-8")
+ rc, out = _run([node, "--check", str(f)])
+ if rc == 0:
+ return []
+ m = re.search(r":(\d+)\s*\n", out)
+ line = int(m.group(1)) + offset if m else None
+ msg = next((ln for ln in out.splitlines() if "Error" in ln), out.splitlines()[-1] if out else "syntax error")
+ return [Diag(rel, line, msg.strip(), tool)]
+
+
+def check_js(path: Path, rel: str) -> list[Diag]:
+ src = path.read_text(encoding="utf-8", errors="replace")
+ module = path.suffix == ".mjs" or bool(re.search(r"^\s*(import|export)\s", src, re.M))
+ return _node_check(src, rel, module)
+
+
+def check_html(path: Path, rel: str) -> list[Diag]:
+ src = path.read_text(encoding="utf-8", errors="replace")
+ out: list[Diag] = []
+ for m in re.finditer(r"", src, re.S | re.I):
+ attrs, code = m.group(1), m.group(2)
+ if "src=" in attrs or re.search(r"type\s*=\s*[\"'](?:application/json|importmap|text/template)", attrs, re.I):
+ continue
+ if not code.strip():
+ continue
+ offset = src[:m.start(2)].count("\n")
+ out += _node_check(code, rel, "module" in attrs, offset, "node(html)")
+ if src.lower().count(""""
+
+
+def main_args(argv=None):
+ import argparse
+ p = argparse.ArgumentParser()
+ p.add_argument("--seconds", type=float, default=None, help="stop after N seconds")
+ p.add_argument("--ticks", type=int, default=None, help="stop after N ticks")
+ p.add_argument("--simulate", action="store_true", help="no hardware/network: fake remote data")
+ p.add_argument("--no-hub", action="store_true", help="do not start the HTTP hub in-process")
+ p.add_argument("--quiet", action="store_true")
+ return p.parse_args(argv)
diff --git a/nlcl/modules/app_mod.py b/nlcl/modules/app_mod.py
new file mode 100644
index 0000000000000000000000000000000000000000..576e95c0cf2f4ce7d6d975a03be0225803e693f1
--- /dev/null
+++ b/nlcl/modules/app_mod.py
@@ -0,0 +1,413 @@
+"""Application domain: GUI programs for every operating system.
+
+From the same IR this module emits
+ * app.py + nlcl_app.py a desktop app (Python + Tkinter, standard library only) that runs on
+ Windows, macOS and Linux, with scripts that package it as a native
+ executable for each OS (PyInstaller, free);
+ * web/ the same app as an installable PWA (HTML + JS, no build step) for
+ Android, iOS, ChromeOS and any browser.
+Widgets are entities (button, label, input, checkbox, slider, list ...), a window/app entity is
+the root, behaviours become event handlers, links to other modules go through the NLCL hub.
+"""
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+from ..ir import Entity, describe_action
+from .base import BuildContext, DomainModule, RunResult
+
+ASSETS = Path(__file__).parent / "_assets" / "app"
+ROOT_KINDS = ("app", "application", "window", "dialog", "screen", "page")
+KEYS = {"space", "enter", "return", "escape", "esc", "up", "down", "left", "right", "tab"}
+
+
+class AppModule(DomainModule):
+ name = "app"
+ title = "Applications (desktop GUI for Windows/macOS/Linux + installable web app for Android/iOS)"
+ aliases = ("application", "desktop", "gui", "ui", "pwa", "mobile")
+ keywords = ("app", "application", "window", "dialog", "form", "menu", "widget", "tkinter", "windows",
+ "macos", "linux", "android", "ios", "notepad", "calculator", "todo", "checkbox", "textbox",
+ "textarea", "dropdown", "slider", "listbox", "screen", "page", "toolbar", "label")
+ kinds = {
+ "object": {},
+ "app": {"title": "", "size": [480, 360]},
+ "application": {"title": "", "size": [480, 360]},
+ "window": {"title": "", "size": [480, 360]},
+ "dialog": {"title": ""},
+ "screen": {"title": ""},
+ "page": {"title": ""},
+ "form": {},
+ "panel": {},
+ "frame": {},
+ "group": {},
+ "tab": {},
+ "button": {},
+ "label": {},
+ "slider": {"value": 0, "min": 0, "max": 100},
+ "timer": {},
+ "title": {},
+ "heading": {},
+ "input": {"value": ""},
+ "textbox": {"value": ""},
+ "entry": {"value": ""},
+ "field": {"value": ""},
+ "password": {"value": ""},
+ "textarea": {"value": ""},
+ "checkbox": {"checked": False},
+ "switch": {"checked": False},
+ "dropdown": {"items": [], "value": ""},
+ "select": {"items": [], "value": ""},
+ "listbox": {"items": []},
+ "list": {"items": []},
+ "progress": {"value": 0, "max": 100},
+ "canvas": {},
+ "image": {},
+ "store": {},
+ "model": {},
+ }
+ suggested_props = ("title", "text", "value", "size", "items", "checked", "label", "placeholder")
+ protocols = ("http",)
+ toolchain = """**Desktop (Windows / macOS / Linux)** - free CPython 3.10+ from python.org (Tkinter is included;
+on Debian/Ubuntu: `sudo apt install python3-tk`):
+
+ python app.py # run the app
+ python app.py --selftest # build the UI, fire every event once, print the state, exit
+
+Native executable for the OS you are on (free PyInstaller: `pip install pyinstaller`):
+
+ build_windows.bat # -> dist\\.exe
+ ./build_macos.sh # -> dist/.app
+ ./build_linux.sh # -> dist/ (+ .desktop launcher)
+
+**Android / iOS / ChromeOS / any browser** - `web/` is an installable PWA, no build step:
+
+ python -m http.server 8080 --directory web # then open http://localhost:8080
+ (on the phone: open the page -> browser menu -> "Add to Home screen" / "Install app")
+ node web/app.js --selftest # logic self-test without a browser"""
+
+ # ------------------------------------------------------------------ spec
+ def _spec(self, ctx: BuildContext) -> dict:
+ ids = {e.id: e.ident for e in ctx.entities}
+ root = next((e for e in ctx.entities if e.kind in ROOT_KINDS and e.parent not in ids), None)
+ title = str((root.props.get("title") if root else "") or (root.name if root else ctx.system.name)).replace("_", " ")
+ size = (root.props.get("size") if root else None) or [480, 360]
+ if not isinstance(size, list):
+ size = [size, 360]
+ widgets = []
+ for e in ctx.entities:
+ props = {k: v for k, v in e.props.items() if not k.startswith("_")}
+ parent = ids.get(e.parent)
+ if parent is None and root is not None and e.id != root.id and e.kind not in ROOT_KINDS:
+ parent = root.ident
+ widgets.append({"id": e.ident, "kind": e.kind, "parent": parent, "props": props})
+ channels = []
+ for c in ctx.channels:
+ url = c.config.get("hub_url", "http://localhost:8765") + c.config.get("path", f"/channel/{c.id}")
+ if c.src.domain == self.name and c.dst.domain == self.name:
+ continue # both ends in this app: state is shared already
+ channels.append({"id": c.id, "dir": "out" if c.src.domain == self.name else "in",
+ "src": c.src.ident, "dst": c.dst.ident, "fields": list(c.fields), "url": url,
+ "interval_ms": int(c.config.get("interval_ms", 1000) or 1000)})
+ return {"title": title.strip() or "NLCL app", "size": size, "widgets": widgets, "channels": channels}
+
+ # ------------------------------------------------------------------ handlers
+ def _handlers(self, ctx: BuildContext, lang: str) -> tuple[dict, set[str], list[str]]:
+ """-> ({group: entries}, call names, notes). Entries are source snippets."""
+ local = {e.ident for e in ctx.entities}
+ H: dict = {"start": [], "update": [], "timers": [], "click": {}, "key": {}, "change": {}, "message": {}}
+ calls: set[str] = set()
+ notes: list[str] = []
+ n = 0
+ for e in ctx.entities:
+ for b in e.behaviors or []:
+ if not isinstance(b, dict) or not b.get("do"):
+ continue
+ n += 1
+ on = str(b.get("on") or "update")
+ kind, _, arg = on.partition(":")
+ name = self._namer(e, lang)
+ cond = self.expr(b["if"], "python" if lang == "py" else "js", name) if b.get("if") else None
+ acts = []
+ for a in b["do"]:
+ acts += self._action(e, a, lang, name, calls)
+ edge = None
+ if kind == "update" and cond:
+ edge = f"{e.ident}_{n}" # "when x is above 5, ..." fires once when it becomes true
+ fn = self._fn(e, cond, acts, lang, edge, on)
+ if kind == "start":
+ H["start"].append((e.ident, fn))
+ elif kind == "update":
+ H["update"].append((e.ident, fn))
+ elif kind == "timer":
+ try:
+ ms = max(10, int(float(arg)))
+ except ValueError:
+ ms = 1000
+ H["timers"].append((e.ident, ms, fn))
+ elif kind == "input":
+ key = arg.strip().lower().replace(" ", "_")
+ if key in ("click", "mouse", "tap", "touch", "clicked", "it", "self"):
+ H["click"].setdefault(e.ident, []).append((e.ident, fn))
+ elif key in local and key not in KEYS:
+ H["click"].setdefault(key, []).append((e.ident, fn))
+ else:
+ H["key"].setdefault({"return": "enter", "esc": "escape"}.get(key, key), []).append((e.ident, fn))
+ elif kind == "change":
+ ent, _, prop = arg.rpartition(".")
+ H["change"].setdefault((ent or e.ident, prop), []).append((e.ident, fn))
+ elif kind == "message":
+ H["message"].setdefault(arg or "any", []).append((e.ident, fn))
+ else:
+ notes.append(f"{e.name}: '{on}' has no meaning in a GUI app and was skipped")
+ return H, calls, notes
+
+ @staticmethod
+ def _namer(e: Entity, lang: str):
+ def f(n: str) -> str:
+ if "." in n:
+ ent, prop = n.split(".", 1)
+ return f"app.get({ent!r}, {prop!r})" if lang == "py" else f"app.get({json.dumps(ent)}, {json.dumps(prop)})"
+ return f"app.get({e.ident!r}, {n!r})" if lang == "py" else f"app.get({json.dumps(e.ident)}, {json.dumps(n)})"
+ return f
+
+ def _action(self, e: Entity, a: dict, lang: str, name, calls: set[str]) -> list[str]:
+ q = (lambda s: repr(s)) if lang == "py" else (lambda s: json.dumps(s, ensure_ascii=False))
+ ex = lambda v: self.expr(v, "python" if lang == "py" else "js", name) # noqa: E731
+ end = "" if lang == "py" else ";"
+ o, op = q(e.ident), a.get("op")
+ try:
+ if op == "set":
+ return [f"app.set({o}, {q(a['prop'])}, {ex(a['value'])}){end}"]
+ if op == "add":
+ return [f"app.add({o}, {q(a['prop'])}, {ex(a['value'])}){end}"]
+ if op == "toggle":
+ return [f"app.toggle({o}, {q(a['prop'])}){end}"]
+ if op == "destroy":
+ return [f"app.hide({o}){end}"]
+ if op == "log":
+ return [f"app.log({o}, {q(a.get('text', ''))}){end}"]
+ if op == "send":
+ none = "None" if lang == "py" else "null"
+ return [f"app.send({o}, {q(a['to']) if a.get('to') else none}, {q(list(a.get('fields') or []))}){end}"]
+ if op == "call":
+ calls.add(str(a["name"]))
+ args = "".join(", " + ex(x) for x in a.get("args", []))
+ return [f"app.call({o}, {q(a['name'])}{args}){end}"]
+ except Exception:
+ pass
+ text = describe_action(a) if isinstance(a, dict) and a.get("op") in ("move",) else str(a.get("op"))
+ return [("pass # " if lang == "py" else "/* ") + f"'{text}' is not meaningful in a GUI app" + ("" if lang == "py" else " */")]
+
+ @staticmethod
+ def _fn(e: Entity, cond: str | None, acts: list[str], lang: str, edge: str | None, on: str) -> list[str]:
+ """Body lines of one handler (no def line)."""
+ body = []
+ if cond and edge:
+ body.append(f"if not app.edge({edge!r}, {cond}): return" if lang == "py"
+ else f"if (!app.edge({json.dumps(edge)}, {cond})) return;")
+ elif cond:
+ body.append(f"if not ({cond}): return" if lang == "py" else f"if (!({cond})) return;")
+ return body + (acts or (["pass"] if lang == "py" else []))
+
+ # ------------------------------------------------------------------ python
+ def _py(self, ctx: BuildContext, spec: dict) -> str:
+ H, calls, notes = self._handlers(ctx, "py")
+ L = ["#!/usr/bin/env python3",
+ f'"""{spec["title"]} - desktop application (Windows / macOS / Linux). Generated by NLCL; edit freely."""',
+ "from nlcl_app import main", "",
+ "SPEC = " + _pyrepr(spec), ""]
+ L += [f"# note: {n}" for n in notes]
+ defs: list[str] = []
+ counter = [0]
+
+ def reg(owner, body, comment):
+ counter[0] += 1
+ fname = f"h{counter[0]}_{owner}"
+ defs.extend([f"def {fname}(app): # {comment}"] + [" " + ln for ln in body] + ["", ""])
+ return f"({owner!r}, {fname})"
+ groups = {"start": [reg(o, b, "on start") for o, b in H["start"]],
+ "update": [reg(o, b, "every tick") for o, b in H["update"]]}
+ timers = []
+ for o, ms, b in H["timers"]:
+ counter[0] += 1
+ fname = f"h{counter[0]}_{o}"
+ defs.extend([f"def {fname}(app): # every {ms} ms"] + [" " + ln for ln in b] + ["", ""])
+ timers.append(f"({o!r}, {ms}, {fname})")
+ maps = {}
+ for g in ("click", "key", "message"):
+ maps[g] = {k: [reg(o, b, f"{g} {k}") for o, b in v] for k, v in H[g].items()}
+ change = {k: [reg(o, b, f"when {k[0]}.{k[1]} changes") for o, b in v] for k, v in H["change"].items()}
+ L += defs
+ L += ["HANDLERS = {",
+ f" 'start': [{', '.join(groups['start'])}],",
+ f" 'update': [{', '.join(groups['update'])}],",
+ f" 'timers': [{', '.join(timers)}],"]
+ for g in ("click", "key", "message"):
+ L.append(f" {g!r}: {{" + ", ".join(f"{k!r}: [{', '.join(v)}]" for k, v in maps[g].items()) + "},")
+ L.append(" 'change': {" + ", ".join(f"{k!r}: [{', '.join(v)}]" for k, v in change.items()) + "},")
+ L += ["}", "", "# Your own functions for 'call ' actions: name -> function(app, owner, *args)",
+ "CALLS = {"]
+ for c in sorted(calls):
+ L.append(f" # {c!r}: lambda app, owner, *args: app.log(owner, {c + ' done'!r}),")
+ L += ["}", "", "", "if __name__ == '__main__':", " main(SPEC, HANDLERS, CALLS)", ""]
+ return "\n".join(L)
+
+ # ------------------------------------------------------------------ javascript
+ def _js(self, ctx: BuildContext, spec: dict) -> str:
+ H, calls, notes = self._handlers(ctx, "js")
+
+ def fn(body):
+ return "(app) => { " + " ".join(body) + " }"
+
+ def pairs(lst):
+ return "[" + ", ".join(f"[{json.dumps(o)}, {fn(b)}]" for o, b in lst) + "]"
+ L = [(ASSETS / "app_runtime.js").read_text(encoding="utf-8").rstrip(), "",
+ "// ---------------------------------------------------------------- generated by NLCL",
+ "const SPEC = " + json.dumps(spec, ensure_ascii=False, indent=1) + ";"]
+ L += [f"// note: {n}" for n in notes]
+ L += ["const HANDLERS = {",
+ f" start: {pairs(H['start'])},",
+ f" update: {pairs(H['update'])},",
+ " timers: [" + ", ".join(f"[{json.dumps(o)}, {ms}, {fn(b)}]" for o, ms, b in H["timers"]) + "],"]
+ for g in ("click", "key", "message"):
+ L.append(f" {g}: {{" + ", ".join(f"{json.dumps(k)}: {pairs(v)}" for k, v in H[g].items()) + "},")
+ L.append(" change: {" + ", ".join(f"{json.dumps(k[0] + '.' + k[1])}: {pairs(v)}" for k, v in H["change"].items()) + "},")
+ L += ["};", "// Your own functions for 'call ' actions: name -> (app, owner, ...args) => {}",
+ "const CALLS = {" + "".join(f"\n // {json.dumps(c)}: (app, owner, ...args) => app.log(owner, {json.dumps(c + ' done')})," for c in sorted(calls)) + "\n};",
+ "if (typeof document !== 'undefined') {",
+ " const app = new NlclApp(SPEC, HANDLERS, CALLS); window.app = app; app.mainloop();",
+ " if ('serviceWorker' in navigator && location.protocol.startsWith('http')) navigator.serviceWorker.register('sw.js').catch(() => {});",
+ "} else if (typeof process !== 'undefined' && process.argv.includes('--selftest')) {",
+ " new NlclApp(SPEC, HANDLERS, CALLS, null).selftest();",
+ "}", ""]
+ return "\n".join(L)
+
+ # ------------------------------------------------------------------ build
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
+ spec = self._spec(ctx)
+ slug = self.ident(spec["title"]) or "app"
+ title = spec["title"]
+ files = {
+ "nlcl_app.py": (ASSETS / "nlcl_app.py").read_text(encoding="utf-8"),
+ "app.py": self._py(ctx, spec),
+ "web/app.js": self._js(ctx, spec),
+ "web/index.html": _INDEX.replace("{title}", _html(title)),
+ "web/manifest.webmanifest": json.dumps({
+ "name": title, "short_name": title[:12], "start_url": ".", "display": "standalone",
+ "background_color": "#ffffff", "theme_color": "#2563eb",
+ "icons": [{"src": "icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any maskable"}]}, indent=1),
+ "web/sw.js": _SW,
+ "web/icon.svg": _ICON.replace("{letter}", _html((title[:1] or "N").upper())),
+ "build_windows.bat": f"@echo off\r\nrem Native Windows executable (free): pip install pyinstaller\r\n"
+ f"python -m PyInstaller --noconfirm --onefile --windowed --name {slug} app.py\r\n"
+ f"echo Done: dist\\{slug}.exe\r\n",
+ "build_macos.sh": f"#!/bin/sh\n# Native macOS app bundle (free): pip3 install pyinstaller\nset -e\n"
+ f"python3 -m PyInstaller --noconfirm --windowed --name {slug} app.py\n"
+ f"echo \"Done: dist/{slug}.app\"\n",
+ "build_linux.sh": f"#!/bin/sh\n# Native Linux executable (free): pip3 install pyinstaller ; needs python3-tk\nset -e\n"
+ f"python3 -m PyInstaller --noconfirm --onefile --name {slug} app.py\n"
+ f"cat > {slug}.desktop < list[str]:
+ out = []
+ if entity.kind in ("dropdown", "select", "list", "listbox") and not isinstance(entity.props.get("items", []), list):
+ out.append("items should be a list, e.g. 'with items red, green and blue'")
+ return out
+
+ def prompt_for(self, entity: Entity) -> str | None:
+ if entity.kind in ROOT_KINDS:
+ return f"What should {entity.name} contain? (e.g. 'add a button called ok with text \"OK\" to {entity.name}')"
+ return None
+
+ def run(self, ctx: BuildContext) -> RunResult | None:
+ out, ok = [], True
+ r = self.sh([sys.executable, "-u", "app.py", "--selftest"], ctx.outdir, timeout=30)
+ ok &= r.ok and "SELFTEST OK" in r.output
+ out.append("desktop (python app.py --selftest): " + ("OK" if r.ok and "SELFTEST OK" in r.output else "FAILED"))
+ out += [" " + ln[:300] for ln in r.output.splitlines()[-8:]]
+ node = self.which("node")
+ if node:
+ r2 = self.sh([node, "web/app.js", "--selftest"], ctx.outdir, timeout=30)
+ good = r2.ok and "SELFTEST OK" in r2.output
+ ok &= good
+ out.append("web/PWA (node web/app.js --selftest): " + ("OK" if good else "FAILED"))
+ if not good:
+ out += [" " + ln[:300] for ln in r2.output.splitlines()[-8:]]
+ out.append(f"start it: python {ctx.outdir / 'app.py'}")
+ return RunResult(ok, "\n".join(out), "app self-test")
+
+
+def _pyrepr(obj) -> str:
+ """JSON-like Python literal (True/False/None) with indentation."""
+ return json.dumps(obj, ensure_ascii=False, indent=1).replace(": true", ": True").replace(": false", ": False") \
+ .replace(": null", ": None").replace("[true", "[True").replace("[false", "[False") \
+ .replace(", true", ", True").replace(", false", ", False")
+
+
+def _html(s: str) -> str:
+ return str(s).replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
+
+
+_INDEX = """
+
+
+
+
+{title}
+
+
+
+
+
+
+{title}
+
+
+
+
+
+"""
+
+_SW = """// Offline cache for the installed app.
+const CACHE = "nlcl-app-v1";
+const FILES = ["./", "index.html", "app.js", "manifest.webmanifest", "icon.svg"];
+self.addEventListener("install", (e) => e.waitUntil(caches.open(CACHE).then((c) => c.addAll(FILES))));
+self.addEventListener("fetch", (e) => {
+ if (e.request.method !== "GET" || !e.request.url.startsWith(self.location.origin)) return;
+ e.respondWith(fetch(e.request).then((r) => { const copy = r.clone(); caches.open(CACHE).then((c) => c.put(e.request, copy)); return r; })
+ .catch(() => caches.match(e.request)));
+});
+"""
+
+_ICON = """
+"""
+
+MODULE = AppModule()
diff --git a/nlcl/modules/base.py b/nlcl/modules/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ad81da650f8c9f73e7bf997a32b04e09dbadc29
--- /dev/null
+++ b/nlcl/modules/base.py
@@ -0,0 +1,190 @@
+"""Domain module interface.
+
+A domain module turns the universal IR (entities, behaviours, channels) into
+artefacts for one execution environment: a game engine, a micro-controller,
+an HDL, a CAD tool ... Modules never see natural language.
+
+To add a new domain, drop a file in nlcl/modules/ that defines a subclass of
+DomainModule and exposes an instance as ``MODULE``.
+"""
+from __future__ import annotations
+
+import shutil
+import subprocess
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from ..ir import Entity, SystemState, ident, pascal, render_expr
+
+
+@dataclass
+class Channel:
+ """A resolved cross-entity communication path (from a Link)."""
+ id: str
+ protocol: str # serial | http | mqtt | gpio | spi | i2c | udp | websocket
+ src: Entity
+ dst: Entity
+ fields: list[str] # data fields carried src -> dst
+ config: dict = field(default_factory=dict) # baud, port, url, topic, broker, pins ...
+
+ def direction(self, entity_or_domain: Any) -> str | None:
+ """'out' if the given entity/domain is the sender, 'in' if receiver."""
+ if isinstance(entity_or_domain, Entity):
+ if entity_or_domain.id == self.src.id:
+ return "out"
+ if entity_or_domain.id == self.dst.id:
+ return "in"
+ return None
+ if self.src.domain == entity_or_domain:
+ return "out"
+ if self.dst.domain == entity_or_domain:
+ return "in"
+ return None
+
+ def peer(self, entity: Entity) -> Entity:
+ return self.dst if entity.id == self.src.id else self.src
+
+ @property
+ def topic(self) -> str:
+ return self.config.get("topic", f"nlcl/{self.id}")
+
+ @property
+ def hub_url(self) -> str:
+ return self.config.get("hub_url", "http://localhost:8765")
+
+ def to_dict(self) -> dict:
+ return {"id": self.id, "protocol": self.protocol, "src": self.src.name,
+ "src_domain": self.src.domain, "dst": self.dst.name,
+ "dst_domain": self.dst.domain, "fields": self.fields, "config": self.config}
+
+
+@dataclass
+class BuildContext:
+ system: SystemState
+ domain: str
+ entities: list[Entity] # entities of this domain (creation order)
+ channels: list[Channel] # every channel touching this domain
+ outdir: Path # where this module writes (already created)
+ project: str = "project"
+ llm: Any = None # optional LLM backend (may be None)
+
+ def channels_for(self, entity: Entity) -> list[Channel]:
+ return [c for c in self.channels if entity.id in (c.src.id, c.dst.id)]
+
+ def children(self, entity: Entity) -> list[Entity]:
+ return [e for e in self.entities if e.parent == entity.id]
+
+ def roots(self) -> list[Entity]:
+ ids = {e.id for e in self.entities}
+ return [e for e in self.entities if e.parent not in ids]
+
+
+@dataclass
+class RunResult:
+ ok: bool
+ output: str
+ command: str = ""
+
+
+class DomainModule:
+ # identity
+ name: str = "base" # canonical domain id, e.g. "game"
+ title: str = "Base"
+ aliases: tuple[str, ...] = () # other words that name this domain directly
+ keywords: tuple[str, ...] = () # words that *suggest* this domain (kinds, tech names)
+ # kind -> default props. "object" should always be present.
+ kinds: dict[str, dict] = {"object": {}}
+ # property names the module understands well (used for "What properties?" prompts)
+ suggested_props: tuple[str, ...] = ()
+ # protocols this domain can speak natively
+ protocols: tuple[str, ...] = ("http",)
+ # free toolchain advice shown in SYSTEM.md
+ toolchain: str = ""
+
+ # ---------------------------------------------------------------- props
+ def default_props(self, kind: str) -> dict:
+ return dict(self.kinds.get(kind, self.kinds.get("object", {})))
+
+ def validate(self, entity: Entity) -> list[str]:
+ """Return human-readable warnings (never raise)."""
+ return []
+
+ def prompt_for(self, entity: Entity) -> str | None:
+ """Optional follow-up question after an entity is created."""
+ if self.suggested_props:
+ return (f"What properties should {entity.name} have? "
+ f"(e.g. {', '.join(self.suggested_props[:5])})")
+ return None
+
+ # ---------------------------------------------------------------- build
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
+ """Return {relative_path: file_content}."""
+ raise NotImplementedError
+
+ def run(self, ctx: BuildContext) -> RunResult | None:
+ """Execute/simulate generated artefacts if a free local tool exists."""
+ return None
+
+ # ---------------------------------------------------------------- helpers
+ @staticmethod
+ def expr(e: Any, lang: str, name=lambda n: n) -> str:
+ return render_expr(e, lang, name)
+
+ @staticmethod
+ def ident(s: str) -> str:
+ return ident(s)
+
+ @staticmethod
+ def pascal(s: str) -> str:
+ return pascal(s)
+
+ @staticmethod
+ def which(*names: str) -> str | None:
+ for n in names:
+ p = shutil.which(n)
+ if p:
+ return p
+ return None
+
+ @staticmethod
+ def sh(cmd: list[str], cwd: Path, timeout: int = 30) -> RunResult:
+ try:
+ p = subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True,
+ timeout=timeout, encoding="utf-8", errors="replace")
+ return RunResult(p.returncode == 0, (p.stdout + p.stderr).strip(), " ".join(cmd))
+ except subprocess.TimeoutExpired as e:
+ out = (e.stdout or "") if isinstance(e.stdout, str) else ""
+ return RunResult(True, out + f"\n[stopped after {timeout}s]", " ".join(cmd))
+ except OSError as e:
+ return RunResult(False, str(e), " ".join(cmd))
+
+ @staticmethod
+ def literal(v: Any, lang: str) -> str:
+ """Render a property value as a literal in the target language."""
+ if isinstance(v, bool):
+ return {"python": "True" if v else "False",
+ "verilog": "1'b1" if v else "1'b0"}.get(lang, "true" if v else "false")
+ if isinstance(v, (int, float)):
+ if lang in ("csharp",) and isinstance(v, float):
+ return f"{v}f"
+ return repr(v)
+ if isinstance(v, (list, tuple)):
+ inner = ", ".join(DomainModule.literal(x, lang) for x in v)
+ return {"python": f"[{inner}]", "js": f"[{inner}]", "gdscript": f"[{inner}]",
+ "openscad": f"[{inner}]"}.get(lang, "{" + inner + "}")
+ s = str(v).replace("\\", "\\\\").replace('"', '\\"')
+ return f'"{s}"'
+
+ @staticmethod
+ def ctype(v: Any, lang: str) -> str:
+ """Best-effort static type for a value."""
+ if isinstance(v, bool):
+ return {"csharp": "bool", "cpp": "bool", "c": "bool", "gdscript": "bool"}.get(lang, "bool")
+ if isinstance(v, int):
+ return {"csharp": "int", "cpp": "int", "c": "int", "gdscript": "int"}.get(lang, "int")
+ if isinstance(v, float):
+ return {"csharp": "float", "cpp": "float", "c": "float", "gdscript": "float"}.get(lang, "float")
+ if isinstance(v, (list, tuple)):
+ return {"csharp": "float[]", "cpp": "std::vector", "gdscript": "Array"}.get(lang, "float*")
+ return {"csharp": "string", "cpp": "std::string", "c": "const char*", "gdscript": "String"}.get(lang, "String")
diff --git a/nlcl/modules/cad_mod.py b/nlcl/modules/cad_mod.py
new file mode 100644
index 0000000000000000000000000000000000000000..99d1526f1cd74ae3ff100c58b68b63052ef5d6e0
--- /dev/null
+++ b/nlcl/modules/cad_mod.py
@@ -0,0 +1,2107 @@
+"""CAD domain: parametric, 3D-printable parts as OpenSCAD (+ CadQuery) source.
+
+Every root entity becomes ``cad/.scad`` (parameters as top-level
+variables named ``_`` so they can be overridden with
+``openscad -D``), children of a part become features: holes / cutouts /
+ports are subtracted, other parts are unioned. ``cad/assembly.scad`` places
+every root part at its position/rotation. ``cad/_cadquery.py`` is a
+free CadQuery alternative and ``cad/cad_bridge.py`` connects parts to NLCL
+channels (live parameters in, part parameters out).
+
+Geometry is millimetres. Every part is centred on X/Y and sits on Z=0 (the
+print bed) unless stated otherwise.
+"""
+from __future__ import annotations
+
+import json
+import math
+import pprint
+import re
+
+from ..ir import Entity, describe_action, ident
+from .base import BuildContext, Channel, DomainModule, RunResult
+
+# ----------------------------------------------------------------------------
+# reference data
+# ----------------------------------------------------------------------------
+# Common boards: pcb length (x) / width (y), tallest component above the pcb,
+# mounting holes (from the lower-left pcb corner), mounting hole diameter and
+# connector cut-outs: (label, side, offset along the side from the pcb corner,
+# width, height). Dimensions are approximate - verify against your board.
+BOARDS = {
+ "uno": dict(title="Arduino Uno", l=68.6, w=53.4, comp=12.0, hole_d=3.2,
+ holes=[(14.0, 2.5), (15.3, 50.7), (66.1, 7.6), (66.1, 35.5)],
+ ports=[("usb-b", "left", 38.1, 12.5, 11.5), ("dc jack", "left", 7.6, 9.5, 11.5)]),
+ "mega": dict(title="Arduino Mega 2560", l=101.6, w=53.3, comp=12.0, hole_d=3.2,
+ holes=[(14.0, 2.5), (15.3, 50.7), (66.1, 7.6), (66.1, 35.5), (90.2, 50.7), (96.5, 2.5)],
+ ports=[("usb-b", "left", 38.1, 12.5, 11.5), ("dc jack", "left", 7.6, 9.5, 11.5)]),
+ "nano": dict(title="Arduino Nano", l=45.0, w=18.0, comp=8.0, hole_d=0, holes=[],
+ ports=[("usb", "left", 9.0, 9.0, 5.0)]),
+ "esp32": dict(title="ESP32 DevKit", l=55.0, w=28.0, comp=8.0, hole_d=0, holes=[],
+ ports=[("usb", "left", 14.0, 10.0, 5.0)]),
+ "esp8266": dict(title="ESP8266 NodeMCU", l=49.0, w=26.0, comp=8.0, hole_d=3.0,
+ holes=[(2.5, 2.5), (46.5, 2.5), (2.5, 23.5), (46.5, 23.5)],
+ ports=[("usb", "left", 13.0, 10.0, 5.0)]),
+ "pico": dict(title="Raspberry Pi Pico", l=51.0, w=21.0, comp=4.0, hole_d=2.1,
+ holes=[(2.0, 4.8), (2.0, 16.2), (49.0, 4.8), (49.0, 16.2)],
+ ports=[("usb", "left", 10.5, 9.0, 4.5)]),
+ "rpi4": dict(title="Raspberry Pi 4", l=85.0, w=56.0, comp=16.0, hole_d=2.75,
+ holes=[(3.5, 3.5), (61.5, 3.5), (3.5, 52.5), (61.5, 52.5)],
+ ports=[("usb-c power", "front", 11.2, 10.0, 4.5), ("micro hdmi 0", "front", 26.0, 8.0, 4.0),
+ ("micro hdmi 1", "front", 39.5, 8.0, 4.0), ("usb a 1", "right", 9.0, 14.5, 16.0),
+ ("usb a 2", "right", 27.0, 14.5, 16.0), ("ethernet", "right", 45.75, 16.5, 14.0)]),
+ "pizero": dict(title="Raspberry Pi Zero", l=65.0, w=30.0, comp=5.0, hole_d=2.75,
+ holes=[(3.5, 3.5), (61.5, 3.5), (3.5, 26.5), (61.5, 26.5)],
+ ports=[("mini hdmi", "front", 12.4, 12.0, 4.5), ("micro usb", "front", 41.4, 9.0, 4.0),
+ ("micro usb power", "front", 54.0, 9.0, 4.0)]),
+}
+# normalised text fragment -> board key (checked in order)
+BOARD_MATCH = [("pi4", "rpi4"), ("raspberrypi4", "rpi4"), ("rpi4", "rpi4"), ("pizero", "pizero"),
+ ("rpizero", "pizero"), ("pico", "pico"), ("mega", "mega"), ("nano", "nano"),
+ ("uno", "uno"), ("esp8266", "esp8266"), ("nodemcu", "esp8266"), ("wemos", "esp8266"),
+ ("esp32", "esp32"), ("esp", "esp32"), ("raspberrypi", "rpi4"), ("rpi", "rpi4"),
+ ("arduino", "uno")]
+
+# child features that are *subtracted* from their parent.
+# shape: round (d) | rect (w x h) | slots ; side: default face
+FEATURES = {
+ "usb_c": dict(shape="rect", w=10.0, h=4.5, side="left"),
+ "usb": dict(shape="rect", w=12.0, h=7.0, side="left"),
+ "hdmi": dict(shape="rect", w=16.0, h=7.0, side="back"),
+ "ethernet": dict(shape="rect", w=17.0, h=14.0, side="back"),
+ "button": dict(shape="round", d=12.0, side="top"),
+ "switch": dict(shape="rect", w=13.0, h=9.0, side="front"),
+ "led": dict(shape="round", d=5.2, side="top"),
+ "lcd": dict(shape="rect", w=72.0, h=25.0, side="top"),
+ "oled": dict(shape="rect", w=27.0, h=16.0, side="top"),
+ "display": dict(shape="rect", w=27.0, h=16.0, side="top"),
+ "screen": dict(shape="rect", w=27.0, h=16.0, side="top"),
+ "jack": dict(shape="round", d=8.0, side="back"),
+ "barrel": dict(shape="round", d=8.0, side="back"),
+ "power": dict(shape="round", d=8.0, side="back"),
+ "cable": dict(shape="round", d=6.0, side="back"),
+ "wire": dict(shape="round", d=6.0, side="back"),
+ "antenna": dict(shape="round", d=6.5, side="back"),
+ "potentiometer": dict(shape="round", d=7.0, side="front"),
+ "pot": dict(shape="round", d=7.0, side="front"),
+ "encoder": dict(shape="round", d=7.0, side="top"),
+ "buzzer": dict(shape="round", d=12.0, side="top"),
+ "speaker": dict(shape="round", d=20.0, side="top"),
+ "sensor": dict(shape="round", d=10.0, side="top"),
+ "fan": dict(shape="round", d=28.0, side="top"),
+ "vent": dict(shape="slots", side="front"),
+ "grille": dict(shape="slots", side="front"),
+ "slot": dict(shape="rect", w=20.0, h=2.0, side="top"),
+ "window": dict(shape="rect", w=20.0, h=10.0, side="front"),
+ "opening": dict(shape="rect", w=10.0, h=6.0, side="front"),
+ "port": dict(shape="rect", w=10.0, h=6.0, side="front"),
+ "cutout": dict(shape="rect", w=10.0, h=6.0, side="front"),
+ "hole": dict(shape="round", d=3.2, side="top"),
+ "bore": dict(shape="round", d=5.0, side="top"),
+}
+
+# words that map onto an implemented geometry ("canonical kind")
+KIND_MAP = {
+ "object": "box", "part": "box", "box": "box", "block": "box", "cuboid": "box", "brick": "box",
+ "cube": "cube",
+ "cylinder": "cylinder", "rod": "cylinder", "disc": "cylinder", "disk": "cylinder", "puck": "cylinder",
+ "peg": "cylinder", "shaft": "cylinder", "axle": "cylinder",
+ "sphere": "sphere", "ball": "sphere",
+ "cone": "cone",
+ "plate": "plate", "panel": "plate", "baseplate": "plate", "sheet": "plate", "faceplate": "plate",
+ "enclosure": "enclosure", "case": "enclosure", "housing": "enclosure", "casing": "enclosure",
+ "shell": "enclosure",
+ "bracket": "bracket", "angle": "bracket",
+ "standoff": "standoff", "boss": "standoff",
+ "spacer": "spacer", "bushing": "spacer",
+ "washer": "washer",
+ "gear": "gear", "cog": "gear", "sprocket": "gear", "pinion": "gear",
+ "tube": "tube", "pipe": "tube", "ring": "tube", "sleeve": "tube",
+ "knob": "knob", "dial": "knob",
+ "hinge": "hinge",
+ "mount": "mount", "holder": "mount", "clip": "mount", "clamp": "mount", "cradle": "mount",
+}
+GEOMETRY_KINDS = {"box", "cube", "cylinder", "sphere", "cone", "plate", "enclosure", "bracket", "standoff",
+ "spacer", "washer", "gear", "tube", "knob", "hinge", "mount"}
+PALETTE = ["SteelBlue", "Orange", "SeaGreen", "Tomato", "SlateGray", "Gold", "Orchid", "Peru"]
+GENERIC_FEATURES = {"hole", "cutout", "opening", "port", "slot", "window", "bore"}
+PROP_ALIASES = {"holes": "hole_count", "number_of_holes": "hole_count", "hole_number": "hole_count",
+ "num_holes": "hole_count", "outer_diameter": "diameter", "outside_diameter": "diameter",
+ "inner_diameter": "hole_diameter", "inside_diameter": "hole_diameter",
+ "number_of_teeth": "teeth", "tooth_count": "teeth", "teeth_count": "teeth",
+ "thick": "thickness", "tall": "height", "long": "length", "wide": "width"}
+
+SIDE_WORDS = {"left": "left", "right": "right", "front": "front", "back": "back", "rear": "back",
+ "top": "top", "lid": "top", "bottom": "bottom", "floor": "bottom", "base": "bottom",
+ "-x": "left", "+x": "right", "-y": "front", "+y": "back", "+z": "top", "-z": "bottom"}
+
+
+# ----------------------------------------------------------------------------
+# small value helpers (never raise)
+# ----------------------------------------------------------------------------
+def _num(v, default=None):
+ """Coerce a prop value to float; None/garbage -> default."""
+ if isinstance(v, bool) or v is None:
+ return default
+ if isinstance(v, (int, float)):
+ return float(v) if math.isfinite(v) else default
+ if isinstance(v, (list, tuple)):
+ return _num(v[0], default) if v else default
+ m = re.search(r"-?\d+(?:\.\d+)?", str(v))
+ return float(m.group(0)) if m else default
+
+
+def _vec(v, n=3):
+ """Coerce size-like values ([80,50,30], 80, '80x50x30') to a list of floats (may be shorter than n)."""
+ if v is None or isinstance(v, bool):
+ return []
+ if isinstance(v, (int, float)):
+ return [float(v)]
+ if isinstance(v, (list, tuple)):
+ out = [_num(x) for x in v]
+ return [x for x in out if x is not None][:n]
+ return [float(x) for x in re.findall(r"-?\d+(?:\.\d+)?", str(v))][:n]
+
+
+def _truthy(v, default=False):
+ if v is None:
+ return default
+ if isinstance(v, bool):
+ return v
+ if isinstance(v, (int, float)):
+ return v != 0
+ return str(v).strip().lower() in ("true", "yes", "on", "1", "y", "enabled")
+
+
+def _n(x) -> str:
+ """Number literal for OpenSCAD / Python."""
+ try:
+ x = float(x)
+ except (TypeError, ValueError):
+ return "0"
+ if not math.isfinite(x):
+ return "0"
+ x = round(x, 4)
+ if x == int(x):
+ return str(int(x))
+ return repr(x)
+
+
+def _pos(e: Entity, default=(0.0, 0.0, 0.0)) -> list[float]:
+ p = _vec(e.props.get("position"))
+ if not p:
+ return list(default)
+ return (p + list(default)[len(p):])[:3]
+
+
+def _rot(e: Entity) -> list[float]:
+ r = None
+ for k in ("rotation", "rotate", "angle", "rotate_by", "rotated_by", "rotated", "rotate_to", "turn", "turn_by"):
+ if e.props.get(k) is not None and not isinstance(e.props.get(k), bool):
+ r = e.props.get(k)
+ break
+ v = _vec(r)
+ if not v:
+ return [0.0, 0.0, 0.0]
+ if len(v) == 1:
+ return [0.0, 0.0, v[0]]
+ return (v + [0.0, 0.0])[:3]
+
+
+def _color(v, fallback: str | None) -> str | None:
+ if v is None or isinstance(v, bool):
+ return fallback
+ if isinstance(v, (list, tuple)):
+ nums = [_num(x, 0.0) for x in v][:3]
+ if len(nums) == 3:
+ if max(nums) > 1:
+ nums = [c / 255.0 for c in nums]
+ return "#%02x%02x%02x" % tuple(int(max(0.0, min(1.0, c)) * 255) for c in nums)
+ return fallback
+ s = re.sub(r"[^A-Za-z0-9#]", "", str(v))
+ if re.fullmatch(r"#?[0-9a-fA-F]{6}", s):
+ return "#" + s.lstrip("#")
+ return s or fallback
+
+
+def _scad_str(s: str) -> str:
+ return '"' + str(s).replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+def _is_start(b: dict) -> bool:
+ """A start-up behaviour (also the 'update if started == true' form some parsers produce)."""
+ cond = re.sub(r"\s+", " ", str(b.get("if") or "")).strip().lower()
+ if b.get("on") == "start":
+ return not cond
+ return b.get("on") == "update" and cond in ("started == true", "started", "started == 1")
+
+
+def _comment(s: str) -> str:
+ return re.sub(r"[\r\n]+", " ", str(s))
+
+
+# ----------------------------------------------------------------------------
+# the module
+# ----------------------------------------------------------------------------
+class CadModule(DomainModule):
+ name = "cad"
+ title = "CAD (parametric 3D-printable parts: OpenSCAD + CadQuery)"
+ aliases = ("cad", "openscad", "mechanical", "3d-print", "printable", "قطعه")
+ keywords = ("cadquery", "freecad", "scad", "stl", "printable", "printer", "3d-printer",
+ "printing", "filament", "pla", "petg", "slicer", "cura", "prusaslicer", "prusa",
+ "mm", "millimeter", "millimeters", "millimetre", "enclosure", "housing", "casing", "case",
+ "lid", "bracket", "standoff", "standoffs", "spacer", "washer", "bushing", "gear", "gears",
+ "cog", "sprocket", "pinion", "tube", "pipe", "knob", "dial", "hinge", "mount", "holder",
+ "clip", "clamp", "cradle", "plate", "baseplate", "faceplate", "fillet", "chamfer", "gusset",
+ "boss", "flange", "extrusion", "cutout", "bore", "countersink", "screw", "bolt", "nut",
+ "m3", "m2.5", "infill", "mechanical", "cuboid", "cylinder", "cone")
+ kinds = {
+ "object": {},
+ "part": {"size": [20, 20, 20]},
+ "box": {"size": [20, 20, 20]},
+ "cube": {"size": 20},
+ "cylinder": {"diameter": 20, "height": 20},
+ "sphere": {"diameter": 20},
+ "cone": {"diameter": 20, "top_diameter": 0, "height": 20},
+ "plate": {"size": [60, 40, 3], "hole_count": 4, "hole_diameter": 3.2, "corner_radius": 3},
+ "enclosure": {"wall": 2},
+ "case": {"wall": 2},
+ "housing": {"wall": 2},
+ "bracket": {"width": 20, "length": 40, "height": 30, "thickness": 3, "hole_diameter": 4.2},
+ "standoff": {"height": 10, "diameter": 6, "hole_diameter": 2.7},
+ "spacer": {"height": 5, "diameter": 7, "hole_diameter": 3.4},
+ "washer": {"diameter": 10, "hole_diameter": 5.3, "thickness": 1},
+ "gear": {"teeth": 20, "module": 1, "thickness": 5, "bore": 5},
+ "tube": {"diameter": 20, "wall": 2, "length": 50},
+ "pipe": {"diameter": 20, "wall": 2, "length": 50},
+ "knob": {"diameter": 20, "height": 15, "shaft_diameter": 6},
+ "hinge": {"width": 40, "leaf": 20, "thickness": 3, "knuckles": 5, "pin_diameter": 3},
+ "mount": {"diameter": 20, "width": 15, "thickness": 3, "hole_diameter": 4.2},
+ "hole": {},
+ "cutout": {},
+ }
+ suggested_props = ("size", "wall", "hole_diameter", "fillet", "board", "vents", "color", "position",
+ "rotation", "quality")
+ protocols = ("http", "mqtt", "serial", "udp", "websocket")
+ toolchain = """Free tools for the CAD output (all millimetres):
+
+* **OpenSCAD** (openscad.org): open `cad/assembly.scad` or any `cad/.scad`, F6 to render, F7 to export STL.
+ Command line: `openscad -o assembly.stl cad/assembly.scad` ; override a parameter:
+ `openscad -D "case_wall=2.4" -o case.stl cad/case.scad`.
+* **CadQuery** (`pip install cadquery`): `python cad/_cadquery.py` writes STL + STEP (or open it in CQ-editor).
+* **FreeCAD** can import the STEP/STL files; **Cura** / **PrusaSlicer** / **OrcaSlicer** slice the STL for printing.
+* `python cad/cad_bridge.py` (stdlib) links parts to NLCL channels (live parameters / published dimensions)."""
+
+ # ------------------------------------------------------------------ props
+ def default_props(self, kind: str) -> dict:
+ k = (kind or "object").lower()
+ if k in self.kinds:
+ return json.loads(json.dumps(self.kinds[k]))
+ return {}
+
+ def prompt_for(self, entity: Entity) -> str | None:
+ if entity.parent and self._is_cut(entity):
+ return (f"Where and how big is the {entity.name} cut-out? "
+ f"(e.g. side front, diameter 6 / width 12 height 7, position 10 0 8)")
+ k = self._kind(entity)
+ hints = {
+ "enclosure": "size 80 50 30, wall 2, board esp32, vents true, fillet 3",
+ "plate": "size 60 40 3, hole_count 4, hole_diameter 3.2, corner_radius 3",
+ "gear": "teeth 24, module 1.5, thickness 6, bore 5",
+ "bracket": "width 20, length 40, height 30, thickness 3",
+ "cylinder": "diameter 20, height 30",
+ }.get(k)
+ if hints:
+ return f"What dimensions should {entity.name} have? (e.g. {hints})"
+ return super().prompt_for(entity)
+
+ def validate(self, entity: Entity) -> list[str]:
+ out = []
+ try:
+ k = self._kind(entity)
+ p = entity.props
+ wall = _num(p.get("wall", p.get("thickness")))
+ if wall is not None and 0 < wall < 0.8 and k in ("enclosure", "tube", "plate", "bracket"):
+ out.append(f"wall/thickness {wall} mm is thinner than two 0.4 mm nozzle lines (min ~0.8 mm)")
+ if k == "gear":
+ t = _num(p.get("teeth"), 20)
+ if t < 6:
+ out.append("gears need at least 6 teeth (using 6)")
+ used = self.default_props(entity.kind) or self.default_props(k)
+ for key in ("size", "width", "depth", "height", "diameter", "radius", "length"):
+ for x in _vec(p.get(key)):
+ if x < 0 or (x == 0 and (key in used or key in ("size", "width", "depth"))):
+ out.append(f"{key} must be positive (got {x})")
+ elif x > 1000:
+ out.append(f"{key} {x} mm is larger than most printers (values are millimetres)")
+ if k == "enclosure":
+ b = self._board_key(entity, None)
+ size = _vec(p.get("size"))
+ if b and len(size) >= 2:
+ bd = BOARDS[b]
+ if size[0] < bd["l"] + 2 or size[1] < bd["w"] + 2:
+ out.append(f"size {size} is too small for {bd['title']} "
+ f"({bd['l']}x{bd['w']} mm); enlarged automatically")
+ except Exception: # validation must never raise
+ pass
+ return out
+
+ # ------------------------------------------------------------------ kind helpers
+ def _kind(self, e: Entity) -> str:
+ k = ident(e.kind or "object")
+ if k in ("object", "part") and e.props.get("subtype"):
+ sub = ident(str(e.props.get("subtype")))
+ for w in [sub] + sub.split("_"):
+ if w in KIND_MAP and KIND_MAP[w] != "box":
+ return KIND_MAP[w]
+ if k in KIND_MAP:
+ ck = KIND_MAP[k]
+ else:
+ ck = None
+ for w in reversed(k.split("_")):
+ if w in KIND_MAP:
+ ck = KIND_MAP[w]
+ break
+ if ck is None:
+ fk = self._feature_key(e)
+ ck = ("cylinder" if FEATURES[fk]["shape"] == "round" else "box") if fk else "box"
+ if ck == "box" and ("lid" in e.props or _truthy(e.props.get("hollow"))):
+ ck = "enclosure"
+ return ck
+
+ def _feature_key(self, e: Entity) -> str | None:
+ """Most specific feature-table key named by the kind, subtype or name (usb hole -> usb)."""
+ words = [ident(e.kind)] + ident(e.kind).split("_")
+ if e.props.get("subtype"):
+ s = ident(str(e.props["subtype"]))
+ words += [s] + s.split("_")
+ words += [e.ident] + e.ident.split("_")
+ found = [w for w in words if w in FEATURES]
+ for key in FEATURES: # substring match ("usbport", "holes")
+ if any(key in w for w in words if len(w) > 3) and key not in found:
+ found.append(key)
+ specific = [w for w in found if w not in GENERIC_FEATURES]
+ return (specific or found or [None])[0]
+
+ def _foreign_features(self, ctx: BuildContext | None, e: Entity) -> list[Entity]:
+ """Entities of other domains placed "on/in" this part (core sets for_entity), e.g. an embedded
+ led or button added to a CAD enclosure: they become cut-outs (a hole for the led, ...)."""
+ out: list[Entity] = []
+ try:
+ system = ctx.system if ctx else None
+ if system is None:
+ return out
+ mine = {str(e.name).lower(), e.ident}
+ for o in system.entities.values():
+ if o.domain == e.domain or o.parent:
+ continue
+ fe = (o.props or {}).get("for_entity")
+ if fe is None or str(fe).lower() not in mine and ident(str(fe)) not in mine:
+ continue
+ if self._feature_key(o) is None:
+ continue
+ props = {k: v for k, v in (o.props or {}).items() if k not in ("color", "colour")}
+ for k, val in list(props.items()): # 'side_front': True -> side 'front'
+ m = re.fullmatch(r"(side|face|location)_(\w+)", str(k))
+ if m and val is True and m.group(1) not in props:
+ props[m.group(1)] = m.group(2)
+ props["cut"] = True
+ out.append(Entity(id=o.id, name=o.name, domain=e.domain, kind=o.kind, props=props,
+ behaviors=[], parent=e.id))
+ except Exception:
+ return []
+ return out
+
+ def _is_cut(self, e: Entity) -> bool:
+ p = e.props
+ if _truthy(p.get("cut")) or _truthy(p.get("subtract")) or _truthy(p.get("negative")):
+ return True
+ if _truthy(p.get("solid")) or _truthy(p.get("add")):
+ return False
+ k = ident(e.kind)
+ if k in KIND_MAP and KIND_MAP[k] in GEOMETRY_KINDS and k not in ("object", "part"):
+ return False
+ return self._feature_key(e) is not None
+
+ # ------------------------------------------------------------------ board lookup
+ def _board_key(self, e: Entity, ctx: BuildContext | None) -> str | None:
+ texts = []
+ for key in ("board", "for", "fits", "contains", "mcu", "controller", "model", "subtype"):
+ v = e.props.get(key)
+ if v is not None and not isinstance(v, bool):
+ texts.append(str(v))
+ system = ctx.system if ctx else None
+ # the part's own name only counts word-by-word ("respirator case" must not match "esp")
+ for w in re.split(r"[^a-z0-9]+", str(e.name).lower()):
+ if any(w.startswith(frag) for frag, _k in BOARD_MATCH):
+ texts.append(w)
+ # a prop naming another entity ("board esp" where esp is an embedded entity)
+ if system is not None:
+ for t in list(texts):
+ other = None
+ for o in system.entities.values():
+ if o.id != e.id and (o.name.lower() == str(t).lower() or o.ident == ident(str(t))):
+ other = o
+ break
+ if other is not None:
+ texts += [str(other.props.get("board", "")), str(other.props.get("model", "")),
+ other.kind, other.name]
+ # peers over channels (e.g. the esp32 that lives inside this case)
+ if ctx is not None:
+ for c in ctx.channels_for(e):
+ peer = c.peer(e)
+ if peer.domain in ("embedded", "hardware"):
+ texts += [str(peer.props.get("board", "")), peer.kind, peer.name]
+ for t in texts:
+ norm = re.sub(r"[^a-z0-9]", "", str(t).lower())
+ if not norm:
+ continue
+ for frag, key in BOARD_MATCH:
+ if frag in norm:
+ return key
+ return None
+
+ # ==================================================================
+ # parameters per kind
+ # ==================================================================
+ def _params(self, ctx: BuildContext | None, e: Entity) -> tuple[dict, list[float], dict]:
+ """Return (params, bbox [x,y,z], extra). params are scalar numbers/bools/strings."""
+ k = self._kind(e)
+ p = e.props
+ fk = self._feature_key(e) if ident(e.kind) not in KIND_MAP else None
+ if fk: # a feature (hole, usb, ...) without a parent: show it as a solid stand-in
+ spec = FEATURES[fk]
+ stand_in = ({"diameter": spec.get("d", 3.2)} if spec["shape"] == "round"
+ else {"width": spec.get("w", 10.0), "depth": spec.get("h", 6.0)})
+ stand_in["height"] = 10.0
+ stand_in.update(p)
+ p = stand_in
+ g = lambda *names, d=None: next((x for x in (_num(p.get(n)) for n in names) if x is not None), d)
+ size = _vec(p.get("size"))
+ extra: dict = {}
+ P: dict = {}
+ if k in ("box", "cube"):
+ dflt = 20.0
+ if len(size) == 1:
+ size = size * 3
+ size = (size + [dflt] * 3)[:3] if size else [dflt] * 3
+ P["width"] = g("width", "length", d=size[0])
+ P["depth"] = g("depth", d=size[1])
+ P["height"] = g("height", d=size[2])
+ P["fillet"] = g("fillet", "rounding", "corner_radius", d=0.0)
+ if g("hole_diameter", d=0) > 0:
+ P["hole_diameter"] = g("hole_diameter")
+ bbox = [P["width"], P["depth"], P["height"]]
+ elif k == "cylinder":
+ d = g("diameter", d=None)
+ if d is None:
+ r = g("radius")
+ d = 2 * r if r else (size[0] if size else 20.0)
+ P["diameter"] = d
+ P["height"] = g("height", "length", d=size[2] if len(size) > 2 else (size[1] if len(size) == 2 else 20.0))
+ P["hole_diameter"] = g("hole_diameter", "bore", d=0.0)
+ bbox = [d, d, P["height"]]
+ elif k == "sphere":
+ d = g("diameter", d=None)
+ if d is None:
+ r = g("radius")
+ d = 2 * r if r else (size[0] if size else 20.0)
+ P["diameter"] = d
+ bbox = [d, d, d]
+ elif k == "cone":
+ d = g("diameter", "bottom_diameter", d=None)
+ if d is None:
+ r = g("radius")
+ d = 2 * r if r else 20.0
+ P["diameter"] = d
+ P["top_diameter"] = g("top_diameter", d=0.0)
+ P["height"] = g("height", "length", d=20.0)
+ bbox = [d, d, P["height"]]
+ elif k == "plate":
+ size = (size + [60.0, 40.0, 3.0][len(size):])[:3]
+ P["width"] = g("width", "length", d=size[0])
+ P["depth"] = g("depth", d=size[1])
+ P["thickness"] = g("thickness", "height", d=size[2])
+ P["corner_radius"] = g("corner_radius", "fillet", "rounding", "radius", d=3.0)
+ P["hole_count"] = int(max(0, min(200, g("hole_count", "holes", d=4))))
+ P["hole_diameter"] = g("hole_diameter", d=3.2)
+ P["hole_inset"] = g("hole_inset", d=max(P["hole_diameter"] * 1.5, 5.0))
+ P["countersink"] = _truthy(p.get("countersink"))
+ bbox = [P["width"], P["depth"], P["thickness"]]
+ elif k == "enclosure":
+ P, bbox, extra = self._enclosure_params(ctx, e, size, g)
+ elif k == "bracket":
+ P["width"] = g("width", d=size[1] if len(size) > 1 else 20.0)
+ P["length"] = g("length", d=size[0] if size else 40.0)
+ P["height"] = g("height", d=size[2] if len(size) > 2 else 30.0)
+ P["thickness"] = g("thickness", "wall", d=3.0)
+ P["hole_diameter"] = g("hole_diameter", d=4.2)
+ P["holes_per_leg"] = int(max(0, min(20, g("holes_per_leg", d=max(1.0, g("hole_count", d=4) / 2)))))
+ P["gusset"] = _truthy(p.get("gusset"), True)
+ bbox = [P["length"], P["width"], P["height"]]
+ elif k in ("standoff", "spacer", "washer"):
+ defaults = {"standoff": (10.0, 6.0, 2.7), "spacer": (5.0, 7.0, 3.4), "washer": (1.0, 10.0, 5.3)}[k]
+ P["height"] = g("height", "length", "thickness", d=defaults[0])
+ d = g("diameter", d=None)
+ if d is None:
+ r = g("radius")
+ d = 2 * r if r else defaults[1]
+ P["diameter"] = d
+ P["hole_diameter"] = min(g("hole_diameter", "bore", d=defaults[2]), d - 0.8)
+ P["hex"] = _truthy(p.get("hex"), False) or str(p.get("shape", "")).lower() in ("hex", "hexagon")
+ bbox = [d, d, P["height"]]
+ elif k == "gear":
+ P["teeth"] = int(max(6, min(400, g("teeth", "tooth_count", d=20))))
+ P["module"] = max(0.2, g("module", "gear_module", d=None) or
+ (g("pitch_diameter", "diameter", d=0) / P["teeth"]) or 1.0)
+ P["thickness"] = g("thickness", "height", "width", d=5.0)
+ P["bore"] = max(0.0, g("bore", "hole_diameter", "shaft_diameter", d=5.0))
+ od = P["module"] * (P["teeth"] + 2)
+ bbox = [od, od, P["thickness"]]
+ elif k == "tube":
+ d = g("diameter", "outer_diameter", d=None)
+ if d is None:
+ r = g("radius")
+ d = 2 * r if r else 20.0
+ P["diameter"] = d
+ inner = g("inner_diameter", d=None)
+ P["wall"] = (d - inner) / 2 if inner else g("wall", "thickness", d=2.0)
+ P["wall"] = max(0.4, min(P["wall"], d / 2 - 0.2))
+ P["length"] = g("length", "height", d=50.0)
+ bbox = [d, d, P["length"]]
+ elif k == "knob":
+ P["diameter"] = g("diameter", d=(2 * g("radius", d=10.0)))
+ P["height"] = g("height", d=15.0)
+ P["shaft_diameter"] = g("shaft_diameter", "hole_diameter", "bore", d=6.0)
+ P["d_shaft"] = _truthy(p.get("d_shaft"), True)
+ P["ridges"] = int(max(0, min(120, g("ridges", "grip", d=18))))
+ bbox = [P["diameter"], P["diameter"], P["height"]]
+ elif k == "hinge":
+ P["width"] = g("width", "length", d=40.0)
+ P["leaf"] = g("leaf", "leaf_length", "depth", d=20.0)
+ P["thickness"] = g("thickness", d=3.0)
+ P["knuckles"] = int(max(2, min(15, g("knuckles", d=5))))
+ P["pin_diameter"] = g("pin_diameter", d=3.0)
+ P["clearance"] = g("clearance", d=0.4)
+ P["hole_diameter"] = g("hole_diameter", d=3.2)
+ kd = P["pin_diameter"] + 2 * P["clearance"] + 3.2
+ bbox = [P["width"], 2 * P["leaf"] + kd, max(kd, P["thickness"])]
+ elif k == "mount":
+ P["diameter"] = g("diameter", "item_diameter", d=(2 * g("radius", d=10.0)))
+ P["width"] = g("width", d=15.0)
+ P["thickness"] = g("thickness", "wall", d=3.0)
+ P["hole_diameter"] = g("hole_diameter", d=4.2)
+ L = P["diameter"] + 2 * P["thickness"] + 6 * P["hole_diameter"]
+ bbox = [P["width"], L, P["diameter"] + 2 * P["thickness"]]
+ else: # unreachable fallback: generic box
+ P = {"width": 20.0, "depth": 20.0, "height": 20.0, "fillet": 0.0}
+ bbox = [20.0, 20.0, 20.0]
+ # common: dimensions must be positive and finite
+ for key, dflt in (("width", 20.0), ("depth", 20.0), ("height", 20.0), ("diameter", 20.0), ("length", 20.0),
+ ("thickness", 2.0), ("wall", 2.0), ("module", 1.0), ("leaf", 20.0), ("pin_diameter", 3.0)):
+ val = P.get(key)
+ if isinstance(val, (int, float)) and not isinstance(val, bool) and (not math.isfinite(val) or val <= 0):
+ P[key] = dflt
+ bbox = [dflt if (not isinstance(b, (int, float)) or b <= 0) else b for b in bbox]
+ for key in ("hole_diameter", "fillet", "corner_radius", "bore", "top_diameter", "hole_inset"):
+ val = P.get(key)
+ if isinstance(val, (int, float)) and not isinstance(val, bool) and (not math.isfinite(val) or val < 0):
+ P[key] = 0.0
+ q = p.get("quality", p.get("fn", p.get("resolution")))
+ if isinstance(q, str) and q.strip().lower() in ("low", "draft", "fast"):
+ fn = 24
+ elif isinstance(q, str) and q.strip().lower() in ("high", "fine", "smooth"):
+ fn = 128
+ else:
+ fn = int(max(8, min(360, _num(q, 64.0))))
+ P["fn"] = fn
+ for key, v in list(P.items()):
+ if isinstance(v, float) and not math.isfinite(v):
+ P[key] = 0.0
+ return P, [max(0.01, float(x)) for x in bbox], extra
+
+ def _enclosure_params(self, ctx, e, size, g):
+ p = e.props
+ extra: dict = {}
+ wall = max(0.8, g("wall", "wall_thickness", "thickness", d=2.0))
+ board = self._board_key(e, ctx)
+ clearance = g("clearance", d=1.0)
+ standoff_h = g("standoff_height", d=5.0)
+ dims = (size + [80.0, 50.0, 30.0][len(size):])[:3] if size else None
+ W = g("width", "length", d=dims[0] if dims else None)
+ D = g("depth", d=dims[1] if dims else None)
+ H = g("height", d=dims[2] if dims else None)
+ if board:
+ bd = BOARDS[board]
+ need = [bd["l"] + 2 * clearance + 2 * wall,
+ bd["w"] + 2 * clearance + 2 * wall,
+ standoff_h + 1.6 + bd["comp"] + 2.0 + 2 * wall]
+ W = max(W or 0, need[0])
+ D = max(D or 0, need[1])
+ H = max(H or 0, need[2])
+ extra["board"] = board
+ W, D, H = W or 80.0, D or 50.0, H or 30.0
+ H = max(H, 2 * wall + 4)
+ P = {"width": W, "depth": D, "height": H, "wall": wall,
+ "fillet": g("fillet", "rounding", "corner_radius", d=3.0),
+ "lip_height": g("lip_height", d=3.0), "lip_thickness": g("lip_thickness", d=1.2),
+ "fit": g("fit", "tolerance", d=0.2), "explode": g("explode", d=0.0),
+ "standoff_height": standoff_h, "screw_diameter": g("screw_diameter", d=2.5)}
+ vents = p.get("vents", p.get("ventilation", p.get("vent")))
+ if vents is not None and _truthy(vents if not isinstance(vents, (int, float)) or isinstance(vents, bool) else vents != 0):
+ n = int(_num(vents, 0) or 0) if not isinstance(vents, bool) else 0
+ extra["vents"] = int(max(1, min(40, n if n > 1 else max(3, (W - 20) / 6))))
+ bosses = p.get("screw_bosses", p.get("bosses"))
+ extra["bosses"] = _truthy(bosses, bool(board and BOARDS[board]["holes"]))
+ extra["lid"] = _truthy(p.get("lid"), True)
+ return P, [W, D, H], extra
+
+ # ==================================================================
+ # features (holes, cut-outs, bosses, vents) as primitive lists
+ # ==================================================================
+ # feature dict: op cut|add, target base|lid|body, shape box|cyl, axis x|y|z,
+ # size [x,y,z] (box) or d,h (cyl), c numeric centre, cs scad expressions
+ def _face(self, v, k, P, bbox, side, u, w_along, zc, depth_override=None):
+ """Compute centre + oriented box size for a feature on a face.
+
+ u: offset along the face's horizontal tangent (x for front/back/top, y for left/right),
+ zc: height of the centre (side faces) or y offset (top/bottom faces).
+ Returns (target, axis, centre numbers, centre scad expressions, normal depth).
+ """
+ bx, by, bz = bbox
+ enc = k == "enclosure"
+ wall = P.get("wall", 2.0)
+ if side in ("left", "right"):
+ s = -1 if side == "left" else 1
+ if enc:
+ cx, cxs = s * (bx / 2 - wall / 2), f"{'-' if s < 0 else ''}({v}_width/2 - {v}_wall/2)"
+ depth = wall + 2
+ else:
+ cx, cxs = 0.0, "0"
+ depth = bx + 2
+ return "base" if enc else "body", "x", [cx, u, zc], [cxs, _n(u), _n(zc)], depth
+ if side in ("front", "back"):
+ s = -1 if side == "front" else 1
+ if enc:
+ cy, cys = s * (by / 2 - wall / 2), f"{'-' if s < 0 else ''}({v}_depth/2 - {v}_wall/2)"
+ depth = wall + 2
+ else:
+ cy, cys = 0.0, "0"
+ depth = by + 2
+ return "base" if enc else "body", "y", [u, cy, zc], [_n(u), cys, _n(zc)], depth
+ # top / bottom
+ if enc:
+ if side == "top":
+ return "lid", "z", [u, zc, bz - wall / 2], [_n(u), _n(zc), f"{v}_height - {v}_wall/2"], wall + 2
+ return "base", "z", [u, zc, wall / 2], [_n(u), _n(zc), f"{v}_wall/2"], wall + 2
+ return "body", "z", [u, zc, bz / 2], [_n(u), _n(zc), _n(bz / 2)], bz + 2
+
+ def _features(self, ctx: BuildContext, e: Entity, k: str, P: dict, bbox: list, extra: dict) -> tuple[list, list]:
+ """Return (features, union_children)."""
+ v = self._vid(e)
+ feats: list[dict] = []
+ unions: list[Entity] = []
+ bx, by, bz = bbox
+ enc = k == "enclosure"
+ wall = P.get("wall", 2.0)
+ base_h = (bz - wall if extra.get("lid", True) else bz) if enc else bz
+ mid_z = (wall + base_h) / 2 if enc else bz / 2
+
+ def add_round(target, axis, c, cs, d, depth, label, op="cut"):
+ feats.append(dict(op=op, target=target, shape="cyl", axis=axis, d=d, h=depth, c=c, cs=cs, label=label))
+
+ def add_rect(target, axis, c, cs, w, h, depth, label, op="cut"):
+ if axis == "x":
+ size = [depth, w, h]
+ elif axis == "y":
+ size = [w, depth, h]
+ else:
+ size = [w, h, depth]
+ feats.append(dict(op=op, target=target, shape="box", axis=axis, size=size, c=c, cs=cs, label=label))
+
+ # ---- board: bosses + connector cut-outs
+ board = extra.get("board")
+ if enc and board:
+ bd = BOARDS[board]
+ ox, oy = -bd["l"] / 2, -bd["w"] / 2
+ pcb_top = wall + P["standoff_height"] + 1.6
+ if extra.get("bosses"):
+ for (hx, hy) in bd["holes"]:
+ x, y = ox + hx, oy + hy
+ h = P["standoff_height"]
+ od = max(5.0, bd["hole_d"] * 2.2)
+ add_round("base", "z", [x, y, wall + h / 2 - 0.01], [_n(x), _n(y), f"{v}_wall + {_n(h / 2 - 0.01)}"],
+ od, h + 0.02, f"{bd['title']} mounting boss", op="add")
+ add_round("base", "z", [x, y, wall + h / 2 + 0.5], [_n(x), _n(y), f"{v}_wall + {_n(h / 2 + 0.5)}"],
+ P["screw_diameter"], h + 1.02, "boss pilot hole")
+ child_usb = any(self._is_cut(ch) and self._feature_key(ch) in ("usb", "usb_c")
+ and "position" not in ch.props
+ for ch in ctx.children(e) + self._foreign_features(ctx, e))
+ for pi, (label, side, off, w, h) in enumerate(bd["ports"]):
+ if pi == 0 and child_usb:
+ continue # the usb child feature below replaces the board's own usb cut-out
+ u = (oy + off) if side in ("left", "right") else (ox + off)
+ zc = pcb_top + h / 2 - 0.5
+ tgt, axis, c, cs, depth = self._face(v, k, P, bbox, side, u, w, zc)
+ add_rect(tgt, axis, c, cs, w + 1.0, h + 1.0, depth, f"{bd['title']} {label}")
+ elif enc and extra.get("bosses"):
+ # generic pcb bosses in the corners
+ inset = wall + 4.0
+ for sx in (-1, 1):
+ for sy in (-1, 1):
+ x, y = sx * (bx / 2 - inset), sy * (by / 2 - inset)
+ h = P["standoff_height"]
+ add_round("base", "z", [x, y, wall + h / 2 - 0.01], [_n(x), _n(y), f"{v}_wall + {_n(h / 2 - 0.01)}"],
+ 6.0, h + 0.02, "screw boss", op="add")
+ add_round("base", "z", [x, y, wall + h / 2 + 0.5], [_n(x), _n(y), f"{v}_wall + {_n(h / 2 + 0.5)}"],
+ P["screw_diameter"], h + 1.02, "boss pilot hole")
+ # ---- ventilation slots on the two long side walls
+ if enc and extra.get("vents"):
+ n = int(extra["vents"])
+ long_x = bx >= by
+ span = (bx if long_x else by) * 0.6
+ hh = max(3.0, (base_h - wall) * 0.4)
+ zc = wall + (base_h - wall) * 0.6
+ for side in (("front", "back") if long_x else ("left", "right")):
+ for i in range(n):
+ u = -span / 2 + (i + 0.5) * span / n
+ tgt, axis, c, cs, depth = self._face(v, k, P, bbox, side, u, 2.0, zc)
+ add_rect(tgt, axis, c, cs, 2.0, hh, depth, f"vent slot {side}")
+ # ---- children
+ cuts: list[tuple[Entity, dict, str]] = []
+ for ch in ctx.children(e) + self._foreign_features(ctx, e):
+ if self._is_cut(ch):
+ key = self._feature_key(ch) or "hole"
+ spec = dict(FEATURES.get(key, FEATURES["hole"]))
+ side = None
+ for sk in ("side", "face", "wall", "location"):
+ sv = ch.props.get(sk)
+ if isinstance(sv, str) and sv.strip().lower() in SIDE_WORDS:
+ side = SIDE_WORDS[sv.strip().lower()]
+ if side is None:
+ side = spec["side"] if enc else "top"
+ if enc and key == "usb" and board:
+ side = BOARDS[board]["ports"][0][1]
+ cuts.append((ch, spec, side))
+ else:
+ unions.append(ch)
+ # distribute features without explicit position along their face
+ by_side: dict[str, list] = {}
+ for item in cuts:
+ if "position" not in item[0].props:
+ by_side.setdefault(item[2], []).append(item)
+ auto_u: dict[str, float] = {}
+ for side, items in by_side.items():
+ length = (by if side in ("left", "right") else bx) * 0.6
+ for i, (ch, _s, _sd) in enumerate(items):
+ auto_u[ch.id] = -length / 2 + (i + 0.5) * length / len(items)
+ for ch, spec, side in cuts:
+ cp = ch.props
+ pos = _vec(cp.get("position"))
+ d = _num(cp.get("diameter"))
+ if d is None and _num(cp.get("radius")) is not None:
+ d = 2 * _num(cp.get("radius"))
+ if d is None:
+ d = _num(cp.get("hole_diameter"))
+ sz = _vec(cp.get("size"))
+ w = _num(cp.get("width"), sz[0] if sz else None)
+ h = _num(cp.get("height"), sz[1] if len(sz) > 1 else None)
+ shape = spec["shape"]
+ if d is not None and w is None:
+ shape = "round"
+ elif w is not None or h is not None:
+ shape = "rect" if shape != "slots" else "slots"
+ if side in ("left", "right"):
+ u = pos[1] if len(pos) > 1 else auto_u.get(ch.id, 0.0)
+ zc = pos[2] if len(pos) > 2 else mid_z
+ elif side in ("front", "back"):
+ u = pos[0] if pos else auto_u.get(ch.id, 0.0)
+ zc = pos[2] if len(pos) > 2 else mid_z
+ else:
+ u = pos[0] if pos else auto_u.get(ch.id, 0.0)
+ zc = pos[1] if len(pos) > 1 else 0.0
+ # usb without explicit height on a board enclosure: align with the board connector
+ if enc and board and self._feature_key(ch) in ("usb", "usb_c") and len(pos) < 3 and side in ("left", "right", "front", "back"):
+ bp = BOARDS[board]["ports"][0]
+ zc = wall + P["standoff_height"] + 1.6 + bp[4] / 2 - 0.5
+ if not pos:
+ u = (-BOARDS[board]["w"] / 2 + bp[2]) if side in ("left", "right") else (-BOARDS[board]["l"] / 2 + bp[2])
+ tgt, axis, c, cs, depth = self._face(v, k, P, bbox, side, u, w or 0, zc)
+ depth = _num(cp.get("depth"), depth)
+ label = f"{ch.name} ({ch.kind}, {side})"
+ if shape == "round":
+ add_round(tgt, axis, c, cs, d if d is not None else spec.get("d", 3.2), depth, label)
+ elif shape == "slots":
+ n = int(_num(cp.get("count", cp.get("slots")), 5))
+ n = max(1, min(60, n))
+ sw = w or 2.0
+ sh = h or max(3.0, (base_h - wall) * 0.4 if enc else bz * 0.5)
+ pitch = sw * 2.5
+ for i in range(n):
+ du = (i - (n - 1) / 2) * pitch
+ if axis == "x":
+ cc = [c[0], c[1] + du, c[2]]
+ ccs = [cs[0], _n(cc[1]), cs[2]]
+ else:
+ cc = [c[0] + du, c[1], c[2]]
+ ccs = [_n(cc[0]), cs[1], cs[2]]
+ add_rect(tgt, axis, cc, ccs, sw, sh, depth, f"{label} slot {i + 1}")
+ else:
+ add_rect(tgt, axis, c, cs, w or spec.get("w", 10.0), h or spec.get("h", 6.0), depth, label)
+ return feats, unions
+
+ # ==================================================================
+ # OpenSCAD generation
+ # ==================================================================
+ def _vid(self, e: Entity) -> str:
+ v = e.ident or ident(e.id) or "part"
+ # names that would clash with generated files (assembly.scad, the helper library, the bridge)
+ if v in ("assembly", "nlcl_cad_lib", "cad_bridge", "readme", "live_values"):
+ v += "_part"
+ return v
+
+ def _scad_vars(self, v: str, P: dict) -> list[str]:
+ L = []
+ for key, val in P.items():
+ if isinstance(val, bool):
+ L.append(f"{v}_{key} = {'true' if val else 'false'};")
+ elif isinstance(val, (int, float)):
+ L.append(f"{v}_{key} = {_n(val)};")
+ else:
+ L.append(f"{v}_{key} = {_scad_str(val)};")
+ return L
+
+ def _scad_prim(self, f: dict) -> str:
+ c = ", ".join(f["cs"])
+ if f["shape"] == "box":
+ return f"translate([{c}]) cube([{', '.join(_n(x) for x in f['size'])}], center=true); // {_comment(f['label'])}"
+ rot = {"x": "rotate([0, 90, 0]) ", "y": "rotate([90, 0, 0]) ", "z": ""}[f["axis"]]
+ return (f"translate([{c}]) {rot}cylinder(d={_n(f['d'])}, h={_n(f['h'])}, center=true);"
+ f" // {_comment(f['label'])}")
+
+ def _scad_body(self, v: str, k: str, P: dict) -> list[str]:
+ """Plain body of a non-enclosure part (no features)."""
+ if k in ("box", "cube"):
+ L = [f"nl_rbox([{v}_width, {v}_depth, {v}_height], {v}_fillet);"]
+ if "hole_diameter" in P:
+ L = ["difference() {", " " + L[0],
+ f" translate([0, 0, -1]) cylinder(d={v}_hole_diameter, h={v}_height + 2);", "}"]
+ return L
+ if k == "cylinder":
+ return ["difference() {", f" cylinder(d={v}_diameter, h={v}_height);",
+ f" if ({v}_hole_diameter > 0) translate([0, 0, -1]) cylinder(d={v}_hole_diameter, h={v}_height + 2);",
+ "}"]
+ if k == "sphere":
+ return [f"translate([0, 0, {v}_diameter / 2]) sphere(d={v}_diameter);"]
+ if k == "cone":
+ return [f"cylinder(d1={v}_diameter, d2={v}_top_diameter, h={v}_height);"]
+ if k == "plate":
+ return [f"nl_plate({v}_width, {v}_depth, {v}_thickness, {v}_corner_radius, {v}_hole_count, "
+ f"{v}_hole_diameter, {v}_hole_inset, {v}_countersink);"]
+ if k == "bracket":
+ return [f"nl_bracket({v}_length, {v}_width, {v}_height, {v}_thickness, {v}_hole_diameter, "
+ f"{v}_holes_per_leg, {v}_gusset);"]
+ if k in ("standoff", "spacer", "washer"):
+ return [f"nl_standoff({v}_diameter, {v}_height, {v}_hole_diameter, {v}_hex);"]
+ if k == "gear":
+ return [f"nl_gear({v}_teeth, {v}_module, {v}_thickness, {v}_bore);"]
+ if k == "tube":
+ return [f"nl_tube({v}_diameter, {v}_diameter - 2 * {v}_wall, {v}_length);"]
+ if k == "knob":
+ return [f"nl_knob({v}_diameter, {v}_height, {v}_shaft_diameter, {v}_d_shaft, {v}_ridges);"]
+ if k == "hinge":
+ return [f"nl_hinge({v}_width, {v}_leaf, {v}_thickness, {v}_knuckles, {v}_pin_diameter, "
+ f"{v}_clearance, {v}_hole_diameter);"]
+ if k == "mount":
+ return [f"nl_mount({v}_diameter, {v}_thickness, {v}_width, {v}_hole_diameter);"]
+ return [f"nl_rbox([{v}_width, {v}_depth, {v}_height], {v}_fillet);"]
+
+ def _notes(self, ctx: BuildContext, e: Entity) -> list[str]:
+ L = []
+ for b in e.behaviors or []:
+ try:
+ acts = "; ".join(describe_action(a) for a in b.get("do", []))
+ cond = f" if {b['if']}" if b.get("if") else ""
+ L.append(f"// note: behaviour on {b.get('on')}{cond} -> {_comment(acts)} "
+ f"(CAD geometry is static; behaviours are not simulated)")
+ except Exception:
+ L.append(f"// note: behaviour {_comment(b)} (ignored)")
+ for c in ctx.channels_for(e) if ctx else []:
+ d = c.direction(e)
+ L.append(f"// note: channel {c.id} ({c.protocol}) {'sends' if d == 'out' else 'receives'} "
+ f"{', '.join(c.fields)} {'to' if d == 'out' else 'from'} {c.peer(e).name} "
+ f"({c.peer(e).domain}) - see cad_bridge.py")
+ return L
+
+ def _start_offset(self, e: Entity) -> list[float]:
+ """Numeric 'move' actions in start behaviours shift the placement."""
+ off = [0.0, 0.0, 0.0]
+ for b in e.behaviors or []:
+ if not _is_start(b):
+ continue
+ for a in b.get("do", []):
+ if a.get("op") == "move":
+ vals = [_num(a.get(ax)) for ax in ("x", "y", "z")]
+ if all(x is not None and re.fullmatch(r"-?\d+(\.\d+)?", str(a.get(ax)).strip())
+ for x, ax in zip(vals, ("x", "y", "z"))):
+ off = [o + x for o, x in zip(off, vals)]
+ return off
+
+ def _placement(self, e: Entity, default=(0.0, 0.0, 0.0)) -> tuple[list[float], list[float]]:
+ pos = _pos(e, default)
+ off = self._start_offset(e)
+ return [a + b for a, b in zip(pos, off)], _rot(e)
+
+ def _scad_entity(self, ctx: BuildContext, e: Entity, color_fallback: str | None, info: dict, depth=0) -> list[str]:
+ """Parameters + modules for e and (recursively) its children."""
+ v = self._vid(e)
+ k = self._kind(e)
+ P, bbox, extra = self._params(ctx, e)
+ feats, unions = self._features(ctx, e, k, P, bbox, extra)
+ info[e.id] = dict(kind=k, P=P, bbox=bbox, extra=extra, feats=feats, unions=unions)
+ L = [f"// ---- {_comment(e.name)}: {k}" + (f" (from kind '{_comment(e.kind)}')" if ident(e.kind) != k else "")
+ + f" bbox {' x '.join(_n(x) for x in bbox)} mm"]
+ if ident(e.kind) not in KIND_MAP and not self._feature_key(e):
+ L.append(f"// note: kind '{_comment(e.kind)}' has no dedicated CAD template; using a parametric box")
+ if extra.get("board"):
+ bd = BOARDS[extra["board"]]
+ L.append(f"// sized for {bd['title']} ({_n(bd['l'])} x {_n(bd['w'])} mm pcb) + clearance; "
+ f"verify connector positions against your board")
+ L += self._notes(ctx, e)
+ L += self._scad_vars(v, P)
+ if k == "enclosure":
+ if extra.get("lid", True):
+ L.append(f"{v}_base_h = {v}_height - {v}_wall; // height of the base (lid sits on top)")
+ else:
+ L.append(f"{v}_base_h = {v}_height; // open-top box (no lid)")
+ col = _color(e.props.get("color", e.props.get("colour")), color_fallback)
+ L.append(f"{v}_color = {_scad_str(col) if col else 'undef'};")
+ L.append("")
+ # children modules first
+ child_lines = []
+ for ch in unions:
+ child_lines += self._scad_entity(ctx, ch, None, info, depth + 1)
+ L += child_lines
+
+ def child_calls(target_floor):
+ out = []
+ for ch in unions:
+ cpos, crot = self._placement(ch, (0.0, 0.0, target_floor))
+ out.append(f"translate([{', '.join(_n(x) for x in cpos)}]) rotate([{', '.join(_n(x) for x in crot)}]) "
+ f"{self._vid(ch)}_part(); // child {_comment(ch.name)}")
+ return out
+
+ def wrap(target, body):
+ adds = [self._scad_prim(f) for f in feats if f["target"] == target and f["op"] == "add"]
+ cuts = [self._scad_prim(f) for f in feats if f["target"] == target and f["op"] == "cut"]
+ extra_adds = child_calls(P.get("wall", 0) if k == "enclosure" else bbox[2]) if target in ("base", "body") else []
+ if not adds and not cuts and not extra_adds:
+ return body
+ out = ["difference() {", " union() {"]
+ out += [" " + x for x in body + adds + extra_adds]
+ out += [" }"]
+ out += [" " + x for x in cuts]
+ out += ["}"]
+ return out
+
+ if k == "enclosure":
+ shell = [
+ "difference() {",
+ f" nl_rbox([{v}_width, {v}_depth, {v}_base_h], {v}_fillet);",
+ f" translate([0, 0, {v}_wall]) nl_rbox([{v}_width - 2 * {v}_wall, {v}_depth - 2 * {v}_wall, {v}_base_h], "
+ f"max({v}_fillet - {v}_wall, 0));",
+ "}",
+ ]
+ lid = [
+ f"translate([0, 0, {v}_base_h]) nl_rbox([{v}_width, {v}_depth, {v}_wall], {v}_fillet);",
+ "// lip that keys into the base (friction fit)",
+ f"translate([0, 0, {v}_base_h - {v}_lip_height]) difference() {{",
+ f" nl_rbox([{v}_width - 2 * ({v}_wall + {v}_fit), {v}_depth - 2 * ({v}_wall + {v}_fit), {v}_lip_height + 0.01], "
+ f"max({v}_fillet - {v}_wall, 0));",
+ f" translate([0, 0, -1]) nl_rbox([{v}_width - 2 * ({v}_wall + {v}_fit + {v}_lip_thickness), "
+ f"{v}_depth - 2 * ({v}_wall + {v}_fit + {v}_lip_thickness), {v}_lip_height + 2], 0);",
+ "}",
+ ]
+ L.append(f"// base: open box, floor = wall")
+ L.append(f"module {v}_base() {{")
+ L.append(f" $fn = {v}_fn;")
+ L += [" " + x for x in wrap("base", shell)]
+ L.append("}")
+ L.append("")
+ L.append(f"// lid (in assembled position)")
+ L.append(f"module {v}_lid() {{")
+ L.append(f" $fn = {v}_fn;")
+ L += [" " + x for x in wrap("lid", lid)]
+ L.append("}")
+ L.append("")
+ L.append(f"// assembled part (lid raised by {v}_explode for an exploded view)")
+ L.append(f"module {v}_part() {{")
+ L.append(f" nl_color({v}_color) {{")
+ L.append(f" {v}_base();")
+ if extra.get("lid", True):
+ L.append(f" translate([0, 0, {v}_explode]) {v}_lid();")
+ L.append(" }")
+ if extra.get("board"):
+ bd = BOARDS[extra["board"]]
+ L.append(f" // ghost of the {bd['title']} pcb (% = preview only, not exported)")
+ L.append(f" %translate([{_n(-bd['l'] / 2)}, {_n(-bd['w'] / 2)}, {v}_wall + {v}_standoff_height]) "
+ f"cube([{_n(bd['l'])}, {_n(bd['w'])}, 1.6]);")
+ L.append("}")
+ L.append("")
+ L.append("// print layout: base + lid flipped upside down next to it")
+ L.append(f"module {v}_print() {{")
+ L.append(f" {v}_base();")
+ if extra.get("lid", True):
+ L.append(f" translate([{v}_width + 10, 0, {v}_height]) rotate([180, 0, 0]) {v}_lid();")
+ L.append("}")
+ else:
+ body = self._scad_body(v, k, P)
+ L.append(f"module {v}_part() {{")
+ L.append(f" $fn = {v}_fn;")
+ L.append(f" nl_color({v}_color) {{")
+ L += [" " + x for x in wrap("body", body)]
+ L.append(" }")
+ L.append("}")
+ L.append("")
+ L.append(f"module {v}_print() {{ {v}_part(); }}")
+ L.append("")
+ return L
+
+ # ------------------------------------------------------------------ library
+ SCAD_LIB = r"""// NLCL CAD helper library (OpenSCAD 2019.05+). Units: mm.
+// All parts are centred on X/Y and sit on Z = 0.
+
+// colour wrapper that accepts undef (= default colour)
+module nl_color(c) { if (is_undef(c)) children(); else color(c) children(); }
+
+// box centred on X/Y, from z = 0 up, vertical edges rounded with radius r
+module nl_rbox(size, r = 0) {
+ rr = min(r, size[0] / 2 - 0.01, size[1] / 2 - 0.01);
+ if (rr <= 0.01) translate([-size[0] / 2, -size[1] / 2, 0]) cube(size);
+ else hull() for (x = [-1, 1], y = [-1, 1])
+ translate([x * (size[0] / 2 - rr), y * (size[1] / 2 - rr), 0]) cylinder(r = rr, h = size[2]);
+}
+
+// point on the perimeter of an a x b rectangle at arc length s (starts at the -x,-y corner)
+function nl_perim_at(a, b, s) =
+ s < a ? [-a / 2 + s, -b / 2] :
+ s < a + b ? [a / 2, -b / 2 + (s - a)] :
+ s < 2 * a + b ? [a / 2 - (s - a - b), b / 2] :
+ [-a / 2, b / 2 - (s - 2 * a - b)];
+
+// n hole centres for a w x d plate, inset from the edges
+function nl_hole_pts(w, d, n, inset) =
+ let(a = max(w - 2 * inset, 0), b = max(d - 2 * inset, 0))
+ n <= 0 ? [] :
+ n == 1 ? [[0, 0]] :
+ n == 2 ? [[-a / 2, 0], [a / 2, 0]] :
+ n == 3 ? [[-a / 2, -b / 2], [a / 2, -b / 2], [0, b / 2]] :
+ n == 4 ? [for (x = [-1, 1], y = [-1, 1]) [x * a / 2, y * b / 2]] :
+ [for (i = [0 : n - 1]) nl_perim_at(a, b, i * 2 * (a + b) / n)];
+
+// flat plate with rounded corners and a hole pattern
+module nl_plate(w, d, t, r, n, hd, inset, countersink = false) {
+ difference() {
+ nl_rbox([w, d, t], r);
+ for (p = nl_hole_pts(w, d, n, inset)) translate([p[0], p[1], 0]) {
+ translate([0, 0, -1]) cylinder(d = hd, h = t + 2);
+ if (countersink) translate([0, 0, t - hd / 2]) cylinder(d1 = hd, d2 = 2 * hd, h = hd / 2 + 0.01);
+ }
+ }
+}
+
+// L-bracket: horizontal leg along +x (length a), vertical leg up +z (height b), width w along y
+module nl_bracket(a, w, b, t, hd, n, gusset = true) {
+ difference() {
+ union() {
+ translate([0, -w / 2, 0]) cube([a, w, t]);
+ translate([0, -w / 2, 0]) cube([t, w, b]);
+ if (gusset) for (s = [-1, 1])
+ translate([t, s * (w / 2 - t / 2), t]) rotate([90, 0, 0])
+ linear_extrude(height = t, center = true)
+ polygon([[0, 0], [max(min(a, b) * 0.5 - t, 1), 0], [0, max(min(a, b) * 0.5 - t, 1)]]);
+ }
+ if (n > 0) for (i = [0 : n - 1]) {
+ translate([t + (a - t) * (i + 0.5) / n, 0, -1]) cylinder(d = hd, h = t + 2);
+ translate([-1, 0, t + (b - t) * (i + 0.5) / n]) rotate([0, 90, 0]) cylinder(d = hd, h = t + 2);
+ }
+ }
+}
+
+// round or hexagonal standoff / spacer / washer with a centre hole
+module nl_standoff(od, h, hd, hex = false) {
+ difference() {
+ if (hex) cylinder(d = od, h = h, $fn = 6); else cylinder(d = od, h = h);
+ if (hd > 0) translate([0, 0, -1]) cylinder(d = hd, h = h + 2);
+ }
+}
+
+module nl_tube(od, id, h) {
+ difference() {
+ cylinder(d = od, h = h);
+ if (id > 0) translate([0, 0, -1]) cylinder(d = id, h = h + 2);
+ }
+}
+
+// spur gear, trapezoid approximation of an involute tooth (6 points per tooth)
+// mod = module (pitch diameter / teeth); pressure angle ~20 deg
+module nl_gear(teeth, mod, thickness, bore) {
+ z = max(6, round(teeth));
+ rp = mod * z / 2; // pitch radius
+ ra = rp + mod; // addendum (tip) radius
+ rf = max(rp - 1.25 * mod, bore / 2 + 0.5 * mod); // dedendum (root) radius
+ h = 90 / z; // quarter of the angular pitch (deg)
+ prof = [[rf, -1.25], [rp, -1.0], [ra, -0.55], [ra, 0.55], [rp, 1.0], [rf, 1.25]];
+ pts = [for (i = [0 : z - 1], j = [0 : 5])
+ let(a = i * 360 / z + prof[j][1] * h) [prof[j][0] * cos(a), prof[j][0] * sin(a)]];
+ difference() {
+ linear_extrude(height = thickness) polygon(pts);
+ if (bore > 0) translate([0, 0, -1]) cylinder(d = bore, h = thickness + 2);
+ }
+}
+
+// knurled knob with a (D-)shaft hole from below and a pointer groove on top
+module nl_knob(d, h, sd, dshaft = true, ridges = 18) {
+ difference() {
+ cylinder(d = d, h = h);
+ if (ridges > 0) for (i = [0 : ridges - 1])
+ rotate([0, 0, i * 360 / ridges]) translate([d / 2, 0, -1]) cylinder(d = d * 0.08, h = h + 2, $fn = 12);
+ translate([0, 0, -1]) intersection() {
+ cylinder(d = sd + 0.2, h = h - 2 + 1);
+ if (dshaft) translate([-sd, -sd, -1]) cube([2 * sd, sd + sd * 0.25, h + 2]);
+ else translate([-sd, -sd, -1]) cube([2 * sd, 2 * sd, h + 2]);
+ }
+ translate([0, d / 4, h]) cube([1.2, d / 2 - 1, 1.6], center = true);
+ }
+}
+
+// print-in-place hinge (two leaves, alternating knuckles, pin attached to leaf A)
+module nl_hinge(w, leaf, t, n, pin, clr, hd) {
+ kd = pin + 2 * clr + 3.2; // knuckle diameter
+ seg = (w - (n - 1) * clr) / n; // knuckle length
+ // leaf A (-y side) + its knuckles + pin
+ difference() {
+ union() {
+ translate([-w / 2, -(kd / 2 + leaf), 0]) cube([w, leaf - clr, t]);
+ for (i = [0 : 2 : n - 1]) translate([-w / 2 + i * (seg + clr), 0, 0]) {
+ translate([0, -(kd / 2 + clr), 0]) cube([seg, kd / 2 + clr, t]);
+ translate([0, 0, kd / 2]) rotate([0, 90, 0]) cylinder(d = kd, h = seg);
+ }
+ translate([-w / 2, 0, kd / 2]) rotate([0, 90, 0]) cylinder(d = pin, h = w);
+ }
+ for (s = [-1, 1]) translate([s * w / 4, -(kd / 2 + leaf / 2), -1]) cylinder(d = hd, h = t + 2);
+ }
+ // leaf B (+y side) + its knuckles, bored for the pin
+ difference() {
+ union() {
+ translate([-w / 2, kd / 2 + clr, 0]) cube([w, leaf - clr, t]);
+ if (n > 1) for (i = [1 : 2 : n - 1]) translate([-w / 2 + i * (seg + clr), 0, 0]) {
+ cube([seg, kd / 2 + clr + 0.01, t]);
+ translate([0, 0, kd / 2]) rotate([0, 90, 0]) cylinder(d = kd, h = seg);
+ }
+ }
+ translate([-w / 2 - 1, 0, kd / 2]) rotate([0, 90, 0]) cylinder(d = pin + 2 * clr, h = w + 2);
+ for (s = [-1, 1]) translate([s * w / 4, kd / 2 + leaf / 2, -1]) cylinder(d = hd, h = t + 2);
+ }
+}
+
+// snap-in cradle / pipe clip for a round item of diameter D, screwed down with two holes
+module nl_mount(D, t, w, hd) {
+ L = D + 2 * t + 6 * hd;
+ difference() {
+ union() {
+ translate([-w / 2, -L / 2, 0]) cube([w, L, t]);
+ translate([0, 0, t + D / 2]) rotate([0, 90, 0]) cylinder(d = D + 2 * t, h = w, center = true);
+ }
+ translate([0, 0, t + D / 2]) rotate([0, 90, 0]) cylinder(d = D, h = w + 2, center = true);
+ translate([0, 0, t + 0.8 * D + D / 2]) cube([w + 2, 0.8 * D, D], center = true); // snap opening
+ for (s = [-1, 1]) translate([0, s * (L / 2 - 1.5 * hd), -1]) cylinder(d = hd, h = t + 2);
+ }
+}
+"""
+
+ def _scad_file(self, ctx: BuildContext, root: Entity, color_fallback: str | None, info: dict) -> str:
+ v = self._vid(root)
+ L = [f"// {_comment(root.name)} - generated by NLCL (cad module). Units: mm. Edit the parameters below.",
+ f"// Render: F6 in OpenSCAD, export STL with F7, or: openscad -o {v}.stl {v}.scad",
+ f"// Override: openscad -D \"{v}_=\" -o {v}.stl {v}.scad",
+ "include ", ""]
+ L += self._scad_entity(ctx, root, color_fallback, info)
+ L += ["// what is rendered when this file is opened directly (print layout)", f"{v}_print();", ""]
+ return "\n".join(L)
+
+ def _assembly(self, ctx: BuildContext, roots: list[Entity], info: dict) -> str:
+ L = [f"// {ctx.system.name} - CAD assembly generated by NLCL. Units: mm.",
+ "// Each part file is 'use'd (modules only) and placed at its position / rotation.",
+ "// Export everything as one STL: openscad -o assembly.stl assembly.scad", ""]
+ for r in roots:
+ L.append(f"use <{self._vid(r)}.scad>")
+ L.append("")
+ if not roots:
+ L.append("// (no CAD parts yet)")
+ L.append("cube(0.01);")
+ # the first part without an explicit position stays at the origin (others are usually placed
+ # relative to it); further unplaced parts are laid out in a row along +X so they do not overlap
+ auto = {}
+ unplaced = [r for r in roots if "position" not in r.props]
+ extents = [self._placement(r)[0][0] + info.get(r.id, {}).get("bbox", [0])[0] / 2
+ for r in roots if "position" in r.props]
+ if unplaced:
+ extents.append(info.get(unplaced[0].id, {}).get("bbox", [20.0])[0] / 2)
+ cursor = (max(extents) if extents else 0.0) + 10
+ for r in unplaced[1:]:
+ w = info.get(r.id, {}).get("bbox", [20.0])[0]
+ auto[r.id] = cursor + w / 2
+ cursor += w + 10
+ placed: dict = {}
+ stacked = {r.id for r in roots if r.props.get("on") and "position" not in r.props}
+ for r in roots:
+ if r.id in stacked:
+ auto.pop(r.id, None)
+ order = [r for r in roots if r.id not in stacked] + [r for r in roots if r.id in stacked]
+ for r in order:
+ pos, rot = self._placement(r)
+ if r.id in auto:
+ pos[0] += auto[r.id]
+ tgt = r.props.get("on") if r.id in stacked else None
+ if tgt in placed and tgt != r.id:
+ tpos = placed[tgt]
+ pos = [tpos[0] + pos[0], tpos[1] + pos[1],
+ tpos[2] + info.get(tgt, {}).get("bbox", [0, 0, 0])[2] + pos[2]]
+ placed[r.id] = pos
+ i = info.get(r.id, {})
+ L.append(f"// {_comment(r.name)}: {i.get('kind', r.kind)}, bbox {' x '.join(_n(x) for x in i.get('bbox', []))} mm")
+ L.append(f"translate([{', '.join(_n(x) for x in pos)}]) rotate([{', '.join(_n(x) for x in rot)}]) "
+ f"{self._vid(r)}_part();")
+ L.append("")
+ return "\n".join(L)
+
+ # ==================================================================
+ # CadQuery generation
+ # ==================================================================
+ CQ_HEAD = '''"""{title} - CadQuery model generated by NLCL. Units: mm.
+
+Free alternative to the OpenSCAD file. Requires CadQuery: pip install cadquery
+ python {fname} -> writes STL + STEP next to this script
+Open it in CQ-editor to view it interactively (show_object is used there).
+"""
+import math
+import os
+
+import cadquery as cq
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+
+def rbox(w, d, h, r=0.0):
+ """Box centred on X/Y from z=0 up, vertical edges rounded."""
+ b = cq.Workplane("XY").box(w, d, h, centered=(True, True, False))
+ r = min(r, w / 2 - 0.01, d / 2 - 0.01)
+ if r > 0.05:
+ b = b.edges("|Z").fillet(r)
+ return b
+
+
+def cyl(d, h, center=(0, 0, 0), axis="z", base=False):
+ """Cylinder of diameter d, length h along axis, centred on center (or starting at z=0 if base)."""
+ plane = {"x": "YZ", "y": "XZ", "z": "XY"}[axis]
+ if base:
+ return cq.Workplane(plane).circle(d / 2).extrude(h).translate(center)
+ return cq.Workplane(plane).circle(d / 2).extrude(h / 2, both=True).translate(center)
+
+
+def boxc(size, center):
+ return cq.Workplane("XY").box(*size).translate(center)
+
+
+def tube(od, id_, h):
+ t = cyl(od, h, base=True)
+ if id_ > 0:
+ t = t.cut(cyl(id_, h + 2, center=(0, 0, -1), base=True))
+ return t
+
+
+def perim_at(a, b, s):
+ if s < a:
+ return (-a / 2 + s, -b / 2)
+ if s < a + b:
+ return (a / 2, -b / 2 + (s - a))
+ if s < 2 * a + b:
+ return (a / 2 - (s - a - b), b / 2)
+ return (-a / 2, b / 2 - (s - 2 * a - b))
+
+
+def hole_pts(w, d, n, inset):
+ a, b = max(w - 2 * inset, 0), max(d - 2 * inset, 0)
+ if n <= 0:
+ return []
+ if n == 1:
+ return [(0, 0)]
+ if n == 2:
+ return [(-a / 2, 0), (a / 2, 0)]
+ if n == 3:
+ return [(-a / 2, -b / 2), (a / 2, -b / 2), (0, b / 2)]
+ if n == 4:
+ return [(x * a / 2, y * b / 2) for x in (-1, 1) for y in (-1, 1)]
+ return [perim_at(a, b, i * 2 * (a + b) / n) for i in range(n)]
+
+
+def gear(teeth, mod, thickness, bore):
+ z = max(6, int(round(teeth)))
+ rp = mod * z / 2
+ ra = rp + mod
+ rf = max(rp - 1.25 * mod, bore / 2 + 0.5 * mod)
+ h = math.radians(90 / z)
+ prof = [(rf, -1.25), (rp, -1.0), (ra, -0.55), (ra, 0.55), (rp, 1.0), (rf, 1.25)]
+ pts = []
+ for i in range(z):
+ for r, k in prof:
+ a = i * 2 * math.pi / z + k * h
+ pts.append((r * math.cos(a), r * math.sin(a)))
+ g = cq.Workplane("XY").polyline(pts).close().extrude(thickness)
+ if bore > 0:
+ g = g.cut(cyl(bore, thickness + 2, center=(0, 0, -1), base=True))
+ return g
+
+
+def place(wp, pos=(0, 0, 0), rot=(0, 0, 0)):
+ """Rotate (x, y, z order, degrees) then translate, like OpenSCAD translate() rotate()."""
+ for axis, ang in zip(((1, 0, 0), (0, 1, 0), (0, 0, 1)), rot):
+ if ang:
+ wp = wp.rotate((0, 0, 0), axis, ang)
+ return wp.translate(tuple(pos))
+
+'''
+
+ def _cq_feat(self, f: dict) -> str:
+ c = "(" + ", ".join(_n(x) for x in f["c"]) + ")"
+ if f["shape"] == "box":
+ return f"boxc(({', '.join(_n(x) for x in f['size'])}), {c})"
+ return f"cyl({_n(f['d'])}, {_n(f['h'])}, center={c}, axis={f['axis']!r})"
+
+ def _cq_entity(self, ctx: BuildContext, e: Entity, info: dict) -> list[str]:
+ """def build_() -> dict[name, Workplane]; children first."""
+ v = self._vid(e)
+ i = info.get(e.id)
+ if i is None:
+ return []
+ k, P, bbox, extra, feats, unions = i["kind"], i["P"], i["bbox"], i["extra"], i["feats"], i["unions"]
+ L = []
+ for ch in unions:
+ L += self._cq_entity(ctx, ch, info)
+ L.append(f"P_{v} = {P!r}")
+ L.append("")
+ L.append("")
+ L.append(f"def build_{v}():")
+ L.append(f' """{_comment(e.name).replace(chr(92), "/").replace(chr(34), chr(39))}: {k}. Returns {{name: solid}}."""')
+ L.append(f" P = P_{v}")
+ approx = False
+ if k in ("box", "cube"):
+ L.append(' body = rbox(P["width"], P["depth"], P["height"], P["fillet"])')
+ if "hole_diameter" in P:
+ L.append(' body = body.cut(cyl(P["hole_diameter"], P["height"] + 2, center=(0, 0, -1), base=True))')
+ elif k == "cylinder":
+ L.append(' body = cyl(P["diameter"], P["height"], base=True)')
+ L.append(' if P["hole_diameter"] > 0:')
+ L.append(' body = body.cut(cyl(P["hole_diameter"], P["height"] + 2, center=(0, 0, -1), base=True))')
+ elif k == "sphere":
+ L.append(' body = cq.Workplane("XY").sphere(P["diameter"] / 2).translate((0, 0, P["diameter"] / 2))')
+ elif k == "cone":
+ L.append(' body = cq.Workplane("XY").add(cq.Solid.makeCone(P["diameter"] / 2, max(P["top_diameter"], 0) / 2, P["height"]))')
+ elif k == "plate":
+ L += [' body = rbox(P["width"], P["depth"], P["thickness"], P["corner_radius"])',
+ ' for (x, y) in hole_pts(P["width"], P["depth"], P["hole_count"], P["hole_inset"]):',
+ ' body = body.cut(cyl(P["hole_diameter"], P["thickness"] + 2, center=(x, y, -1), base=True))']
+ elif k in ("standoff", "spacer", "washer"):
+ L += [' if P["hex"]:',
+ ' body = cq.Workplane("XY").polygon(6, P["diameter"]).extrude(P["height"])',
+ ' else:',
+ ' body = cyl(P["diameter"], P["height"], base=True)',
+ ' if P["hole_diameter"] > 0:',
+ ' body = body.cut(cyl(P["hole_diameter"], P["height"] + 2, center=(0, 0, -1), base=True))']
+ elif k == "tube":
+ L.append(' body = tube(P["diameter"], P["diameter"] - 2 * P["wall"], P["length"])')
+ elif k == "gear":
+ L.append(' body = gear(P["teeth"], P["module"], P["thickness"], P["bore"])')
+ elif k == "bracket":
+ L += [' a, w, b, t, n = P["length"], P["width"], P["height"], P["thickness"], P["holes_per_leg"]',
+ ' body = boxc((a, w, t), (a / 2, 0, t / 2)).union(boxc((t, w, b), (t / 2, 0, b / 2)))',
+ ' for i in range(n):',
+ ' body = body.cut(cyl(P["hole_diameter"], t + 2, center=(t + (a - t) * (i + 0.5) / n, 0, t / 2)))',
+ ' body = body.cut(cyl(P["hole_diameter"], t + 2, center=(t / 2, 0, t + (b - t) * (i + 0.5) / n), axis="x"))']
+ elif k == "enclosure":
+ L += [' W, D, H, wall, r = P["width"], P["depth"], P["height"], P["wall"], P["fillet"]',
+ ' base_h = H - wall' + ('' if extra.get("lid", True) else ' * 0 # open-top box (no lid)'),
+ ' base = rbox(W, D, base_h, r).cut(rbox(W - 2 * wall, D - 2 * wall, base_h, max(r - wall, 0)).translate((0, 0, wall)))',
+ ' lw, ld = W - 2 * (wall + P["fit"]), D - 2 * (wall + P["fit"])',
+ ' lip = rbox(lw, ld, P["lip_height"], max(r - wall, 0)).cut(',
+ ' rbox(lw - 2 * P["lip_thickness"], ld - 2 * P["lip_thickness"], P["lip_height"] + 2).translate((0, 0, -1)))',
+ ' lid = rbox(W, D, wall, r).translate((0, 0, base_h)).union(lip.translate((0, 0, base_h - P["lip_height"])))']
+ else:
+ approx = True
+ bx, by, bz = bbox
+ L.append(f" # NOTE: '{k}' has no CadQuery template yet - bounding-box stand-in; use {v}.scad for the real shape")
+ L.append(f" body = rbox({_n(bx)}, {_n(by)}, {_n(bz)})")
+ # features
+ for target in (("base", "lid") if k == "enclosure" else ("body",)):
+ var = target
+ for f in feats:
+ if f["target"] != target:
+ continue
+ L.append(f" {var} = {var}.{'union' if f['op'] == 'add' else 'cut'}({self._cq_feat(f)}) # {_comment(f['label'])}")
+ # union children
+ floor = P.get("wall", 0) if k == "enclosure" else bbox[2]
+ tgt = "base" if k == "enclosure" else "body"
+ for ch in unions:
+ cpos, crot = self._placement(ch, (0.0, 0.0, floor))
+ L.append(f" for _s in build_{self._vid(ch)}().values(): # child {_comment(ch.name)}")
+ L.append(f" {tgt} = {tgt}.union(place(_s, ({', '.join(_n(x) for x in cpos)}), "
+ f"({', '.join(_n(x) for x in crot)})))")
+ if k == "enclosure":
+ if extra.get("lid", True):
+ L.append(f" return {{{(v + '_base')!r}: base, {(v + '_lid')!r}: lid}}")
+ else:
+ L.append(f" return {{{(v + '_base')!r}: base}}")
+ else:
+ L.append(f" return {{{v!r}: body}}")
+ L.append("")
+ L.append("")
+ if approx:
+ info[e.id]["cq_approx"] = True
+ return L
+
+ def _cq_file(self, ctx: BuildContext, root: Entity, info: dict) -> str:
+ v = self._vid(root)
+ L = [self.CQ_HEAD.replace("{title}", _comment(root.name)).replace("{fname}", f"{v}_cadquery.py")]
+ L += self._cq_entity(ctx, root, info)
+ L += [
+ f"result = build_{v}()",
+ "",
+ 'if "show_object" in globals(): # CQ-editor',
+ " for _name, _shape in result.items():",
+ " show_object(_shape, name=_name) # noqa: F821",
+ 'elif __name__ == "__main__":',
+ " for _name, _shape in result.items():",
+ ' cq.exporters.export(_shape, os.path.join(HERE, _name + ".stl"))',
+ ' cq.exporters.export(_shape, os.path.join(HERE, _name + ".step"))',
+ ' print("wrote", _name + ".stl", "and", _name + ".step")',
+ "",
+ ]
+ return "\n".join(L)
+
+ # ==================================================================
+ # channel bridge
+ # ==================================================================
+ @staticmethod
+ def _bridge_rules(ent: Entity, peer: Entity, fields: list) -> list[dict]:
+ """'when target changes / when dial receives a message, set height to target' on a CAD part:
+ rules the bridge applies to incoming messages (field -> geometry parameter)."""
+ rules = []
+ pnames = {str(peer.name).lower(), peer.ident, str(peer.id).lower()}
+ for b in ent.behaviors or []:
+ if not isinstance(b, dict):
+ continue
+ on = str(b.get("on") or "")
+ kind, _, arg = on.partition(":")
+ arg = arg.lower()
+ if kind == "message" and arg not in ("", "any", "*") and arg not in pnames and ident(arg) not in pnames:
+ continue
+ if kind == "change" and arg not in fields:
+ continue
+ if kind not in ("message", "change"):
+ continue
+ for a in b.get("do") or []:
+ if isinstance(a, dict) and a.get("op") == "set" and a.get("prop") and a.get("value") is not None:
+ expr = str(a["value"])
+ for pn in pnames: # 'ctl.target' -> 'target'
+ expr = re.sub(rf"\b{re.escape(pn)}\.", "", expr, flags=re.I)
+ rules.append({"on": on, "if": b.get("if"), "param": str(a["prop"]), "expr": expr})
+ return rules
+
+ def _bridge(self, ctx: BuildContext, info: dict) -> str | None:
+ local = {e.id: e for e in ctx.entities}
+ chans = []
+ for c in ctx.channels:
+ if c.protocol in ("spi", "i2c", "gpio", "wire"):
+ continue
+ for ent, direction in ((c.src, "out"), (c.dst, "in")):
+ if ent.id not in local:
+ continue
+ root = ent
+ seen = set()
+ while root.parent in local and root.id not in seen:
+ seen.add(root.id)
+ root = local[root.parent]
+ cfg = dict(c.config)
+ ch = {"id": c.id, "protocol": c.protocol, "direction": direction,
+ "entity": self._vid(ent), "file": self._vid(root), "from": c.src.name,
+ "peer": c.peer(ent).name, "peer_domain": c.peer(ent).domain,
+ "fields": list(c.fields), "config": cfg}
+ if direction == "in":
+ ch["rules"] = self._bridge_rules(local.get(ent.id, ent), c.peer(ent), list(c.fields))
+ pp = c.peer(ent).props or {}
+ ch["samples"] = {f: pp[f] for f in c.fields
+ if isinstance(pp.get(f), (int, float, bool))} # peer's values for --simulate
+ chans.append(ch)
+ if not chans:
+ return None
+ params = {}
+ for e in ctx.entities:
+ i = info.get(e.id)
+ if i:
+ params[self._vid(e)] = {k: v for k, v in i["P"].items()}
+ for k, val in e.props.items():
+ if isinstance(val, (int, float)) and not isinstance(val, bool) and k not in params[self._vid(e)]:
+ params[self._vid(e)].setdefault("_" + k, val)
+ # Python literals (not JSON: booleans must be True/False in the generated script)
+ return BRIDGE_TEMPLATE.replace("__CHANNELS__", pprint.pformat(chans, indent=1, width=110, sort_dicts=False)) \
+ .replace("__PARAMS__", pprint.pformat(params, indent=1, width=110, sort_dicts=False)) \
+ .replace("__SYSTEM__", repr(ctx.system.name))
+
+ # ==================================================================
+ # README
+ # ==================================================================
+ def _readme(self, ctx: BuildContext, roots: list[Entity], info: dict, has_bridge: bool) -> str:
+ L = [f"# {ctx.system.name} - CAD parts", "",
+ "Generated by NLCL. Units are **millimetres**; every part is centred on X/Y and sits on Z = 0.", "",
+ "## Parts", "", "| part | type | bounding box (mm) | files |", "|---|---|---|---|"]
+ for r in roots:
+ i = info.get(r.id, {})
+ v = self._vid(r)
+ files = f"`{v}.scad`, `{v}_cadquery.py`"
+ L.append(f"| {r.name} | {i.get('kind', r.kind)} | {' x '.join(_n(x) for x in i.get('bbox', []))} | {files} |")
+ L += [""]
+ for r in roots:
+ i = info.get(r.id, {})
+ ex = i.get("extra", {})
+ details = []
+ if ex.get("board"):
+ bd = BOARDS[ex["board"]]
+ details.append(f"sized for the {bd['title']} ({_n(bd['l'])} x {_n(bd['w'])} mm) with "
+ f"{'mounting bosses and ' if ex.get('bosses') and bd['holes'] else ''}"
+ f"connector cut-outs ({', '.join(p[0] for p in bd['ports'])}) - check them against "
+ "your exact board revision before printing")
+ if ex.get("vents"):
+ details.append(f"{ex['vents']} ventilation slots per long side")
+ feats = [f["label"] for f in i.get("feats", []) if f["op"] == "cut" and "slot" not in f["label"]
+ and "pilot" not in f["label"]]
+ if feats:
+ details.append("cut-outs: " + "; ".join(feats))
+ if i.get("unions"):
+ details.append("attached: " + ", ".join(c.name for c in i["unions"]))
+ if i.get("cq_approx"):
+ details.append("CadQuery file is a bounding-box stand-in for this type (use the .scad file)")
+ if details:
+ L.append(f"- **{r.name}**: " + "; ".join(details))
+ L += ["", "## Open / render with free tools", "",
+ "1. Install **OpenSCAD** (https://openscad.org, free).",
+ "2. Open `assembly.scad` to see everything placed together, or a single `.scad` for its print layout",
+ " (enclosures show base + flipped lid side by side). F5 preview, F6 render, F7 export STL.",
+ "3. Command line:", "",
+ "```sh",
+ "openscad -o assembly.stl assembly.scad"]
+ for r in roots:
+ v = self._vid(r)
+ L.append(f"openscad -o {v}.stl {v}.scad")
+ if roots:
+ v = self._vid(roots[0])
+ L.append(f'openscad -D "{v}_fn=128" -o {v}_fine.stl {v}.scad # override any _')
+ L += ["```", "",
+ "Every parameter is a top-level variable `_` at the top of the part file "
+ "(e.g. `case_wall`, `case_fillet`). Edit it, or use the OpenSCAD Customizer.", "",
+ "### CadQuery (Python, free)", "", "```sh", "pip install cadquery"]
+ for r in roots:
+ L.append(f"python {self._vid(r)}_cadquery.py # writes STL + STEP")
+ L += ["```", "",
+ "STEP files open in **FreeCAD** (free) for further editing / drawings.", "",
+ "## Printing", "",
+ "Slice the STL with **PrusaSlicer**, **Cura** or **OrcaSlicer** (all free). Typical settings: PLA or PETG, "
+ "0.2 mm layers, 3 perimeters, 20 % infill. Print enclosure lids top-face down (the print layout already "
+ "flips them). Holes are modelled at nominal size + clearance (M3 clearance 3.2-3.4 mm, M3 tap 2.5-2.7 mm).", ""]
+ if has_bridge:
+ L += ["## Live link to other modules", "",
+ "`cad_bridge.py` (Python stdlib) connects these parts to the NLCL channels:", "",
+ "- **incoming** channels write `_live.scad` (includes the part and overrides the matching "
+ "`_` parameters) and `live_values.json`; with `--export` and OpenSCAD on PATH it "
+ "re-exports `_live.stl` after every change;",
+ "- **outgoing** channels publish the part's parameters (e.g. dimensions) every `interval_ms`.", "",
+ "```sh",
+ "python ../python/main.py # starts the NLCL hub on :8765 (HTTP channels)",
+ "python cad_bridge.py # real transports",
+ "python cad_bridge.py --simulate --seconds 5 # offline demo",
+ "```", "",
+ "| channel | protocol | direction | part | fields |", "|---|---|---|---|---|"]
+ for c in ctx.channels:
+ for ent in (c.src, c.dst):
+ if ent.id in {x.id for x in ctx.entities}:
+ L.append(f"| {c.id} | {c.protocol} | {'out' if ent.id == c.src.id else 'in'} "
+ f"({c.peer(ent).name}, {c.peer(ent).domain}) | {ent.name} | {', '.join(c.fields)} |")
+ L.append("")
+ notes = []
+ for e in ctx.entities:
+ for b in e.behaviors or []:
+ notes.append(f"- {e.name}: on `{b.get('on')}` -> " + "; ".join(describe_action(a) for a in b.get("do", [])))
+ if notes:
+ L += ["## Behaviours (not simulated)", "",
+ "CAD output is static geometry. These behaviours are kept as `// note:` comments in the .scad files "
+ "(numeric `move` actions on start shift the placement):", ""] + notes + [""]
+ return "\n".join(L)
+
+ # ==================================================================
+ # entry points
+ # ==================================================================
+ @staticmethod
+ def _normalized(ctx: BuildContext) -> BuildContext:
+ """Copy of ctx whose entities have tidy props ('vents_true': True -> 'vents': True)."""
+ ents = []
+ for e in ctx.entities:
+ props = {}
+ for k, val in dict(e.props or {}).items():
+ k = str(k)
+ m = re.fullmatch(r"(\w+?)_(true|yes|on|false|no|off)", k)
+ m2 = re.fullmatch(r"(side|face|location|shape|color|colour|board|material|quality)_(\w+)", k)
+ m3 = re.fullmatch(r"(?:on_|at_)?(?:the_)?(\w+?)(?:_(?:side|face|wall|panel|end))?", k)
+ if m2 and val is True and m2.group(1) not in e.props:
+ props[m2.group(1)] = m2.group(2) # 'side_front': True -> side 'front'
+ elif (m3 and val is True and m3.group(1) in SIDE_WORDS and m3.group(1) not in ("lid", "base")
+ and not any(s in e.props for s in ("side", "face", "location"))):
+ props["side"] = SIDE_WORDS[m3.group(1)] # 'front_side' / 'on_top': True -> side
+ props[k] = val
+ elif m and isinstance(val, bool) and m.group(1) not in e.props:
+ props[m.group(1)] = m.group(2) in ("true", "yes", "on")
+ else:
+ props[k] = val
+ # aliases the user may type ("6 holes", "outer diameter 12"): an explicit alias wins over the
+ # kind's default that the core filled in at creation
+ dflt = CadModule.kinds.get(str(e.kind or "object").lower(), {})
+ for alias, canon in PROP_ALIASES.items():
+ av = props.get(alias)
+ if not isinstance(av, (int, float)) or isinstance(av, bool) or av <= 0:
+ continue
+ if canon in ("hole_count", "teeth") and float(av) != int(av):
+ continue # "4 holes of 3.2 mm" may leave holes: 3.2 - a size, not a count
+ if canon == "hole_diameter" and ident(e.kind) in ("tube", "pipe"):
+ continue # tubes use inner_diameter directly
+ if canon not in props or (canon in dflt and props[canon] == dflt[canon]):
+ props[canon] = int(av) if canon in ("hole_count", "teeth", "knuckles") else av
+ # board named by a flag key ('arduino_uno': True from "for an arduino uno")
+ if "board" not in props:
+ for k, val in (e.props or {}).items():
+ nk = re.sub(r"[^a-z0-9]", "", str(k).lower())
+ if val is True and any(frag in nk for frag, _bk in BOARD_MATCH):
+ props["board"] = str(k)
+ break
+ # "put peg on the base" (core: 'put_on_base': True) -> stack on that part in the assembly
+ if "on" not in props:
+ names = {}
+ for o in ctx.entities:
+ if o.id != e.id:
+ names[ident(str(o.name))] = o.id
+ names[o.ident] = o.id
+ for k, val in (e.props or {}).items():
+ m4 = re.fullmatch(r"(?:put_|place_|sit_|sits_|stack_|stacked_|mount_|mounted_|set_)?"
+ r"(?:on|onto|atop|above)(?:_top_of)?_(?:the_|a_)?(\w+)", str(k))
+ if m4 and val is True and m4.group(1) in names:
+ props["on"] = names[m4.group(1)]
+ break
+ # "when started, set wall to 3": literal start-up values are the initial geometry
+ for b in e.behaviors or []:
+ if not isinstance(b, dict) or not _is_start(b):
+ continue
+ for a in b.get("do") or []:
+ if not isinstance(a, dict) or a.get("op") != "set" or not a.get("prop"):
+ continue
+ val = a.get("value")
+ if isinstance(val, str) and re.fullmatch(r"\s*-?\d+(\.\d+)?\s*", val):
+ val = float(val) if "." in val else int(val)
+ if isinstance(val, (bool, int, float, list)) or (
+ isinstance(val, str) and str(a["prop"]) in ("color", "colour", "board", "side")):
+ props[str(a["prop"])] = val
+ ents.append(Entity(id=e.id, name=e.name or e.id, domain=e.domain, kind=e.kind or "object",
+ props=props, behaviors=list(e.behaviors or []), parent=e.parent))
+ return BuildContext(ctx.system, ctx.domain, ents, ctx.channels, ctx.outdir, ctx.project, ctx.llm)
+
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
+ ctx = self._normalized(ctx)
+ files: dict[str, str] = {"nlcl_cad_lib.scad": self.SCAD_LIB}
+ info: dict = {}
+ roots = ctx.roots()
+ for idx, r in enumerate(roots):
+ fallback = PALETTE[idx % len(PALETTE)]
+ v = self._vid(r)
+ try:
+ files[f"{v}.scad"] = self._scad_file(ctx, r, fallback, info)
+ except Exception as ex: # never fail the whole build because of one odd part
+ files[f"{v}.scad"] = (f"// {_comment(r.name)}: generation failed ({_comment(ex)}); placeholder cube\n"
+ f"module {v}_part() {{ cube(10); }}\nmodule {v}_print() {{ {v}_part(); }}\n{v}_print();\n")
+ info[r.id] = dict(kind="box", P={}, bbox=[10, 10, 10], extra={}, feats=[], unions=[])
+ try:
+ files[f"{v}_cadquery.py"] = self._cq_file(ctx, r, info)
+ except Exception as ex:
+ files[f"{v}_cadquery.py"] = f"# {r.name}: CadQuery generation failed ({_comment(ex)})\n"
+ files["assembly.scad"] = self._assembly(ctx, roots, info)
+ bridge = None
+ try:
+ bridge = self._bridge(ctx, info)
+ except Exception:
+ bridge = None
+ if bridge:
+ files["cad_bridge.py"] = bridge
+ files["README.md"] = self._readme(ctx, roots, info, bool(bridge))
+ return files
+
+ def run(self, ctx: BuildContext) -> RunResult | None:
+ if not (ctx.outdir / "assembly.scad").exists():
+ return RunResult(False, "build first (assembly.scad missing)")
+ exe = self.which("openscad", "openscad.com", "openscad.exe")
+ if exe:
+ return self.sh([exe, "-o", "assembly.stl", "assembly.scad"], ctx.outdir, timeout=180)
+ # no OpenSCAD: static check of the generated .scad files (+ a short offline bridge run)
+ import sys
+ problems, parts = [], 0
+ for f in sorted(ctx.outdir.glob("*.scad")):
+ if f.name.endswith("_live.scad"):
+ continue
+ text = re.sub(r'"(?:\\.|[^"\\])*"', '""', f.read_text(encoding="utf-8"))
+ text = re.sub(r"//[^\n]*", "", text)
+ for o, c in ("()", "[]", "{}"):
+ if text.count(o) != text.count(c):
+ problems.append(f"{f.name}: unbalanced {o}{c} ({text.count(o)} vs {text.count(c)})")
+ parts += 1
+ lib = (ctx.outdir / "nlcl_cad_lib.scad")
+ defined = set(re.findall(r"\bmodule\s+(\w+)", lib.read_text(encoding="utf-8"))) if lib.exists() else set()
+ for f in ctx.outdir.glob("*.scad"):
+ defined |= set(re.findall(r"\bmodule\s+(\w+)", f.read_text(encoding="utf-8")))
+ for f in ctx.outdir.glob("*.scad"):
+ body = re.sub(r"//[^\n]*", "", f.read_text(encoding="utf-8"))
+ for m in set(re.findall(r"\b(nl_\w+|\w+_part|\w+_print)\s*\(", body)):
+ if m not in defined and not re.search(rf"\bfunction\s+{m}\b", body + (lib.read_text(encoding='utf-8') if lib.exists() else "")):
+ problems.append(f"{f.name}: module {m}() is not defined")
+ out = [f"OpenSCAD not found - static check of {parts} .scad file(s): "
+ + ("OK" if not problems else f"{len(problems)} problem(s)")] + problems
+ if (ctx.outdir / "cad_bridge.py").exists():
+ r = self.sh([sys.executable, "cad_bridge.py", "--simulate", "--seconds", "3"], ctx.outdir, timeout=20)
+ out += ["", "$ python cad_bridge.py --simulate --seconds 3", r.output]
+ if not r.ok:
+ problems.append("bridge failed")
+ out.append("Install OpenSCAD (openscad.org) to render STL: openscad -o assembly.stl assembly.scad")
+ return RunResult(not problems, "\n".join(out), "static check")
+
+
+# ----------------------------------------------------------------------------
+# cad_bridge.py template (stdlib only; pyserial / paho-mqtt if installed)
+# ----------------------------------------------------------------------------
+BRIDGE_TEMPLATE = r'''#!/usr/bin/env python3
+"""CAD <-> NLCL channel bridge for system __SYSTEM__ (generated by NLCL).
+
+Incoming channels: received fields override part parameters -> _live.scad
+ (+ live_values.json, and _live.stl with --export when OpenSCAD is on PATH).
+Outgoing channels: the part's parameters are published every interval_ms.
+
+Messages are flat JSON {"channel": id, "from": name, field: value, ...}.
+HTTP/websocket channels use the NLCL hub (python/main.py): POST/GET {hub_url}/channel/.
+
+ python cad_bridge.py # real transports
+ python cad_bridge.py --simulate # no network: fake incoming values
+ python cad_bridge.py --seconds 10 --export # stop after 10 s, re-export STL on change
+"""
+import argparse
+import json
+import os
+import random
+import shutil
+import socket
+import subprocess
+import sys
+import threading
+import time
+import urllib.request
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+CHANNELS = __CHANNELS__
+# current geometry parameters per part (names match _ in the .scad files)
+PARAMS = __PARAMS__
+
+values = {} # part -> {param: value} received over channels
+lock = threading.Lock()
+
+
+def scad_literal(v):
+ if isinstance(v, bool):
+ return "true" if v else "false"
+ if isinstance(v, (int, float)):
+ return repr(v)
+ if isinstance(v, (list, tuple)):
+ return "[" + ", ".join(scad_literal(x) for x in v) + "]"
+ return json.dumps(str(v))
+
+
+def write_live(ch, export):
+ part, fname = ch["entity"], ch["file"]
+ with lock:
+ vals = dict(values.get(part, {}))
+ lines = ["// live parameters received over NLCL channels - generated by cad_bridge.py",
+ "// " + time.strftime("%Y-%m-%d %H:%M:%S"),
+ "include <%s.scad>" % fname]
+ for k, v in vals.items():
+ if k in PARAMS.get(part, {}):
+ lines.append("%s_%s = %s; // from %s" % (part, k, scad_literal(v), ch["peer"]))
+ else:
+ lines.append("// %s = %r (not a geometry parameter of %s)" % (k, v, part))
+ path = os.path.join(HERE, fname + "_live.scad")
+ with open(path, "w", encoding="utf-8") as f:
+ f.write("\n".join(lines) + "\n")
+ with open(os.path.join(HERE, "live_values.json"), "w", encoding="utf-8") as f:
+ json.dump(values, f, indent=2)
+ print("[%s] %s <- %s" % (ch["id"], part, vals), flush=True)
+ exe = shutil.which("openscad")
+ if export and exe:
+ try:
+ subprocess.run([exe, "-o", fname + "_live.stl", fname + "_live.scad"], cwd=HERE,
+ timeout=180, capture_output=True)
+ print(" exported %s_live.stl" % fname, flush=True)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ print(" openscad failed: %s" % e, flush=True)
+
+
+def receive(ch, msg, export):
+ """Copy fields of an incoming message onto the part parameters."""
+ if not isinstance(msg, dict):
+ return
+ got = {k: v for k, v in msg.items() if k in ch["fields"] and not k.startswith("_")}
+ if not got:
+ return
+ # behaviours of the part ("when target changes, set height to target") map fields -> parameters
+ with lock:
+ env = dict(PARAMS.get(ch["entity"], {}))
+ env.update(values.get(ch["entity"], {}))
+ env.update(got)
+ for rule in ch.get("rules", []):
+ trig = rule.get("on", "")
+ if trig.startswith("change:") and trig[7:] not in got:
+ continue
+ try:
+ if rule.get("if") and not evaluate(rule["if"], env):
+ continue
+ got[rule["param"]] = env[rule["param"]] = evaluate(rule["expr"], env)
+ except Exception as e: # an expression the bridge cannot evaluate: report, keep going
+ print(" rule %s = %s skipped (%s)" % (rule["param"], rule["expr"], e), flush=True)
+ with lock:
+ values.setdefault(ch["entity"], {}).update(got)
+ write_live(ch, export)
+
+
+def evaluate(expr, env):
+ """Tiny safe evaluator for the C-like behaviour expressions (numbers, fields, + - * / %, compares)."""
+ import ast
+ import re as _re
+ s = str(expr).strip()
+ s = s.replace("&&", " and ").replace("||", " or ")
+ s = _re.sub(r"!(?!=)", " not ", s)
+ s = _re.sub(r"\btrue\b", "True", _re.sub(r"\bfalse\b", "False", s))
+ tree = ast.parse(s, mode="eval")
+ ops = {ast.Add: lambda a, b: a + b, ast.Sub: lambda a, b: a - b, ast.Mult: lambda a, b: a * b,
+ ast.Div: lambda a, b: a / b, ast.Mod: lambda a, b: a % b, ast.Pow: lambda a, b: a ** b,
+ ast.Lt: lambda a, b: a < b, ast.LtE: lambda a, b: a <= b, ast.Gt: lambda a, b: a > b,
+ ast.GtE: lambda a, b: a >= b, ast.Eq: lambda a, b: a == b, ast.NotEq: lambda a, b: a != b}
+
+ def ev(n):
+ if isinstance(n, ast.Expression):
+ return ev(n.body)
+ if isinstance(n, ast.Constant) and isinstance(n.value, (int, float, bool, str)):
+ return n.value
+ if isinstance(n, ast.Name):
+ if n.id in env:
+ return env[n.id]
+ raise NameError(n.id)
+ if isinstance(n, ast.Attribute): # peer.field -> field
+ return ev(ast.Name(id=n.attr))
+ if isinstance(n, ast.BinOp) and type(n.op) in ops:
+ return ops[type(n.op)](float(ev(n.left)), float(ev(n.right)))
+ if isinstance(n, ast.UnaryOp):
+ v = ev(n.operand)
+ return (not v) if isinstance(n.op, ast.Not) else (-float(v) if isinstance(n.op, ast.USub) else v)
+ if isinstance(n, ast.BoolOp):
+ vals = [ev(x) for x in n.values]
+ return all(vals) if isinstance(n.op, ast.And) else any(vals)
+ if isinstance(n, ast.Compare):
+ left = ev(n.left)
+ for op, c in zip(n.ops, n.comparators):
+ right = ev(c)
+ if type(op) not in ops or not ops[type(op)](float(left), float(right)):
+ return False
+ left = right
+ return True
+ raise ValueError("unsupported expression")
+ v = ev(tree)
+ if isinstance(v, float) and v.is_integer():
+ v = int(v)
+ return v
+
+
+def payload(ch):
+ p = dict(PARAMS.get(ch["entity"], {}))
+ with lock:
+ p.update(values.get(ch["entity"], {})) # parameters received over channels win
+ out = {"channel": ch["id"], "from": ch["from"]}
+ for f in ch["fields"]:
+ out[f] = p.get(f, p.get("_" + f, 0))
+ return out
+
+
+# ------------------------------------------------------------------ transports
+def http_loop(ch, args, stop):
+ url = ch["config"].get("hub_url", "http://localhost:8765").rstrip("/") + ch["config"].get("path", "/channel/" + ch["id"])
+ url = url.replace("//localhost:", "//127.0.0.1:") # avoids a ~2 s IPv6 fallback per request on Windows
+ period = max(0.2, ch["config"].get("interval_ms", 1000) / 1000.0)
+ seen = None
+ while not stop.is_set():
+ try:
+ if ch["direction"] == "out":
+ data = json.dumps(payload(ch)).encode()
+ urllib.request.urlopen(urllib.request.Request(url, data, {"Content-Type": "application/json"}), timeout=3).read()
+ print("[%s] -> hub %s" % (ch["id"], payload(ch)), flush=True)
+ else:
+ msg = json.loads(urllib.request.urlopen(url, timeout=3).read() or b"{}")
+ if msg and msg.get("_t") != seen:
+ seen = msg.get("_t")
+ receive(ch, msg, args.export)
+ except (OSError, ValueError) as e:
+ print("[%s] hub %s unreachable (%s) - start python/main.py" % (ch["id"], url, e), flush=True)
+ stop.wait(period)
+
+
+def mqtt_loop(ch, args, stop):
+ try:
+ import paho.mqtt.client as mqtt
+ except ImportError:
+ print("[%s] paho-mqtt not installed (pip install paho-mqtt)" % ch["id"], flush=True)
+ return
+ cfg = ch["config"]
+ topic = cfg.get("topic", "nlcl/" + ch["id"])
+ try:
+ client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) if hasattr(mqtt, "CallbackAPIVersion") else mqtt.Client()
+ client.on_message = lambda c, u, m: receive(ch, json.loads(m.payload.decode() or "{}"), args.export)
+ client.connect(cfg.get("broker", "broker.hivemq.com"), int(cfg.get("broker_port", 1883)), 30)
+ if ch["direction"] == "in":
+ client.subscribe(topic)
+ client.loop_start()
+ except (OSError, ValueError) as e:
+ print("[%s] mqtt broker unreachable: %s" % (ch["id"], e), flush=True)
+ return
+ period = max(0.2, cfg.get("interval_ms", 1000) / 1000.0)
+ while not stop.is_set():
+ if ch["direction"] == "out":
+ client.publish(topic, json.dumps(payload(ch)))
+ stop.wait(period)
+ client.loop_stop()
+
+
+def serial_loop(ch, args, stop):
+ try:
+ import serial
+ import serial.tools.list_ports
+ except ImportError:
+ print("[%s] pyserial not installed (pip install pyserial)" % ch["id"], flush=True)
+ return
+ cfg = ch["config"]
+ port = os.environ.get("NLCL_SERIAL_PORT") or (None if cfg.get("port", "auto") == "auto" else cfg.get("port"))
+ if not port:
+ ports = [p.device for p in serial.tools.list_ports.comports()]
+ port = ports[0] if ports else None
+ if not port:
+ print("[%s] no serial port found" % ch["id"], flush=True)
+ return
+ ser = serial.Serial(port, int(cfg.get("baud", 115200)), timeout=0.2)
+ period = max(0.2, cfg.get("interval_ms", 1000) / 1000.0)
+ nxt = 0.0
+ while not stop.is_set():
+ if ch["direction"] == "out" and time.monotonic() >= nxt:
+ nxt = time.monotonic() + period
+ ser.write((json.dumps(payload(ch)) + "\n").encode())
+ line = ser.readline().decode(errors="replace").strip()
+ if line.startswith("{") and ch["direction"] == "in":
+ try:
+ receive(ch, json.loads(line), args.export)
+ except ValueError:
+ pass
+
+
+def udp_loop(ch, args, stop):
+ port = int(ch["config"].get("port", 9876))
+ period = max(0.2, ch["config"].get("interval_ms", 1000) / 1000.0)
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ s.settimeout(0.5)
+ if ch["direction"] == "in":
+ s.bind(("0.0.0.0", port))
+ while not stop.is_set():
+ if ch["direction"] == "out":
+ s.sendto((json.dumps(payload(ch)) + "\n").encode(), ("127.0.0.1", port))
+ stop.wait(period)
+ else:
+ try:
+ data, _ = s.recvfrom(65536)
+ receive(ch, json.loads(data.decode() or "{}"), args.export)
+ except (socket.timeout, ValueError):
+ pass
+
+
+def simulate_loop(ch, args, stop):
+ """Offline demo: fake incoming values around the current parameters."""
+ period = max(0.2, ch["config"].get("interval_ms", 1000) / 1000.0)
+ p = PARAMS.get(ch["entity"], {})
+ while not stop.is_set():
+ if ch["direction"] == "in":
+ msg = {"channel": ch["id"], "from": ch["peer"]}
+ for f in ch["fields"]:
+ base = ch.get("samples", {}).get(f, p.get(f, p.get("_" + f, 10.0)))
+ if isinstance(base, bool):
+ msg[f] = random.random() < 0.5
+ elif isinstance(base, (int, float)):
+ base = base or 20.0 # a zero start value would never change
+ val = base * random.uniform(0.9, 1.1)
+ msg[f] = round(val, 2) if isinstance(base, float) or abs(base) < 20 else int(round(val))
+ else:
+ msg[f] = base
+ receive(ch, msg, args.export)
+ else:
+ print("[%s] (simulated) -> %s" % (ch["id"], payload(ch)), flush=True)
+ stop.wait(period)
+
+
+LOOPS = {"http": http_loop, "websocket": http_loop, "mqtt": mqtt_loop, "serial": serial_loop, "uart": serial_loop,
+ "udp": udp_loop}
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("--simulate", action="store_true", help="no network/hardware: fake incoming values")
+ ap.add_argument("--seconds", type=float, default=0, help="stop after N seconds (0 = until Ctrl+C)")
+ ap.add_argument("--export", action="store_true", help="re-export _live.stl with OpenSCAD on change")
+ args = ap.parse_args()
+ stop = threading.Event()
+ threads = []
+ for ch in CHANNELS:
+ fn = simulate_loop if args.simulate else LOOPS.get(ch["protocol"])
+ if fn is None:
+ print("[%s] protocol %s is not handled by the CAD bridge" % (ch["id"], ch["protocol"]), flush=True)
+ continue
+ t = threading.Thread(target=fn, args=(ch, args, stop), daemon=True)
+ t.start()
+ threads.append(t)
+ print("cad bridge: %d channel(s) (Ctrl+C to stop)" % len(threads), flush=True)
+ t0 = time.monotonic()
+ try:
+ while threads and (args.seconds <= 0 or time.monotonic() - t0 < args.seconds):
+ time.sleep(0.2)
+ except KeyboardInterrupt:
+ pass
+ stop.set()
+ print("cad bridge stopped", flush=True)
+
+
+if __name__ == "__main__":
+ main()
+'''
+
+MODULE = CadModule()
diff --git a/nlcl/modules/cpp_mod.py b/nlcl/modules/cpp_mod.py
new file mode 100644
index 0000000000000000000000000000000000000000..623f8be08a12a4ced8cadf317d3fefbfe538997f
--- /dev/null
+++ b/nlcl/modules/cpp_mod.py
@@ -0,0 +1,1262 @@
+"""C++ domain: native C++17 programs (simulations, controllers, services, agents).
+
+Output (relative to /cpp/):
+ include/nlcl_core.hpp runtime core: Value, flat JSON, Entity, World loop
+ include/.hpp one class per entity (props as typed fields)
+ src/.cpp behaviours as methods (onStart/onUpdate/timers/...)
+ src/main.cpp builds the World, wires channels, CLI (--seconds N ...)
+ src/nlcl_channels.hpp/.cpp transports: http hub, udp, serial-style JSON lines, mqtt
+ single/.cpp everything in one file (for online compilers)
+ CMakeLists.txt, build.sh, build.bat, README.md
+
+Only the C++ standard library and the OS socket API are used (Winsock2 on
+Windows, BSD sockets elsewhere), so any free C++17 compiler builds it.
+"""
+from __future__ import annotations
+
+import json
+import math
+import os
+import re
+from pathlib import Path
+
+from ..ir import Entity, describe_action, expr_names, expr_tokens, ident, validate_expr
+from .base import BuildContext, DomainModule, RunResult
+
+ASSETS = Path(__file__).parent / "_assets" / "cpp"
+
+_CPP_KEYWORDS = set("""
+alignas alignof and and_eq asm auto bitand bitor bool break case catch char char8_t char16_t char32_t class
+compl concept const consteval constexpr constinit const_cast continue co_await co_return co_yield decltype
+default delete do double dynamic_cast else enum explicit export extern false float for friend goto if inline
+int long mutable namespace new noexcept not not_eq nullptr operator or or_eq private protected public register
+reinterpret_cast requires return short signed sizeof static static_assert static_cast struct switch template
+this thread_local throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t
+while xor xor_eq final override import module
+""".split())
+# members of nlcl::Entity, hook parameter names and common lowercase macros
+_BASE_MEMBERS = {"name", "kind", "parent", "set_parent", "alive", "world", "props", "get", "set", "has",
+ "state", "state_json", "every", "destroy", "log", "send", "move", "timer", "nlcl", "std",
+ "dt", "prop", "sender", "msg", "other", "key", "args", "v", "main"}
+_MACROS = {"near", "far", "interface", "small", "hyper", "pascal", "cdecl", "major", "minor", "unix", "linux",
+ "errno", "assert", "stdin", "stdout", "stderr", "offsetof", "setjmp", "va_arg", "min", "max",
+ "environ", "i386", "noreturn"}
+_RESERVED = _CPP_KEYWORDS | _BASE_MEMBERS | _MACROS
+_RESERVED_FILES = {"main", "nlcl_channels", "nlcl_core"}
+
+_CTYPE = {"int": "int", "double": "double", "bool": "bool", "string": "std::string",
+ "vec": "std::vector"}
+
+
+# ---------------------------------------------------------------- literals
+def _fnum(x) -> str:
+ try:
+ f = float(x)
+ except (TypeError, ValueError):
+ return "0.0"
+ if not math.isfinite(f):
+ return "0.0"
+ r = repr(f)
+ return r if any(c in r for c in ".e") else r + ".0"
+
+
+def _cstr(s) -> str:
+ """C++ string literal (UTF-8 kept as-is, controls as 3-digit octal escapes)."""
+ out = ['"']
+ for ch in str(s):
+ if ch == "\\":
+ out.append("\\\\")
+ elif ch == '"':
+ out.append('\\"')
+ elif ch == "\n":
+ out.append("\\n")
+ elif ch == "\t":
+ out.append("\\t")
+ elif ord(ch) < 0x20 or ord(ch) == 0x7F:
+ out.append("\\%03o" % ord(ch))
+ elif ch == "?" and out[-1] == "?":
+ out.append("\\?") # never form a trigraph (pre-C++17 / -trigraphs compilers)
+ else:
+ out.append(ch)
+ out.append('"')
+ return "".join(out)
+
+
+def _cmt(s) -> str:
+ """Text safe inside a // comment."""
+ return re.sub(r"[\r\n\\]+", " ", str(s)).strip()
+
+
+def _typ(v) -> str:
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int" if -2 ** 31 < v < 2 ** 31 else "double"
+ if isinstance(v, float) or v is None:
+ return "double"
+ if isinstance(v, (list, tuple)):
+ return "vec" if all(isinstance(x, (int, float)) for x in v) else "string"
+ return "string"
+
+
+def _lit(v, typ: str) -> str:
+ if typ == "bool":
+ return "true" if (v if isinstance(v, bool) else bool(v)) else "false"
+ if typ == "int":
+ try:
+ return str(int(v))
+ except (TypeError, ValueError):
+ return "0"
+ if typ == "double":
+ return _fnum(v if isinstance(v, (int, float)) and not isinstance(v, bool) else
+ (float(v) if isinstance(v, bool) else 0.0))
+ if typ == "vec":
+ if not isinstance(v, (list, tuple)):
+ return "{}"
+ return "{" + ", ".join(_fnum(x) for x in v) + "}"
+ if isinstance(v, (list, tuple)):
+ v = ", ".join(str(x) for x in v)
+ elif isinstance(v, dict):
+ v = json.dumps(v, ensure_ascii=False)
+ elif v is None:
+ v = ""
+ return _cstr(v)
+
+
+def _value_lit(v) -> str:
+ """nlcl::Value(...) expression for a python value."""
+ t = _typ(v)
+ if t == "vec":
+ return f"nlcl::Value(std::vector{_lit(v, t)})"
+ return f"nlcl::Value({_lit(v, t)})"
+
+
+# ---------------------------------------------------------------- per-entity model
+class _Model:
+ """Resolved C++ view of one entity: typed fields, triggers, method names."""
+
+ def __init__(self, e: Entity, stem: str):
+ self.e = e
+ self.stem = stem
+ self.cls = e.class_name
+ self.props: dict[str, str] = {} # prop -> type key
+ self.init: dict[str, object] = {} # prop -> initial python value
+ self.fields: dict[str, str] = {} # prop -> C++ member name
+ self._used: set[str] = set()
+ self.calls: dict[str, str] = {} # call name -> C++ method name
+ self.edges: list[str] = [] # private bool members for edge-triggered rules
+ for k, v in (e.props or {}).items():
+ k = str(k)
+ if k.startswith("_") or not ident(k):
+ continue
+ self.add(k, _typ(v), v)
+
+ def add(self, prop: str, typ: str, value=None) -> None:
+ prop = str(prop)
+ if prop in self.props:
+ return
+ base = re.sub(r"_+", "_", ident(prop)) or "prop"
+ f = base + "_" if base in _RESERVED else base
+ n = 2
+ while f in self._used:
+ f = f"{base}_{n}"
+ n += 1
+ self._used.add(f)
+ self.props[prop] = typ
+ self.fields[prop] = f
+ if value is None:
+ value = {"int": 0, "double": 0.0, "bool": False, "string": "", "vec": [0.0, 0.0, 0.0]}[typ]
+ self.init[prop] = value
+
+ def call_name(self, name: str) -> str:
+ name = str(name)
+ if name not in self.calls:
+ base = re.sub(r"_+", "_", ident(name)) or "action"
+ m = base if base not in _RESERVED and base not in self._used else "do_" + base
+ while m in self._used:
+ m += "_"
+ self._used.add(m)
+ self.calls[name] = m
+ return self.calls[name]
+
+
+# ---------------------------------------------------------------- expressions
+class _ExprRenderer:
+ """Tiny recursive-descent translator from the NLCL expression language to C++.
+
+ Same precedence as C/C++. Every sub-expression carries a static kind
+ (num, bool, str, lit = string literal, vec) so that mixed operands are
+ converted explicitly: `/` is always true division, `%` is std::fmod,
+ `+` with a string concatenates (nlcl::cat), comparisons of different
+ kinds go through nlcl::Value and strings used as conditions through
+ nlcl::truthy. The generated code therefore always compiles.
+ """
+
+ def __init__(self, tokens, name_fn, kind_fn=None):
+ self.t = tokens
+ self.i = 0
+ self.name = name_fn
+ self.kind = kind_fn or (lambda n: "num")
+
+ def peek(self):
+ return self.t[self.i] if self.i < len(self.t) else (None, None)
+
+ def take(self):
+ tok = self.peek()
+ self.i += 1
+ return tok
+
+ def parse(self) -> tuple[str, str]:
+ out = self.binary(0)
+ if self.i != len(self.t):
+ raise ValueError("trailing tokens")
+ return out
+
+ LEVELS = [("||",), ("&&",), ("==", "!="), ("<", ">", "<=", ">="), ("+", "-"), ("*", "/", "%")]
+
+ @staticmethod
+ def num(x):
+ c, k = x
+ return c if k in ("num", "bool") else f"nlcl::num({c})"
+
+ @staticmethod
+ def cond(x):
+ c, k = x
+ return c if k in ("num", "bool") else f"nlcl::truthy({c})"
+
+ @staticmethod
+ def sobj(x):
+ c, k = x
+ return f"std::string({c})" if k == "lit" else c
+
+ def combine(self, left, op, right):
+ lk, rk = left[1], right[1]
+ strs = ("str", "lit")
+ if op in ("||", "&&"):
+ return f"{self.cond(left)} {op} {self.cond(right)}", "bool"
+ if op in ("==", "!="):
+ if lk in strs and rk in strs:
+ return f"{self.sobj(left)} {op} {right[0]}", "bool"
+ if (lk in ("num", "bool") and rk in ("num", "bool")) or (lk == rk == "vec"):
+ return f"{left[0]} {op} {right[0]}", "bool"
+ return f"nlcl::Value({left[0]}) {op} nlcl::Value({right[0]})", "bool"
+ if op in ("<", ">", "<=", ">="):
+ if lk in strs and rk in strs:
+ return f"{self.sobj(left)} {op} {right[0]}", "bool"
+ return f"{self.num(left)} {op} {self.num(right)}", "bool"
+ if op == "+" and (lk in strs or rk in strs):
+ return f"nlcl::cat({left[0]}, {right[0]})", "str"
+ if op == "%":
+ return f"std::fmod(static_cast({self.num(left)}), static_cast({self.num(right)}))", "num"
+ if op == "/": # NLCL division is true division, also for int operands
+ return f"{self.num(left)} / static_cast({self.num(right)})", "num"
+ return f"{self.num(left)} {op} {self.num(right)}", "num"
+
+ def binary(self, lvl: int):
+ if lvl == len(self.LEVELS):
+ return self.unary()
+ left = self.binary(lvl + 1)
+ while True:
+ k, v = self.peek()
+ if k != "op" or v not in self.LEVELS[lvl]:
+ return left
+ self.take()
+ right = self.binary(lvl + 1)
+ left = self.combine(left, v, right)
+
+ def unary(self):
+ k, v = self.peek()
+ if k == "op" and v in ("!", "-", "+"):
+ self.take()
+ inner = self.unary()
+ code = self.cond(inner) if v == "!" else self.num(inner)
+ code = f"{v}({code})" if code[:1] in "-+!" else f"{v}{code}"
+ return code, ("bool" if v == "!" else "num")
+ return self.primary()
+
+ def primary(self):
+ k, v = self.take()
+ if k == "num":
+ if "." in v:
+ return v, "num"
+ n = int(v)
+ return (str(n) if n < 2 ** 31 else f"{n}.0"), "num"
+ if k == "str":
+ return _cstr(v[1:-1]), "lit"
+ if k == "id":
+ if v in ("true", "false"):
+ return v, "bool"
+ return self.name(v), self.kind(v)
+ if k == "op" and v == "(":
+ inner = self.binary(0)
+ k2, v2 = self.take()
+ if v2 != ")":
+ raise ValueError("missing )")
+ return f"({inner[0]})", inner[1]
+ raise ValueError(f"unexpected token {v!r}")
+
+
+# rotation props (degrees): angle = about z, angle_x / angle_y = about x / y
+_ANGLES = ("angle", "angle_x", "angle_y", "angle_z")
+
+_KIND = {"int":"num", "double": "num", "bool": "bool", "string": "str", "vec": "vec"}
+
+
+def _trigger(b: dict) -> tuple[str, str]:
+ """('timer', '500') from {'on': 'timer:500'}; tolerant of junk."""
+ on = str(b.get("on") or "update").strip()
+ key, _, arg = on.partition(":")
+ return key.strip().lower() or "update", arg.strip()
+
+
+def _names(expr) -> list[str]:
+ try:
+ return expr_names(validate_expr(expr))
+ except ValueError:
+ return []
+
+
+# ---------------------------------------------------------------- module
+class CppModule(DomainModule):
+ name = "cpp"
+ title = "C++ (native C++17 programs: simulations, controllers, services, agents)"
+ aliases = ("c++", "native", "cplusplus", "cxx")
+ keywords = ("cmake", "g++", "clang", "msvc", "mingw", "compiled", "compiler", "executable", "stl",
+ "simulation", "simulator", "solver", "integrator", "kalman", "robot", "robotics", "vehicle",
+ "autopilot", "engine", "multithreaded", "algorithm", "numerical", "fft", "orderbook",
+ "matcher", "scheduler", "planner")
+ kinds = {
+ "object": {},
+ "class": {},
+ "service": {"running": True, "requests": 0},
+ "controller": {"setpoint": 0.0, "output": 0.0, "gain": 1.0},
+ "simulation": {"elapsed": 0.0, "steps": 0},
+ "engine": {"running": False, "rpm": 0.0},
+ "processor": {"processed": 0},
+ "filter": {"input": 0.0, "output": 0.0, "alpha": 0.5},
+ "calculator": {"result": 0.0},
+ "counter": {"count": 0},
+ "timer": {"elapsed": 0.0},
+ "robot": {"position": [0.0, 0.0, 0.0], "speed": 1.0, "battery": 100.0},
+ "vehicle": {"position": [0.0, 0.0, 0.0], "speed": 0.0, "fuel": 100.0},
+ "agent": {"position": [0.0, 0.0, 0.0], "energy": 100.0},
+ }
+ suggested_props = ("speed", "count", "threshold", "gain", "rate", "label")
+ protocols = ("http", "udp", "serial", "mqtt", "websocket")
+ toolchain = """Free C++17 toolchains (no third-party libraries needed):
+
+ cmake -S . -B build && cmake --build build # any compiler, CMake 3.10+
+ ./build/_app --simulate --seconds 5 # Windows: build\\Debug\\_app.exe
+
+ g++ -std=c++17 -O2 -Iinclude -Isrc src/*.cpp -o app -pthread # Linux/macOS (GCC or clang++)
+ g++ -std=c++17 -O2 -Iinclude -Isrc src/*.cpp -o app.exe -lws2_32 # Windows, MinGW-w64 (MSYS2/WinLibs)
+ cl /std:c++17 /EHsc /utf-8 /Iinclude /Isrc src\\*.cpp /Fe:app.exe ws2_32.lib # MSVC Build Tools
+
+Flags: --simulate (fake incoming data/key presses), --seconds N, --dt S, --fast, --quiet.
+`single/.cpp` is the whole program in one file for online compilers
+(Compiler Explorer godbolt.org, Wandbox, OnlineGDB) - run it with --simulate --seconds 3."""
+
+ # ------------------------------------------------------------------ helpers
+ @staticmethod
+ def _stem(e: Entity, used: set[str]) -> str:
+ s = re.sub(r"_+", "_", e.ident) or "entity"
+ if s in _RESERVED_FILES:
+ s += "_entity"
+ base, n = s, 2
+ while s in used:
+ s = f"{base}_{n}"
+ n += 1
+ used.add(s)
+ return s
+
+ @staticmethod
+ def _find(ctx: BuildContext, ref: str | None) -> Entity | None:
+ if not ref:
+ return None
+ r = ident(ref)
+ for e in ctx.system.entities.values():
+ if e.ident == r or e.name.lower() == str(ref).lower():
+ return e
+ return None
+
+ def _watch(self, ctx: BuildContext, e: Entity, arg: str) -> tuple[str | None, str]:
+ """'change:' -> (other entity ident or None for own, prop)."""
+ arg = str(arg).strip()
+ if "." not in arg:
+ return None, arg
+ head, _, prop = arg.partition(".")
+ head, prop = head.strip(), prop.strip()
+ if head in ("self", "this", "it") or ident(head) == e.ident:
+ return None, prop
+ return self._ref_name(ctx, head), prop
+
+ def _with_cond(self, ctx: BuildContext, b: dict) -> str | None:
+ """C++ test for a collision rule's "with" filter (entity ident or kind); None = any."""
+ w = b.get("with")
+ if w is None or not str(w).strip() or str(w).strip().lower() in ("any", "*", "anything"):
+ return None
+ w = str(w).strip()
+ names = {self._ref_name(ctx, w), ident(w) or w}
+ kinds = {w.lower(), (ident(w) or w).lower()}
+ parts = [f"other.name() == {_cstr(n)}" for n in sorted(names)]
+ parts += [f"other.kind() == {_cstr(k)}" for k in sorted(kinds)]
+ return " || ".join(parts)
+
+ def _ref_name(self, ctx: BuildContext, ref: str) -> str:
+ e = self._find(ctx, ref)
+ return e.ident if e else (ident(ref) or str(ref))
+
+ def _models(self, ctx: BuildContext) -> list[_Model]:
+ used: set[str] = set()
+ classes: set[str] = set()
+ models = []
+ for e in ctx.entities:
+ m = _Model(e, self._stem(e, used))
+ base = m.cls if re.match(r"[A-Za-z]\w*$", m.cls or "") else "Obj"
+ cls, n = base, 2
+ while cls in classes: # "my robot" and "my_robot" -> MyRobot, MyRobot2
+ cls = f"{base}{n}"
+ n += 1
+ classes.add(cls)
+ m.cls = cls
+ self._augment(ctx, m)
+ models.append(m)
+ return models
+
+ def _augment(self, ctx: BuildContext, m: _Model) -> None:
+ """Add fields that behaviours and channels need but the IR does not declare."""
+ e = m.e
+
+ def need_names(expr):
+ for n in _names(expr):
+ if "." not in n:
+ m.add(n, "double")
+ else:
+ head = n.split(".", 1)[0]
+ if head in ("self", "this", e.ident) and n.count(".") >= 1:
+ prop = n.split(".")[1]
+ m.add(prop, "double")
+
+ for b in e.behaviors or []:
+ if not isinstance(b, dict):
+ continue
+ key, arg = _trigger(b)
+ if key == "change" and arg:
+ ent, prop = self._watch(ctx, e, arg)
+ if ent is None and prop and ident(prop):
+ m.add(prop, "double")
+ if b.get("if"):
+ need_names(b["if"])
+ for a in b.get("do") or []:
+ if not isinstance(a, dict):
+ continue
+ op = a.get("op")
+ if op in ("set", "add", "toggle") and not (a.get("prop") and ident(str(a.get("prop")))):
+ continue
+ if op in ("set", "add", "toggle") and self._redirect(ctx, e, b, a.get("prop")):
+ need_names(a.get("value", 0)) if op != "toggle" else None
+ continue
+ if op == "move" and self._xy_move(e):
+ for ax in ("x", "y", "z"):
+ need_names(a.get(ax, 0))
+ continue
+ if op == "set":
+ v = a.get("value")
+ toks = []
+ try:
+ toks = expr_tokens(validate_expr(v))
+ except ValueError:
+ pass
+ if len(toks) == 1 and toks[0][0] == "str":
+ m.add(a["prop"], "string", toks[0][1][1:-1])
+ elif len(toks) == 1 and toks[0][1] in ("true", "false"):
+ m.add(a["prop"], "bool", False)
+ else:
+ m.add(a["prop"], "double")
+ need_names(v)
+ elif op == "add":
+ m.add(a["prop"], "double")
+ need_names(a.get("value", 1))
+ elif op == "toggle":
+ m.add(a["prop"], "bool", False)
+ elif op == "move":
+ m.add("position", "vec", [0.0, 0.0, 0.0])
+ for ax in ("x", "y", "z"):
+ need_names(a.get(ax, 0))
+ elif op == "call":
+ for x in a.get("args") or []:
+ need_names(x)
+ m.call_name(a.get("name") or "action")
+ # The interpreter registers props it first sees in a behaviour as int 0.
+ # If such a prop is only ever assigned booleans (or strings), type it so.
+ assigned: dict[str, set[str]] = {}
+ for b in e.behaviors or []:
+ for a in (b.get("do") or []) if isinstance(b, dict) else []:
+ if not isinstance(a, dict):
+ continue
+ op, prop = a.get("op"), a.get("prop")
+ if not prop:
+ continue
+ prop = str(prop)
+ kind = "num"
+ if op == "toggle":
+ kind = "bool"
+ elif op in ("set", "add"):
+ try:
+ toks = expr_tokens(validate_expr(a.get("value", 1)))
+ except ValueError:
+ toks = []
+ if op == "set" and len(toks) == 1 and toks[0][0] == "str":
+ kind = "string"
+ elif op == "set" and len(toks) == 1 and toks[0][1] in ("true", "false"):
+ kind = "bool"
+ elif not all(k == "num" and "." not in v or k == "op" and v in "+-*()" for k, v in toks):
+ kind = "real" # fractions, names, division...: keep it a double
+ assigned.setdefault(prop, set()).add(kind)
+ for prop, kinds in assigned.items():
+ orig = (e.props or {}).get(prop)
+ if prop in m.props and type(orig) is int and orig == 0:
+ if kinds == {"bool"}:
+ m.props[prop], m.init[prop] = "bool", False
+ elif kinds == {"string"}:
+ m.props[prop], m.init[prop] = "string", ""
+ elif ("real" in kinds or prop in _ANGLES) and m.props[prop] == "int":
+ m.props[prop], m.init[prop] = "double", 0.0
+ for prop in _ANGLES: # rotation in degrees: always a double, kept in [0, 360)
+ if m.props.get(prop) == "int":
+ m.props[prop], m.init[prop] = "double", float(m.init.get(prop) or 0)
+ for c in ctx.channels_for(e):
+ for f in c.fields or []:
+ f = str(f)
+ if not ident(f):
+ continue
+ if c.dst.id == e.id:
+ src_v = (c.src.props or {}).get(f)
+ t = _typ(src_v) if src_v is not None else "double"
+ if t == "int": # received data (sensor readings...) may carry fractions
+ t = "double"
+ m.add(f, t, src_v)
+ else:
+ m.add(f, "double")
+
+ def _redirect(self, ctx: BuildContext, e: Entity, b: dict, prop) -> str | None:
+ """'when balance of account < 0, set balance to 0' attached to another entity: the
+ property belongs to the (single, local) entity the condition is about, not to e."""
+ prop = str(prop or "")
+ if not prop or not b.get("if"):
+ return None
+ names = [n for n in _names(b["if"]) if "." in n]
+ own = (e.props or {}).get(prop, None) if prop in (e.props or {}) else None
+ if prop in (e.props or {}):
+ # the interpreter registers a behaviour's prop on the focused entity as int 0;
+ # only treat it as misplaced when the condition reads .
+ if not (type(own) is int and own == 0):
+ return None
+ heads = {n.split(".", 1)[0] for n in names if n.split(".", 1)[1] == prop}
+ else:
+ heads = {n.split(".", 1)[0] for n in names}
+ heads -= {"self", "this", "other", e.ident}
+ hits = []
+ for h in heads:
+ o = self._find(ctx, h)
+ if o is not None and o.id != e.id and prop in (o.props or {}) and any(x.id == o.id for x in ctx.entities):
+ hits.append(o.ident)
+ return hits[0] if len(hits) == 1 else None
+
+ @staticmethod
+ def _xy_move(e: Entity) -> bool:
+ """Entity keeps its location in separate numeric x / y (/ z) properties."""
+ p = e.props or {}
+ num = lambda v: isinstance(v, (int, float)) and not isinstance(v, bool)
+ return "position" not in p and num(p.get("x")) and num(p.get("y"))
+
+ def _namer(self, ctx: BuildContext, m: _Model, collision: bool = False):
+ local_idents = {x.ident for x in ctx.entities}
+
+ def comp(prop_parts: list[str]):
+ return {"x": 0, "y": 1, "z": 2, "r": 0, "g": 1, "b": 2}.get(prop_parts[0]) if prop_parts else None
+
+ kinds: dict[str, str] = {}
+
+ def g(n: str) -> tuple[str, str]:
+ parts = [p for p in n.split(".") if p]
+ if not parts:
+ return "0", "num"
+ if len(parts) == 1:
+ n = parts[0]
+ if n not in m.fields:
+ m.add(n, "double") # defensive: should already exist
+ return m.fields[n], _KIND[m.props[n]]
+ head, rest = parts[0], parts[1:]
+ # own property component: position.x
+ if head in m.fields and m.props[head] == "vec" and comp(rest) is not None:
+ return f"nlcl::at({m.fields[head]}, {comp(rest)})", "num"
+ if head in ("self", "this") or (head == m.e.ident and head not in m.fields):
+ return g(".".join(rest))
+ prop = rest[0]
+ idx = comp(rest[1:])
+ if collision and head == "other":
+ base = f"other.get({_cstr(prop)})"
+ return (f"nlcl::at({base}.asList(), {idx})", "num") if idx is not None else (f"{base}.asNum()", "num")
+ ent = self._find(ctx, head)
+ ename = ent.ident if ent else (ident(head) or head)
+ base = f"world().get({_cstr(ename)}, {_cstr(prop)})"
+ if idx is not None:
+ return f"nlcl::at({base}.asList(), {idx})", "num"
+ typ = _typ((ent.props or {}).get(prop)) if ent is not None and prop in (ent.props or {}) else "double"
+ if ent is not None and ent.ident in local_idents and prop not in (ent.props or {}):
+ typ = "double"
+ lm = (getattr(self, "_local_models", None) or {}).get(ename)
+ if lm is not None and prop in lm.props: # same program: use the generated C++ type
+ typ = lm.props[prop]
+ acc = {"string": "asStr()", "bool": "asBool()", "vec": "asList()"}.get(typ, "asNum()")
+ return f"{base}.{acc}", _KIND.get(typ, "num")
+
+ def f(n: str) -> str:
+ code, k = g(n)
+ kinds[n] = k
+ return code
+
+ f.kind = lambda n: kinds.get(n) or g(n)[1]
+ return f
+
+ def _texpr(self, expr, namer) -> tuple[str, str]:
+ """(C++ code, kind) for an NLCL expression; never raises."""
+ try:
+ toks = expr_tokens(validate_expr(expr))
+ return _ExprRenderer(toks, namer, getattr(namer, "kind", None)).parse()
+ except Exception:
+ return "0", "num"
+
+ def _cexpr(self, expr, namer) -> str:
+ return self._texpr(expr, namer)[0]
+
+ def _cond(self, expr, namer) -> str:
+ return _ExprRenderer.cond(self._texpr(expr, namer))
+
+ def _cnum(self, expr, namer) -> str:
+ return _ExprRenderer.num(self._texpr(expr, namer))
+
+ # ------------------------------------------------------------------ actions
+ def _action(self, ctx: BuildContext, m: _Model, a: dict, namer) -> list[str]:
+ op = a.get("op")
+ if op in ("set", "add", "toggle"):
+ prop = a.get("prop")
+ if not prop or not ident(str(prop)):
+ return [f"// {op}: no property given"]
+ prop = str(prop)
+ if prop not in m.fields:
+ m.add(prop, "bool" if op == "toggle" else "double")
+ fld, t = m.fields[prop], m.props[prop]
+ ctype = _CTYPE[t]
+ numeric = ("num", "bool")
+ if op == "set":
+ v = a.get("value", 0)
+ ex, k = self._texpr(v, namer)
+ if t in ("int", "double", "bool") and k in numeric:
+ return [f"{fld} = static_cast<{ctype}>({ex});"]
+ if t == "string" and k in ("str", "lit"):
+ return [f"{fld} = {ex};"]
+ return [f"nlcl::assign({fld}, nlcl::Value({ex}));"]
+ if op == "add":
+ v = a.get("value", 1)
+ x = self._texpr(v, namer)
+ if prop in _ANGLES and t == "double": # rotate: wrap degrees into [0, 360)
+ return [f"{fld} = std::fmod({fld} + ({_ExprRenderer.num(x)}), 360.0);",
+ f"if ({fld} < 0) {fld} += 360.0;"]
+ if t in ("int", "double", "bool"):
+ return [f"{fld} = static_cast<{ctype}>({fld} + ({_ExprRenderer.num(x)}));"]
+ if t == "string":
+ return [f"{fld} += nlcl::Value({x[0]}).asStr();"]
+ return [f"nlcl::addTo({fld}, static_cast({_ExprRenderer.num(x)}));"]
+ # toggle
+ if t == "bool":
+ return [f"{fld} = !{fld};"]
+ if t in ("int", "double"):
+ return [f"{fld} = static_cast<{ctype}>({fld} == 0 ? 1 : 0);"]
+ if t == "string":
+ return [f'{fld} = {fld}.empty() ? "on" : "";']
+ return [f"// toggle {prop}: not applicable to a vector"]
+ if op == "destroy":
+ return ["destroy();", "return;"]
+ if op == "log":
+ text = str(a.get("text", ""))
+ t = text.strip()
+ if t in m.props or ("." in t and self._find(ctx, t.split(".", 1)[0]) is not None
+ and re.match(r"^[A-Za-z_]\w*\.[A-Za-z_]\w*$", t)):
+ text = f"{t} = {{{t}}}" # "log temperature" -> print its value
+ return [f"log({_cstr(text)});"]
+ if op == "move":
+ xs = [self._cnum(a.get(ax, 0), namer) for ax in ("x", "y", "z")]
+ if self._xy_move(m.e):
+ out = []
+ for ax, v in zip(("x", "y", "z"), xs):
+ if ax in m.props and m.props[ax] in ("int", "double") and v not in ("0", "0.0"):
+ f = m.fields[ax]
+ out.append(f"{f} = static_cast<{_CTYPE[m.props[ax]]}>({f} + ({v}));")
+ return out or ["// move: no displacement"]
+ return [f"move({xs[0]}, {xs[1]}, {xs[2]});"]
+ if op == "send":
+ to = a.get("to")
+ to_s = _cstr(self._ref_name(ctx, to)) if to else '""'
+ fields = [str(x) for x in (a.get("fields") or [])]
+ if fields:
+ return [f"send({to_s}, {{{', '.join(_cstr(x) for x in fields)}}});"]
+ return [f"send({to_s});"]
+ if op == "call":
+ meth = m.call_name(a.get("name") or "action")
+ args = ", ".join(f"nlcl::Value({self._cexpr(x, namer)})" for x in a.get("args") or [])
+ return [f"{meth}({{{args}}});"]
+ try:
+ return [f"// {_cmt(describe_action(a))}"]
+ except Exception:
+ return ["// (unsupported action)"]
+
+ def _remote_action(self, ent: str, a: dict, namer) -> list[str]:
+ op, prop = a.get("op"), str(a.get("prop"))
+ head = f"if (nlcl::Entity* t = world().find({_cstr(ent)})) "
+ if op == "set":
+ return [head + f"t->set({_cstr(prop)}, nlcl::Value({self._cexpr(a.get('value', 0), namer)}));"]
+ if op == "add":
+ return [head + f"t->set({_cstr(prop)}, nlcl::Value(t->get({_cstr(prop)}).asNum() + "
+ f"({self._cnum(a.get('value', 1), namer)})));"]
+ return [head + f"t->set({_cstr(prop)}, nlcl::Value(!t->get({_cstr(prop)}).asBool()));"]
+
+ def _body(self, ctx, m, b, namer, indent=" ", edge: bool = False) -> list[str]:
+ out = [f"{indent}// {_cmt(self._describe(b))}"]
+ ind = indent
+ acts = [a for a in b.get("do") or [] if isinstance(a, dict)]
+ if b.get("if"):
+ cond = self._cond(b['if'], namer)
+ if edge and any(a.get("op") in ("log", "send", "call", "toggle", "add") for a in acts):
+ # fire once each time the condition becomes true (no flood at the loop rate)
+ flag = f"nlclWas{len(m.edges)}_"
+ m.edges.append(flag)
+ out += [f"{indent}const bool {flag}now = {cond};",
+ f"{indent}if ({flag}now && !{flag}) {{"]
+ tail = [f"{indent}}}", f"{indent}{flag} = {flag}now;"]
+ else:
+ out.append(f"{indent}if ({cond}) {{")
+ tail = [indent + "}"]
+ ind = indent + " "
+ for a in acts:
+ if a.get("op") in ("set", "add", "toggle"):
+ ent = self._redirect(ctx, m.e, b, a.get("prop"))
+ if ent:
+ out += [ind + ln for ln in self._remote_action(ent, a, namer)]
+ continue
+ out += [ind + ln for ln in self._action(ctx, m, a, namer)]
+ if b.get("if"):
+ out += tail
+ return out
+
+ @staticmethod
+ def _describe(b: dict) -> str:
+ try:
+ acts = "; ".join(describe_action(a) for a in b.get("do") or [])
+ except Exception:
+ acts = "..."
+ return f"on {b.get('on')}" + (f" if {b['if']}" if b.get("if") else "") + f": {acts}"
+
+ # ------------------------------------------------------------------ classes
+ def _class_files(self, ctx: BuildContext, m: _Model) -> tuple[str, str]:
+ e = m.e
+ groups: dict[str, list[dict]] = {}
+ timers: list[dict] = []
+ for b in e.behaviors or []:
+ if not isinstance(b, dict) or not isinstance(b.get("do"), list) or not b.get("do"):
+ continue
+ key, arg = _trigger(b)
+ if key not in ("start", "update", "timer", "change", "message", "collision", "input") \
+ or (key in ("change", "input") and not arg):
+ continue # unknown/incomplete trigger: nothing to hook it to
+ if key == "timer":
+ timers.append(b)
+ groups.setdefault(key, []).append(b)
+
+ namer = self._namer(ctx, m)
+ cnamer = self._namer(ctx, m, collision=True)
+ # ---- method bodies (generated first: they may register extra fields/calls)
+ bodies: list[tuple[str, str, list[str]]] = [] # (decl, definition head, lines)
+ cls = m.cls
+
+ if "start" in groups:
+ L = []
+ for b in groups["start"]:
+ L += self._body(ctx, m, b, namer)
+ bodies.append(("void onStart() override;", f"void {cls}::onStart() {{", L))
+
+ intrinsic = []
+ num = ("int", "double")
+ if e.kind in ("timer", "simulation") and m.props.get("elapsed") in num:
+ intrinsic.append(f" {m.fields['elapsed']} += static_cast<{_CTYPE[m.props['elapsed']]}>(dt); "
+ f"// {e.kind}: world time")
+ if e.kind == "simulation" and m.props.get("steps") in num:
+ intrinsic.append(f" {m.fields['steps']} += 1; // simulation: step counter")
+ if e.kind == "filter" and all(m.props.get(p) in num for p in ("input", "output", "alpha")):
+ fi, fo, fa = m.fields["input"], m.fields["output"], m.fields["alpha"]
+ intrinsic.append(f" {fo} = static_cast<{_CTYPE[m.props['output']]}>({fo} + {fa} * ({fi} - {fo}));"
+ f" // filter: exponential smoothing")
+ if "update" in groups or intrinsic:
+ L = [" (void)dt;"] + intrinsic
+ for b in groups.get("update", []):
+ L += self._body(ctx, m, b, namer, edge=True)
+ bodies.append(("void onUpdate(double dt) override;", f"void {cls}::onUpdate(double dt) {{", L))
+
+ timer_decls = []
+ for i, b in enumerate(timers):
+ try:
+ ms = max(1, int(round(float(_trigger(b)[1]))))
+ except (TypeError, ValueError, OverflowError):
+ ms = 1000
+ ms = min(ms, 2 ** 31 - 1)
+ L = self._body(ctx, m, b, namer)
+ bodies.append((f"void onTimer{i}(); // every {ms} ms", f"void {cls}::onTimer{i}() {{", L))
+ timer_decls.append((i, ms))
+
+ if "change" in groups:
+ L, W = [], [" (void)who;", " (void)prop;"]
+ for b in groups["change"]:
+ ent, prop = self._watch(ctx, e, _trigger(b)[1])
+ if ent is None:
+ L.append(f" if (prop == {_cstr(prop)}) {{")
+ L += self._body(ctx, m, b, namer, " ")
+ L.append(" }")
+ else: # another entity's property: change:.
+ W.append(f" if (who == {_cstr(ent)} && prop == {_cstr(prop)}) {{")
+ W += self._body(ctx, m, b, namer, " ")
+ W.append(" }")
+ if L:
+ bodies.append(("void onChange(const std::string& prop) override;",
+ f"void {cls}::onChange(const std::string& prop) {{", L))
+ if len(W) > 2:
+ bodies.append(("void onWatch(const std::string& who, const std::string& prop) override;",
+ f"void {cls}::onWatch(const std::string& who, const std::string& prop) {{", W))
+
+ if "message" in groups:
+ L = [" (void)sender;", " (void)msg;"]
+ for b in groups["message"]:
+ src = _trigger(b)[1]
+ if src in ("any", "", "*"):
+ L += self._body(ctx, m, b, namer)
+ else:
+ L.append(f" if (sender == {_cstr(self._ref_name(ctx, src) if self._find(ctx, src) else src)}) {{")
+ L += self._body(ctx, m, b, namer, " ")
+ L.append(" }")
+ bodies.append(("void onMessage(const std::string& sender, const nlcl::Fields& msg) override;",
+ f"void {cls}::onMessage(const std::string& sender, const nlcl::Fields& msg) {{", L))
+
+ if "collision" in groups:
+ L = [" (void)other;"]
+ for b in groups["collision"]:
+ wc = self._with_cond(ctx, b)
+ if wc is None:
+ L += self._body(ctx, m, b, cnamer)
+ else: # "with": only collisions with that entity / kind
+ L.append(f" if ({wc}) {{")
+ L += self._body(ctx, m, b, cnamer, " ")
+ L.append(" }")
+ bodies.append(("void onCollision(nlcl::Entity& other) override;",
+ f"void {cls}::onCollision(nlcl::Entity& other) {{", L))
+
+ if "input" in groups:
+ L = []
+ for b in groups["input"]:
+ k = _trigger(b)[1]
+ k = self._ref_name(ctx, k) if self._find(ctx, k) else k
+ L.append(f" if (key == {_cstr(k)}) {{")
+ L += self._body(ctx, m, b, namer, " ")
+ L.append(" }")
+ bodies.append(("void onInput(const std::string& key) override;",
+ f"void {cls}::onInput(const std::string& key) {{", L))
+
+ for cname, meth in list(m.calls.items()):
+ impl = None
+ if ctx.llm is not None:
+ try:
+ impl = ctx.llm.write_body(
+ "C++17 member function body (fields are members; args is const std::vector&)",
+ cname.replace("_", " "),
+ f"class {cls} with fields {', '.join(f'{_CTYPE[t]} {m.fields[p]}' for p, t in m.props.items())}")
+ except Exception:
+ impl = None
+ if impl and isinstance(impl, str):
+ L = [" " + ln for ln in impl.splitlines()]
+ else:
+ L = [" (void)args; // TODO: implement",
+ f" log({_cstr(cname + ' called')});"]
+ bodies.append((f"void {meth}(const std::vector& args = {{}});",
+ f"void {cls}::{meth}(const std::vector& args) {{", L))
+
+ # ---- header
+ title = f'{e.kind} "{e.name}"'
+ H = [f"// {m.stem}.hpp - C++ class for {_cmt(title)} (generated by NLCL; edit freely)",
+ "#pragma once", "", '#include "nlcl_core.hpp"', "",
+ f"class {cls} : public nlcl::Entity {{", "public:",
+ f" explicit {cls}(nlcl::World& world, const std::string& name = {_cstr(e.ident)});", ""]
+ H.append(" // properties")
+ if not m.props:
+ H.append(" // (none yet)")
+ for p, t in m.props.items():
+ note = "" if m.fields[p] == p else f" // property \"{_cmt(p)}\""
+ H.append(f" {_CTYPE[t]} {m.fields[p]} = {_lit(m.init[p], t)};{note}")
+ if bodies:
+ H += ["", " // behaviours"]
+ for decl, _, _ in bodies:
+ H.append(" " + decl)
+ if m.edges:
+ H += ["", "private:", " // edge detection for 'when ' rules",
+ *[f" bool {f} = false;" for f in m.edges], "", "public:"]
+ H += ["", " // reflection used by the runtime (channels, change detection, log)",
+ " std::vector props() const override;",
+ " nlcl::Value get(const std::string& prop) const override;",
+ " bool set(const std::string& prop, const nlcl::Value& v) override;",
+ "};", ""]
+
+ # ---- source
+ S = [f"// {m.stem}.cpp - behaviours of {_cmt(title)} (generated by NLCL; edit freely)",
+ f'#include "{m.stem}.hpp"', "",
+ f"{cls}::{cls}(nlcl::World& world, const std::string& name)",
+ f" : nlcl::Entity(world, name, {_cstr(e.kind)}) {{"]
+ for i, ms in timer_decls:
+ S.append(f" every({ms}, [this] {{ onTimer{i}(); }});")
+ S += ["}", ""]
+ for _, head, L in bodies:
+ S.append(head)
+ S += L
+ S += ["}", ""]
+ S.append(f"std::vector {cls}::props() const {{")
+ S.append(" return {" + ", ".join(_cstr(p) for p in m.props) + "};")
+ S += ["}", "", f"nlcl::Value {cls}::get(const std::string& prop) const {{"]
+ if not m.props:
+ S.append(" (void)prop;")
+ for p in m.props:
+ S.append(f" if (prop == {_cstr(p)}) return nlcl::Value({m.fields[p]});")
+ S += [" return nlcl::Value();", "}", "",
+ f"bool {cls}::set(const std::string& prop, const nlcl::Value& v) {{"]
+ if not m.props:
+ S += [" (void)prop;", " (void)v;"]
+ for p in m.props:
+ S.append(f" if (prop == {_cstr(p)}) {{ nlcl::assign({m.fields[p]}, v); return true; }}")
+ S += [" return false;", "}", ""]
+ return "\n".join(H), "\n".join(S)
+
+ # ------------------------------------------------------------------ main
+ def _main(self, ctx: BuildContext, models: list[_Model]) -> str:
+ proj = ctx.system.name or ctx.project
+ local = {e.id for e in ctx.entities}
+ L = [f"// main.cpp - {_cmt(proj)}: C++ module generated by NLCL (edit freely).",
+ "// Builds the world, wires the channels and runs the fixed-step loop.",
+ "#include ", "#include ", "#include ", "#include ",
+ "#include ", "", '#include "nlcl_core.hpp"']
+ for m in models:
+ L.append(f'#include "{m.stem}.hpp"')
+ L += ["", "namespace {", "",
+ "void onSigint(int) { nlcl::g_stop = 1; }", "",
+ "void usage() {",
+ ' std::cout << "usage: app [--seconds N] [--simulate] [--dt S] [--fast] [--quiet]\\n"',
+ ' " --seconds N stop after N seconds of world time (default: run until Ctrl+C)\\n"',
+ ' " --simulate no network/hardware: invent incoming channel data and key presses\\n"',
+ ' " --dt S fixed time step in seconds (default 0.1)\\n"',
+ ' " --fast do not wait for real time between steps\\n"',
+ ' " --quiet only print behaviour logs and data lines\\n";',
+ "}", "", "} // namespace", "",
+ "int main(int argc, char** argv) {",
+ " double seconds = 0.0, dt = 0.1;",
+ " bool simulate = false, quiet = false, fast = false;",
+ " for (int i = 1; i < argc; ++i) {",
+ " std::string a = argv[i];",
+ ' if (a == "--seconds" && i + 1 < argc) seconds = std::atof(argv[++i]);',
+ ' else if (a == "--dt" && i + 1 < argc) dt = std::atof(argv[++i]);',
+ ' else if (a == "--simulate") simulate = true;',
+ ' else if (a == "--quiet") quiet = true;',
+ ' else if (a == "--fast") fast = true;',
+ ' else if (a == "--help" || a == "-h") { usage(); return 0; }',
+ ' else { std::cerr << "unknown argument: " << a << "\\n"; usage(); return 2; }',
+ " }",
+ " if (dt <= 0.0) dt = 0.1;",
+ " std::signal(SIGINT, onSigint);",
+ "",
+ " nlcl::World world;",
+ " world.simulate = simulate;",
+ " world.verbose = !quiet;", ""]
+ if models:
+ L.append(" // entities")
+ for m in models:
+ L.append(f" world.add(std::make_unique<{m.cls}>(world)); // {_cmt(m.e.kind)} {_cmt(m.e.name)}")
+ ids = {e.id: e for e in ctx.entities}
+ parents = [(m.e, ids[m.e.parent]) for m in models if m.e.parent in ids]
+ if parents:
+ L += ["", " // hierarchy (\"X in Y\")"]
+ for child, par in parents:
+ L.append(f" if (nlcl::Entity* e = world.find({_cstr(child.ident)})) e->setParent({_cstr(par.ident)});")
+ if ctx.channels:
+ L += ["", " // channels: flat JSON {\"channel\", \"from\", field...}"]
+ for c in ctx.channels:
+ ls, ld = c.src.id in local, c.dst.id in local
+ L.append(f" {{ // {_cmt(c.src.name)} ({c.src.domain}) -> {_cmt(c.dst.name)} ({c.dst.domain}) "
+ f"via {c.protocol}: {_cmt(', '.join(map(str, c.fields or [])))}")
+ cfg = dict(c.config or {})
+ cfg.setdefault("interval_ms", 1000)
+ cfg_txt = ", ".join(f"{{{_cstr(k)}, {_value_lit(v)}}}" for k, v in cfg.items()
+ if isinstance(v, (int, float, str, bool, list)))
+ fields = ", ".join(_cstr(f) for f in c.fields or [])
+ L.append(f" auto ch = nlcl::makeChannel({_cstr(c.protocol)}, {_cstr(c.id)}, {_cstr(c.src.ident)}, "
+ f"{_cstr(c.dst.ident)}, {{{fields}}},")
+ L.append(f" nlcl::Fields{{{cfg_txt}}}, {str(ls).lower()}, {str(ld).lower()});")
+ if not ls:
+ seed = [(f, (c.src.props or {}).get(f)) for f in c.fields or []]
+ seed = [(f, v) for f, v in seed if isinstance(v, (int, float, str, bool, list))
+ and (not isinstance(v, list) or _typ(v) == "vec")]
+ if seed:
+ L.append(" ch->seed = nlcl::Fields{" + ", ".join(
+ f"{{{_cstr(f)}, {_value_lit(v)}}}" for f, v in seed) + "}; // simulate mode starts here")
+ if c.protocol in ("spi", "i2c", "gpio", "wire"):
+ L.append(f" // note: {c.protocol} is an electrical bus; here it is carried as JSON lines on stdio")
+ L.append(" world.addChannel(std::move(ch));")
+ L.append(" }")
+ keys = []
+ for m in models:
+ for b in m.e.behaviors or []:
+ if not isinstance(b, dict):
+ continue
+ key, k = _trigger(b)
+ if key == "input" and k and b.get("do"):
+ k = self._ref_name(ctx, k) if self._find(ctx, k) else k
+ if k not in keys:
+ keys.append(k)
+ if keys:
+ L += ["", " // keys used by \"input\" behaviours: type them + Enter (simulated with --simulate)",
+ " world.inputKeys = {" + ", ".join(_cstr(k) for k in keys) + "};"]
+ L += ["",
+ f" std::cout << \"[\" << {_cstr(proj)} << \"] running \" << world.entities.size() << \" entities, \"",
+ " << world.channels.size() << \" channels\" << (simulate ? \" (simulated)\" : \"\")",
+ " << (seconds > 0 ? \"\" : \" - Ctrl+C to stop\") << std::endl;",
+ " world.run(seconds, dt, !fast);",
+ " world.printState();",
+ " return 0;",
+ "}", ""]
+ return "\n".join(L)
+
+ # ------------------------------------------------------------------ project files
+ def _cmake(self, proj: str, models: list[_Model]) -> str:
+ srcs = " ".join(["src/main.cpp", "src/nlcl_channels.cpp"] + [f"src/{m.stem}.cpp" for m in models])
+ t = f"{proj}_app"
+ return f"""# CMake build for the NLCL C++ module (any C++17 compiler).
+# cmake -S . -B build && cmake --build build
+cmake_minimum_required(VERSION 3.10)
+project({proj} LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_CXX_EXTENSIONS OFF)
+find_package(Threads REQUIRED)
+
+add_executable({t} {srcs})
+target_include_directories({t} PRIVATE include src)
+target_link_libraries({t} PRIVATE Threads::Threads)
+if(WIN32)
+ target_link_libraries({t} PRIVATE ws2_32)
+endif()
+if(MSVC)
+ target_compile_options({t} PRIVATE /utf-8 /W3 /EHsc)
+else()
+ target_compile_options({t} PRIVATE -Wall)
+endif()
+"""
+
+ def _scripts(self, models: list[_Model]) -> tuple[str, str]:
+ srcs = " ".join(["src/main.cpp", "src/nlcl_channels.cpp"] + [f"src/{m.stem}.cpp" for m in models])
+ wsrcs = srcs.replace("/", "\\")
+ sh = f"""#!/bin/sh
+# Build without CMake (GCC or Clang). Usage: ./build.sh && ./app --simulate --seconds 5
+set -e
+cd "$(dirname "$0")"
+CXX="${{CXX:-$(command -v g++ || command -v clang++)}}"
+EXTRA="-pthread"
+case "$(uname -s 2>/dev/null)" in MINGW*|MSYS*|CYGWIN*) EXTRA="-lws2_32";; esac
+"$CXX" -std=c++17 -O2 -Wall -Iinclude -Isrc {srcs} -o app $EXTRA
+echo "built ./app"
+"""
+ bat = f"""@echo off
+rem Build without CMake on Windows: MinGW-w64 g++ or clang++ if on PATH, else MSVC cl
+rem (run cl from a "Developer Command Prompt for VS"). Then: app.exe --simulate --seconds 5
+cd /d "%~dp0"
+where g++ >nul 2>nul
+if not errorlevel 1 (
+ g++ -std=c++17 -O2 -Iinclude -Isrc {wsrcs} -o app.exe -lws2_32 || exit /b 1
+ goto done
+)
+where clang++ >nul 2>nul
+if not errorlevel 1 (
+ clang++ -std=c++17 -O2 -Iinclude -Isrc {wsrcs} -o app.exe -lws2_32 || exit /b 1
+ goto done
+)
+where cl >nul 2>nul
+if not errorlevel 1 (
+ cl /nologo /std:c++17 /EHsc /utf-8 /O2 /Iinclude /Isrc {wsrcs} /Feapp.exe ws2_32.lib || exit /b 1
+ goto done
+)
+echo No C++ compiler found. Install MinGW-w64 (MSYS2 or WinLibs), LLVM clang or the free MSVC Build Tools.
+exit /b 1
+:done
+echo built app.exe
+"""
+ return sh, bat
+
+ @staticmethod
+ def _amalgamate(parts: list[tuple[str, str]]) -> str:
+ """Concatenate files into one translation unit (local includes and pragma once removed)."""
+ out = ["// Single-file build of the NLCL C++ module - paste into an online compiler",
+ "// (Compiler Explorer / Wandbox / OnlineGDB) with -std=c++17 and run it with",
+ "// arguments: --simulate --seconds 3 (Windows: link ws2_32)", ""]
+ for name, text in parts:
+ out.append(f"// ======================================================== {name}")
+ for ln in text.splitlines():
+ if re.match(r'\s*#\s*include\s+"[^"]+"', ln) or re.match(r"\s*#\s*pragma\s+once", ln):
+ continue
+ out.append(ln)
+ out.append("")
+ return "\n".join(out) + "\n"
+
+ def _readme(self, ctx: BuildContext, proj: str, models: list[_Model]) -> str:
+ local = {e.id for e in ctx.entities}
+ L = [f"# {ctx.system.name} - C++ module", "",
+ "Native C++17 program generated by NLCL. It uses only the C++ standard library",
+ "and the operating system's socket API (Winsock2 on Windows, BSD sockets elsewhere).", "",
+ "## Layout", "",
+ "| file | contents |", "|---|---|",
+ "| `include/nlcl_core.hpp` | runtime: `nlcl::Value`, flat JSON, `Entity` base, `World` loop |",
+ "| `src/nlcl_channels.hpp` / `.cpp` | transports: HTTP hub client, UDP, serial-style JSON lines, MQTT |",
+ "| `src/main.cpp` | creates the entities, wires the channels, command line |"]
+ for m in models:
+ L.append(f"| `include/{m.stem}.hpp`, `src/{m.stem}.cpp` | class `{m.cls}` ({_cmt(m.e.kind)} "
+ f"\"{_cmt(m.e.name)}\") |")
+ L += ["| `single/" + proj + ".cpp` | the whole program in one file (online compilers) |",
+ "| `CMakeLists.txt`, `build.sh`, `build.bat` | build scripts |", ""]
+ if models:
+ L += ["## Entities", ""]
+ for m in models:
+ props = ", ".join(f"`{p}` ({_CTYPE[t]})" for p, t in m.props.items()) or "none"
+ L.append(f"- **{m.e.name}** - {m.e.kind}; properties: {props}")
+ for b in m.e.behaviors or []:
+ if isinstance(b, dict):
+ L.append(f" - {self._describe(b)}")
+ L.append("")
+ if ctx.channels:
+ L += ["## Channels", "",
+ "| id | protocol | from | to | fields | here |", "|---|---|---|---|---|---|"]
+ for c in ctx.channels:
+ role = ("local (in memory)" if c.src.id in local and c.dst.id in local
+ else "sends" if c.src.id in local else "receives")
+ L.append(f"| {c.id} | {c.protocol} | {c.src.name} ({c.src.domain}) | {c.dst.name} ({c.dst.domain}) "
+ f"| {', '.join(map(str, c.fields or []))} | {role} |")
+ L += ["", "Messages are flat JSON objects: `{\"channel\": id, \"from\": sender, field: value, ...}`.",
+ "Senders publish their fields every `interval_ms`; receivers copy fields onto same-named",
+ "properties and fire `message` behaviours.", "",
+ "- **http / websocket** - POST/GET `http://localhost:/channel/` on the NLCL hub.",
+ " Start the hub first: `python ../python/main.py` (generated next to this folder).",
+ "- **udp** - one JSON datagram per message to 127.0.0.1:.",
+ "- **serial** (and spi/i2c/gpio/wire) - data lines are printed on stdout; incoming JSON lines",
+ " are read from stdin. Connect a real port with a bridge, e.g. on Linux",
+ " `stty -F /dev/ttyUSB0 115200 raw && ./app < /dev/ttyUSB0 > /dev/ttyUSB0`, or pipe",
+ " two programs: `python ../python/main.py | ./app`.",
+ "- **mqtt** - built-in minimal MQTT 3.1.1 client (QoS 0) to the configured broker.",
+ "- `--simulate` invents plausible incoming data instead of using the network.", ""]
+ L += ["## Build and run (free tools)", "",
+ "CMake (any compiler):", "", "```sh", "cmake -S . -B build", "cmake --build build",
+ f"./build/{proj}_app --simulate --seconds 5 # Windows/MSVC: build\\Debug\\{proj}_app.exe",
+ "```", "",
+ "Without CMake:", "", "```sh",
+ "# Linux / macOS (GCC or clang)",
+ "g++ -std=c++17 -O2 -Iinclude -Isrc src/*.cpp -o app -pthread",
+ "# Windows, MinGW-w64 g++ (MSYS2 `pacman -S mingw-w64-ucrt-x86_64-gcc` or WinLibs)",
+ "g++ -std=c++17 -O2 -Iinclude -Isrc src/*.cpp -o app.exe -lws2_32",
+ "# Windows, LLVM clang++",
+ "clang++ -std=c++17 -O2 -Iinclude -Isrc src/*.cpp -o app.exe -lws2_32",
+ "# Windows, free MSVC Build Tools (Developer Command Prompt)",
+ "cl /std:c++17 /EHsc /utf-8 /Iinclude /Isrc src\\*.cpp /Fe:app.exe ws2_32.lib",
+ "```", "",
+ "Or just `./build.sh` (Linux/macOS/MSYS2) / `build.bat` (Windows).", "",
+ "Online, no install: open https://godbolt.org (Compiler Explorer), paste",
+ f"`single/{proj}.cpp`, choose x86-64 gcc, add `-std=c++17`, enable \"Execute the code\"",
+ "and set the arguments to `--simulate --seconds 3`. Wandbox and OnlineGDB work the same way.", "",
+ "### Command line", "",
+ "| flag | meaning |", "|---|---|",
+ "| `--seconds N` | stop after N seconds of world time (default: until Ctrl+C) |",
+ "| `--simulate` | no network/hardware: fake incoming data and key presses |",
+ "| `--dt S` | fixed step in seconds (default 0.1) |",
+ "| `--fast` | do not wait for real time between steps |",
+ "| `--quiet` | print only behaviour logs and data lines |", "",
+ "Keyboard input: type a key name used by an `input` behaviour (e.g. `space`) and press Enter.",
+ "At the end the program prints the final state of every entity.", "",
+ "Notes: MinGW needs a POSIX-threads build (MSYS2 and WinLibs are) for `std::thread`.",
+ "Properties whose names are C++ keywords get a trailing underscore (e.g. `class_`).", ""]
+ return "\n".join(L)
+
+ # ------------------------------------------------------------------ build
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
+ proj = re.sub(r"_+", "_", ident(ctx.project or ctx.system.name or "project")) or "project"
+ self._local_models = {}
+ models = self._models(ctx)
+ self._local_models = {m.e.ident: m for m in models}
+ files: dict[str, str] = {}
+ core = (ASSETS / "nlcl_core.hpp").read_text(encoding="utf-8")
+ chan_h = (ASSETS / "nlcl_channels.hpp").read_text(encoding="utf-8")
+ chan_c = (ASSETS / "nlcl_channels.cpp").read_text(encoding="utf-8")
+ files["include/nlcl_core.hpp"] = core
+ files["src/nlcl_channels.hpp"] = chan_h
+ files["src/nlcl_channels.cpp"] = chan_c
+ heads, srcs = [], []
+ for m in models:
+ h, s = self._class_files(ctx, m)
+ files[f"include/{m.stem}.hpp"] = h
+ files[f"src/{m.stem}.cpp"] = s
+ heads.append((f"include/{m.stem}.hpp", h))
+ srcs.append((f"src/{m.stem}.cpp", s))
+ main = self._main(ctx, models)
+ files["src/main.cpp"] = main
+ files["CMakeLists.txt"] = self._cmake(proj, models)
+ sh, bat = self._scripts(models)
+ files["build.sh"] = sh
+ files["build.bat"] = bat.replace("\n", "\r\n")
+ # socket headers come last so their macros never touch entity code
+ files[f"single/{proj}.cpp"] = self._amalgamate(
+ [("include/nlcl_core.hpp", core)] + heads + srcs + [("src/main.cpp", main),
+ ("src/nlcl_channels.hpp", chan_h),
+ ("src/nlcl_channels.cpp", chan_c)])
+ files["README.md"] = self._readme(ctx, proj, models)
+ return files
+
+ # ------------------------------------------------------------------ run
+ def run(self, ctx: BuildContext) -> RunResult | None:
+ out = ctx.outdir
+ if not (out / "src" / "main.cpp").exists():
+ return RunResult(False, "build first")
+ win = os.name == "nt"
+ srcs = [str(Path("src") / p.name) for p in sorted((out / "src").glob("*.cpp"))]
+ bdir = out / "build"
+ bdir.mkdir(exist_ok=True)
+ exe = bdir / ("app.exe" if win else "app")
+ gxx = self.which("g++", "clang++")
+ zig = None if gxx else self.which("zig")
+ cl = None if gxx or zig else self.which("cl")
+ flags = ["-std=c++17", "-O1", "-Iinclude", "-Isrc", *srcs, "-o", str(exe)]
+ flags += ["-lws2_32"] if win else ["-pthread"]
+ if gxx:
+ cmd = [gxx, *flags]
+ elif zig:
+ cmd = [zig, "c++", *flags]
+ elif cl:
+ cmd = [cl, "/nologo", "/std:c++17", "/EHsc", "/utf-8", "/Iinclude", "/Isrc", *srcs,
+ f"/Fe{exe}", f"/Fo{bdir}{os.sep}", "ws2_32.lib"]
+ else:
+ return None
+ comp = self.sh(cmd, out, timeout=300)
+ if not comp.ok or not exe.exists():
+ return RunResult(False, "compile failed:\n" + comp.output, comp.command)
+ r = self.sh([str(exe), "--simulate", "--seconds", "2"], out, timeout=20)
+ return RunResult(r.ok, (comp.output + "\n" if comp.output else "") + r.output, comp.command + " && " + r.command)
+
+
+MODULE = CppModule()
diff --git a/nlcl/modules/embedded_mod.py b/nlcl/modules/embedded_mod.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f2773f988c3e87afb5e18087bf486aea6236f3f
--- /dev/null
+++ b/nlcl/modules/embedded_mod.py
@@ -0,0 +1,3015 @@
+"""Embedded domain: micro-controller firmware (Arduino C++ and MicroPython).
+
+Every board entity (arduino / uno / nano / mega / esp32 / esp8266 / pico /
+pico_w / stm32) becomes one firmware project in ``embedded//``:
+
+* ``.ino`` Arduino C++ sketch (Arduino IDE, arduino-cli, PlatformIO)
+* ``platformio.ini`` PlatformIO project (``pio run``)
+* ``main.py`` MicroPython equivalent (esp32 / pico boards)
+* ``diagram.json`` + ``wokwi.toml`` + ``libraries.txt``
+ Wokwi simulation project (free, in the browser / VS Code)
+
+Components (led, button, sensors, motor, servo, relay, buzzer, display ...)
+belong to the board they are children of; orphans go to the only board, or to
+an implicit default board (esp32 when a network channel exists, else Uno).
+
+Behaviours become functions called from ``loop()`` (millis() timers, edge
+detected button presses, change detection ...). Channels become transports:
+serial JSON lines, HTTP to the NLCL hub, MQTT, UDP, I2C/SPI byte frames or one
+GPIO pin per field.
+"""
+from __future__ import annotations
+
+import json
+import math
+import re
+from dataclasses import dataclass, field
+from typing import Any
+
+from ..ir import Entity, describe_action, ident
+from .base import BuildContext, Channel, DomainModule, RunResult
+
+# ===========================================================================
+# Boards
+# ===========================================================================
+
+
+def _int(v: Any, default: int) -> int:
+ """int() that never raises (channel config can carry odd user values)."""
+ try:
+ return int(float(v))
+ except (TypeError, ValueError, OverflowError):
+ return default
+
+
+def _rng(a: int, b: int, prefix: str = "") -> list[str]:
+ return [f"{prefix}{i}" for i in range(a, b + 1)]
+
+
+BOARDS: dict[str, dict] = {
+ "uno": dict(title="Arduino Uno", fqbn="arduino:avr:uno", pio=("atmelavr", "uno", "uno"),
+ wokwi="wokwi-arduino-uno", wid="uno", arch="avr", wifi="", adc_max=1023, upy=False,
+ pwm=["3", "5", "6", "9", "10", "11"], digital=["2", "4", "7", "8", "12", "13"],
+ analog=_rng(0, 5, "A"), i2c=("A4", "A5"), spi=("13", "12", "11"), ss="10",
+ vcc="5V", vcc5="5V", gnd="GND.1", led="13", fw="hex"),
+ "nano": dict(title="Arduino Nano", fqbn="arduino:avr:nano", pio=("atmelavr", "nanoatmega328", "nano"),
+ wokwi="wokwi-arduino-nano", wid="nano", arch="avr", wifi="", adc_max=1023, upy=False,
+ pwm=["3", "5", "6", "9", "10", "11"], digital=["2", "4", "7", "8", "12", "13"],
+ analog=_rng(0, 7, "A"), i2c=("A4", "A5"), spi=("13", "12", "11"), ss="10",
+ vcc="5V", vcc5="5V", gnd="GND.1", led="13", fw="hex"),
+ "mega": dict(title="Arduino Mega 2560", fqbn="arduino:avr:mega", pio=("atmelavr", "megaatmega2560", "mega"),
+ wokwi="wokwi-arduino-mega", wid="mega", arch="avr", wifi="", adc_max=1023, upy=False,
+ pwm=_rng(2, 12) + ["44", "45", "46"], digital=_rng(22, 49) + ["13"],
+ analog=_rng(0, 15, "A"), i2c=("20", "21"), spi=("52", "50", "51"), ss="53",
+ vcc="5V", vcc5="5V", gnd="GND.1", led="13", fw="hex"),
+ "esp32": dict(title="ESP32 DevKit", fqbn="esp32:esp32:esp32", pio=("espressif32", "esp32dev", "esp32"),
+ wokwi="board-esp32-devkit-c-v4", wid="esp", arch="esp32", wifi="esp32", adc_max=4095, upy=True,
+ pwm=["13", "14", "27", "26", "25", "33", "32", "4", "16", "17", "5", "18", "19", "23", "15", "12", "2"],
+ digital=["13", "14", "27", "26", "25", "33", "32", "4", "16", "17", "5", "18", "19", "23", "15", "12", "2"],
+ analog=["34", "35", "32", "33", "36", "39"], i2c=("21", "22"), spi=("18", "19", "23"), ss="5",
+ vcc="3V3", vcc5="5V", gnd="GND.1", led="2", fw="bin"),
+ "esp8266": dict(title="ESP8266 NodeMCU", fqbn="esp8266:esp8266:nodemcuv2",
+ pio=("espressif8266", "nodemcuv2", "esp8266"), wokwi="", wid="esp", arch="esp8266",
+ wifi="esp8266", adc_max=1023, upy=False,
+ pwm=["5", "4", "14", "12", "13", "0", "2", "15"],
+ digital=["5", "4", "14", "12", "13", "16", "0", "2", "15"],
+ analog=["A0"], i2c=("4", "5"), spi=("14", "12", "13"), ss="15",
+ vcc="3V3", vcc5="VIN", gnd="GND", led="2", fw="bin"),
+ "pico": dict(title="Raspberry Pi Pico (RP2040)", fqbn="rp2040:rp2040:rpipico", pio=("raspberrypi", "pico", "pico"),
+ wokwi="wokwi-pi-pico", wid="pico", arch="rp2040", wifi="", adc_max=1023, upy=True,
+ pwm=["15", "14", "13", "12", "11", "10", "9", "8", "7", "6", "3", "2", "20", "21", "22"],
+ digital=["15", "14", "13", "12", "11", "10", "9", "8", "7", "6", "3", "2", "20", "21", "22"],
+ analog=["26", "27", "28"], i2c=("4", "5"), spi=("18", "16", "19"), ss="17",
+ vcc="3V3", vcc5="VBUS", gnd="GND.1", led="", fw="uf2"),
+ "pico_w": dict(title="Raspberry Pi Pico W", fqbn="rp2040:rp2040:rpipicow", pio=("raspberrypi", "rpipicow", "pico_w"),
+ wokwi="board-pi-pico-w", wid="pico", arch="rp2040", wifi="picow", adc_max=1023, upy=True,
+ pwm=["15", "14", "13", "12", "11", "10", "9", "8", "7", "6", "3", "2", "20", "21", "22"],
+ digital=["15", "14", "13", "12", "11", "10", "9", "8", "7", "6", "3", "2", "20", "21", "22"],
+ analog=["26", "27", "28"], i2c=("4", "5"), spi=("18", "16", "19"), ss="17",
+ vcc="3V3", vcc5="VBUS", gnd="GND.1", led="", fw="uf2"),
+ "stm32": dict(title="STM32 Blue Pill (F103C8)", fqbn="STMicroelectronics:stm32:GenF1:pnum=BLUEPILL_F103C8",
+ pio=("ststm32", "bluepill_f103c8", "bluepill"), wokwi="", wid="stm", arch="stm32", wifi="",
+ adc_max=1023, upy=False,
+ pwm=["PA8", "PB8", "PB9", "PA0", "PA1", "PA2", "PA3", "PA6", "PA7", "PB0", "PB1"],
+ digital=["PB12", "PB13", "PB14", "PB15", "PB5", "PB4", "PB3", "PA15", "PB10", "PB11"],
+ analog=["PA0", "PA1", "PA2", "PA3", "PB0", "PB1"], i2c=("PB7", "PB6"),
+ spi=("PA5", "PA6", "PA7"), ss="PA4", vcc="3V3", vcc5="5V", gnd="GND", led="PC13", fw="bin"),
+}
+
+BOARD_KINDS = {
+ "arduino": "uno", "uno": "uno", "nano": "nano", "mega": "mega", "esp32": "esp32", "esp8266": "esp8266",
+ "nodemcu": "esp8266", "wemos": "esp8266", "pico": "pico", "rp2040": "pico", "pico_w": "pico_w",
+ "picow": "pico_w", "stm32": "stm32", "bluepill": "stm32", "board": "uno", "microcontroller": "uno",
+ "mcu": "uno", "devboard": "uno",
+}
+
+# role -> state members every component of that role has (prop -> default)
+ROLE_STATE: dict[str, dict] = {
+ "led": {"on": False},
+ "button": {"pressed": False},
+ "switch": {"on": False},
+ "pir": {"motion": False},
+ "temp": {"temperature": 0.0},
+ "dht": {"temperature": 0.0, "humidity": 0.0},
+ "distance": {"distance": 0.0},
+ "light": {"light": 0},
+ "pot": {"value": 0},
+ "analog": {}, # measure prop is derived from the subtype
+ "motor": {"on": False, "speed": 255},
+ "fan": {"on": False, "speed": 255},
+ "servo": {"angle": 90},
+ "relay": {"on": False},
+ "buzzer": {"on": False, "frequency": 1000},
+ "oled": {"text": ""},
+ "lcd": {"text": ""},
+ "neopixel": {"on": True, "color": "white", "brightness": 50, "pixels": 1},
+ "board": {},
+ "generic": {},
+}
+# the "main" value of a component when its name is used in an expression
+PRIMARY = {"led": "on", "button": "pressed", "switch": "on", "pir": "motion", "temp": "temperature",
+ "dht": "temperature", "distance": "distance", "light": "light", "pot": "value", "motor": "on",
+ "fan": "on", "servo": "angle", "relay": "on", "buzzer": "on", "oled": "text", "lcd": "text",
+ "neopixel": "on"}
+# extra runtime props the drivers understand (beyond ROLE_STATE)
+DRIVER_PROPS = {"led": ("brightness",), "neopixel": ("color", "brightness", "on"), "motor": ("speed",),
+ "fan": ("speed",), "servo": ("angle",), "buzzer": ("frequency",), "oled": ("text",),
+ "lcd": ("text",), "relay": ("on",)}
+# PWM-style props (0..255) an analog reading has to be rescaled for
+PWM_PROPS = {("led", "brightness"), ("neopixel", "brightness"), ("motor", "speed"), ("fan", "speed")}
+# analog measurements users think of in percent
+PERCENT_FIELDS = {"moisture", "humidity", "level", "percent", "water", "water_level", "soil", "wetness"}
+# props that configure hardware and never become runtime state
+SKIP_PROPS = {"pin", "pins", "trig_pin", "echo_pin", "subtype", "position", "rotation", "scale", "size",
+ "address", "model", "wifi_ssid", "wifi_password", "board", "baud", "port", "hub_host",
+ "collision_cm", "material", "texture", "shape", "units", "mass", "gravity"}
+SENSOR_WORDS = {"sensor", "probe", "detector", "meter", "transducer"}
+
+CPP_RESERVED = set("""alignas alignof and and_eq asm auto bitand bitor bool break case catch char class compl
+const constexpr const_cast continue decltype default delete do double dynamic_cast else enum explicit export
+extern false float for friend goto if inline int long mutable namespace new noexcept not not_eq nullptr operator
+or or_eq private protected public register reinterpret_cast return short signed sizeof static static_assert
+static_cast struct switch template this throw true try typedef typeid typename union unsigned using virtual void
+volatile wchar_t while xor xor_eq setup loop delay millis micros random min max abs round map constrain sq sqrt
+pow sin cos tan log exp tone word byte boolean bit isnan isinf radians degrees interrupts yield main index select
+free malloc exit printf signal remove rename gamma y0 y1 j0 j1 now string serial time ceil floor trunc fabs
+lround labs atoi itoa ltoa random_seed init""".split())
+PY_RESERVED = set("""False None True and as assert async await break class continue def del elif else except
+finally for from global if import in is lambda nonlocal not or pass raise return try while with yield time sys
+json machine network Pin ADC PWM I2C SPI Obj REMOTE select dht neopixel print str int float bool len range list
+dict min max abs round id type object input open setup loop main socket requests""".split())
+
+# local / helper names used inside generated functions: an entity global with one of these names would be
+# shadowed (C++) or would clobber a helper (MicroPython), so such entities get an '_obj' suffix.
+LOCAL_NAMES = set("""a a0 a1 a2 args b body buf c ch changed client code col cond data e got h hi http i j k key
+kw l1 last lasttry len line lo m method msg n now path payload r raw s self t t0 tc topic txt up url us v vals w was
+who beep color command comms handle_line i16 to_num nlcl_log read_inputs write_outputs triggers wifi_up udp_sock
+mqtt_client poll_serial math ssd1306 umqtt urequests usocket struct gc os errno""".split())
+COLORS = {"red": (255, 0, 0), "green": (0, 255, 0), "blue": (0, 0, 255), "yellow": (255, 200, 0),
+ "white": (255, 255, 255), "orange": (255, 100, 0), "purple": (128, 0, 255), "pink": (255, 60, 120),
+ "cyan": (0, 255, 255), "magenta": (255, 0, 255), "black": (0, 0, 0)}
+
+# I2C/SPI frame (shared with the hardware module): 0xA5, N, then N x int16 big-endian in field order.
+# Reads: SPI master sends 0x5A then clocks 1 + 2N bytes (0xA5 + words); I2C read returns 0xA5, N, words.
+FRAME_SYNC = 0xA5
+FRAME_READ = 0x5A
+
+
+# ===========================================================================
+# Internal model
+# ===========================================================================
+
+@dataclass
+class Member:
+ name: str # identifier in generated code
+ field: str # original property / JSON key
+ ctype: str # bool | long | float | String
+ value: Any
+
+
+@dataclass
+class Comp:
+ e: Entity
+ role: str
+ var: str
+ members: dict = field(default_factory=dict) # field -> Member
+ pins: dict = field(default_factory=dict) # logical -> canonical pin string
+ explicit: set = field(default_factory=set) # logical pins the user chose
+
+
+@dataclass
+class Chan:
+ ch: Channel
+ out: bool
+ inn: bool
+ transport: str
+ src: Comp | None = None
+ dst: Comp | None = None
+ note: str = ""
+ pins: dict = field(default_factory=dict) # gpio: field -> pin ; spi: {"cs": pin}
+
+ @property
+ def cid(self) -> str:
+ return ident(self.ch.id) or "chan"
+
+ @property
+ def local(self) -> bool:
+ return self.out and self.inn
+
+
+@dataclass
+class Beh:
+ n: int
+ comp: Comp
+ b: dict
+
+ @property
+ def trig(self) -> str:
+ return self.b["on"].split(":", 1)[0]
+
+ @property
+ def arg(self) -> str:
+ return self.b["on"].split(":", 1)[1] if ":" in self.b["on"] else ""
+
+
+@dataclass
+class Board:
+ key: str
+ spec: dict
+ ident: str
+ entity: Entity | None
+ comps: list = field(default_factory=list)
+ chans: list = field(default_factory=list)
+ behs: list = field(default_factory=list)
+ used: set = field(default_factory=set)
+ warnings: list = field(default_factory=list)
+ remotes: dict = field(default_factory=dict) # key "src.field" -> cpp var
+ calls: dict = field(default_factory=dict) # user function name -> max argc
+ libs: set = field(default_factory=set)
+ pwm_avoid: set = field(default_factory=set) # pins whose PWM timer is taken by Servo / tone()
+
+ @property
+ def wifi(self) -> str:
+ return self.spec["wifi"]
+
+ def by_role(self, *roles) -> list:
+ return [c for c in self.comps if c.role in roles]
+
+
+# ===========================================================================
+# Module
+# ===========================================================================
+
+class EmbeddedModule(DomainModule):
+ name = "embedded"
+ title = "Embedded firmware (Arduino C++, MicroPython, Wokwi simulation)"
+ aliases = ("embedded", "firmware", "mcu", "iot", "microcontroller", "microcontrollers",
+ "تعبیهشده", "تعبیه_شده", "میکروکنترلر")
+ keywords = ("arduino", "esp32", "esp8266", "nodemcu", "wemos", "rp2040", "pico", "stm32", "bluepill",
+ "micropython", "platformio", "wokwi", "sketch", "gpio", "pwm", "adc", "wifi", "bluetooth",
+ "led", "leds", "button", "pushbutton", "sensor", "sensors", "thermistor", "thermometer", "dht",
+ "dht11", "dht22", "hygrometer", "ultrasonic", "sonar", "ldr", "photoresistor", "potentiometer",
+ "knob", "motor", "servo", "relay", "buzzer", "piezo", "fan", "oled", "lcd", "neopixel",
+ "ws2812", "pir", "breadboard", "millis", "baud", "thermostat", "greenhouse", "irrigation",
+ "doorbell", "datalogger", "weather station", "smart home", "esp", "nano", "uno", "mega")
+ kinds = {
+ "object": {},
+ # boards
+ "arduino": {}, "uno": {}, "nano": {}, "mega": {}, "esp32": {}, "esp8266": {}, "nodemcu": {},
+ "pico": {}, "pico_w": {}, "rp2040": {}, "stm32": {}, "bluepill": {}, "board": {}, "microcontroller": {},
+ # outputs
+ "led": {"on": False}, "lamp": {"on": False},
+ "motor": {"on": False, "speed": 255}, "fan": {"on": False, "speed": 255},
+ "servo": {"angle": 90}, "relay": {"on": False},
+ "buzzer": {"on": False, "frequency": 1000}, "piezo": {"on": False, "frequency": 1000},
+ "display": {"text": ""}, "oled": {"text": ""}, "lcd": {"text": ""},
+ "neopixel": {"on": True, "color": "white", "brightness": 50, "pixels": 1},
+ "ws2812": {"on": True, "color": "white", "brightness": 50, "pixels": 1},
+ # inputs
+ "button": {"pressed": False}, "pushbutton": {"pressed": False}, "switch": {"on": False},
+ "pir": {"motion": False},
+ "sensor": {},
+ "thermistor": {"temperature": 0.0}, "thermometer": {"temperature": 0.0}, "lm35": {"temperature": 0.0},
+ "dht": {"temperature": 0.0, "humidity": 0.0}, "dht11": {"temperature": 0.0, "humidity": 0.0},
+ "dht22": {"temperature": 0.0, "humidity": 0.0}, "hygrometer": {"temperature": 0.0, "humidity": 0.0},
+ "ultrasonic": {"distance": 0.0}, "hc_sr04": {"distance": 0.0}, "sonar": {"distance": 0.0},
+ "ldr": {"light": 0}, "photoresistor": {"light": 0},
+ "potentiometer": {"value": 0}, "knob": {"value": 0},
+ "counter": {"count": 0},
+ }
+ suggested_props = ("pin", "on", "interval_ms", "threshold", "brightness", "angle", "speed")
+ protocols = ("serial", "http", "mqtt", "udp", "i2c", "spi", "gpio", "wire")
+ toolchain = """Every board folder `embedded//` is a complete project for free tools:
+
+- **Wokwi** (free browser simulator, no hardware): open https://wokwi.com, start a new project for the
+ board, paste `.ino` into `sketch.ino`, replace `diagram.json` and `libraries.txt`, press Play.
+ VS Code: install the free Wokwi extension, run `pio run` once, then *Wokwi: Start Simulator* (uses `wokwi.toml`).
+- **arduino-cli**: `arduino-cli core install ` then
+ `arduino-cli compile --fqbn embedded/` and
+ `arduino-cli upload -p --fqbn embedded/` (fqbn/core listed in the folder README).
+- **PlatformIO**: `pio run -d embedded/` / `pio run -d embedded/ -t upload` / `pio device monitor`.
+- **MicroPython** (esp32 / pico): flash MicroPython, then `mpremote cp embedded//main.py :main.py` and reset.
+
+Serial channels are newline-delimited JSON at 115200 baud: `python main.py` in the python folder reads them."""
+
+ # ------------------------------------------------------------------ props
+ def validate(self, entity: Entity) -> list[str]:
+ """Give sensors their measurement property (e.g. temperature) and check pins. Never raises."""
+ warns: list[str] = []
+ try:
+ role = self._role(entity)
+ if role in ("temp", "dht", "distance", "light", "pot", "pir", "analog"):
+ for k, v in self._state_defaults(entity, role).items():
+ entity.props.setdefault(k, v)
+ pin = entity.props.get("pin")
+ if pin is not None and not isinstance(pin, (list, tuple)) and self._norm_pin("uno", pin) is None \
+ and self._norm_pin("stm32", pin) is None:
+ warns.append(f"pin {pin!r} is not a pin name I understand; a free pin will be chosen")
+ except Exception: # validation must never break the interpreter
+ pass
+ return warns
+
+ # ------------------------------------------------------------------ roles
+ @staticmethod
+ def _words(e: Entity) -> set[str]:
+ st = str(e.props.get("subtype", "") or "")
+ return {w for w in re.split(r"[^a-z0-9]+", (e.kind + " " + st + " " + e.name).lower()) if w}
+
+ def _role(self, e: Entity) -> str:
+ k = (e.kind or "object").lower()
+ st = str(e.props.get("subtype", "") or "").lower()
+ sw = {w for w in re.split(r"[^a-z0-9]+", st) if w}
+ allw = sw | {k}
+ if k in BOARD_KINDS:
+ return "board"
+ if k in ("neopixel", "ws2812", "strip", "ring") or (k == "led" and sw & {"neopixel", "ws2812", "rgb_strip"}):
+ return "neopixel"
+ if k in ("led", "lamp", "bulb", "light", "indicator"):
+ return "led"
+ if k in ("button", "pushbutton", "push_button"):
+ return "button"
+ if k == "switch":
+ return "switch"
+ if k in ("motor",):
+ return "motor"
+ if k == "fan":
+ return "fan"
+ if k == "servo":
+ return "servo"
+ if k == "relay":
+ return "relay"
+ if k in ("buzzer", "piezo", "speaker", "beeper", "siren"):
+ return "buzzer"
+ if k == "lcd" or (k in ("display", "screen") and "lcd" in sw):
+ return "lcd"
+ if k in ("display", "oled", "screen", "ssd1306"):
+ return "oled"
+ if k in ("potentiometer", "knob", "dial", "slider", "pot"):
+ return "pot"
+ sensorish = k in SENSOR_WORDS or k.endswith("sensor") or k in (
+ "pir", "dht", "dht11", "dht22", "hygrometer", "thermistor", "thermometer", "lm35", "ntc",
+ "ultrasonic", "hc_sr04", "sonar", "ldr", "photoresistor", "photocell")
+ if not sensorish:
+ # "pico w" / "esp32 devkit" parse as kind 'w' / 'devkit' with the board in the subtype
+ if sw & set(BOARD_KINDS) and k not in ROLE_STATE:
+ return "board"
+ return "generic"
+ if allw & {"pir", "motion", "presence", "movement"}:
+ return "pir"
+ if allw & {"dht", "dht11", "dht22", "humidity", "hygrometer"}:
+ return "dht"
+ if allw & {"temperature", "temp", "thermo", "thermal", "thermistor", "thermometer", "lm35", "ntc", "heat"}:
+ return "temp"
+ if allw & {"distance", "ultrasonic", "sonar", "hc_sr04", "range", "proximity", "hcsr04"}:
+ return "distance"
+ if allw & {"light", "ldr", "photo", "photoresistor", "photocell", "lux", "luminosity"}:
+ return "light"
+ return "analog"
+
+ def _state_defaults(self, e: Entity, role: str) -> dict:
+ d = dict(ROLE_STATE.get(role, {}))
+ if role == "analog":
+ st = [w for w in re.split(r"[^a-z0-9]+", str(e.props.get("subtype", "") or "").lower()) if w]
+ m = ident(st[-1]) if st else ""
+ if not m or m in SKIP_PROPS or m in CPP_RESERVED or m in PY_RESERVED or m in ("analog", "sensor"):
+ m = "value"
+ d[m] = 0
+ return d
+
+ # ------------------------------------------------------------------ pins
+ @staticmethod
+ def _norm_pin(key: str, v: Any) -> str | None:
+ if isinstance(v, bool) or v is None:
+ return None
+ if isinstance(v, float):
+ v = int(v)
+ s = str(v).strip().upper().replace(" ", "")
+ if key == "stm32":
+ m = re.fullmatch(r"P([A-E])(\d{1,2})", s)
+ return f"P{m.group(1)}{m.group(2)}" if m else None
+ s = re.sub(r"^(GPIO|GP|IO|PIN)", "", s)
+ if key == "esp8266":
+ dmap = {"D0": "16", "D1": "5", "D2": "4", "D3": "0", "D4": "2", "D5": "14", "D6": "12", "D7": "13",
+ "D8": "15"}
+ if s in dmap:
+ return dmap[s]
+ m = re.fullmatch(r"D(\d{1,2})", s)
+ if m:
+ s = m.group(1)
+ m = re.fullmatch(r"A(\d{1,2})", s)
+ if m:
+ n = int(m.group(1))
+ if key == "esp32":
+ amap = {0: "36", 3: "39", 4: "32", 5: "33", 6: "34", 7: "35"}
+ return amap.get(n)
+ if key in ("pico", "pico_w"):
+ return str(26 + n) if n <= 2 else None
+ return f"A{n}"
+ if re.fullmatch(r"\d{1,2}", s):
+ return str(int(s))
+ return None
+
+ @staticmethod
+ def _pin_needs(c: Comp) -> list[tuple[str, str]]:
+ r = c.role
+ if r == "led":
+ return [("pin", "pwm" if "brightness" in c.e.props else "digital")]
+ if r in ("button", "switch", "pir", "dht", "relay", "neopixel"):
+ return [("pin", "digital")]
+ if r in ("temp", "light", "pot", "analog"):
+ return [("pin", "analog")]
+ if r == "distance":
+ return [("trig", "digital"), ("echo", "digital")]
+ if r in ("motor", "fan"):
+ return [("pin", "pwm")]
+ if r in ("servo", "buzzer"): # Servo / tone() work on any digital pin: keep PWM pins for dimming
+ return [("pin", "digital")]
+ return []
+
+ def _alloc(self, b: Board, kind: str, prefer: str = "") -> str:
+ sp = b.spec
+ # analog pins double as digital I/O (except the input-only ESP32 ADC pins)
+ spare = [p for p in sp["analog"] if not (b.key == "esp32" and p in ("34", "35", "36", "39"))]
+ pwm = [p for p in sp["pwm"] if p not in b.pwm_avoid]
+ order = {"analog": [sp["analog"]], "pwm": [pwm, sp["digital"], sp["pwm"]],
+ "digital": [sp["digital"], sp["pwm"], spare]}[kind]
+ if prefer and prefer not in b.used and kind != "analog":
+ b.used.add(prefer)
+ return prefer
+ for pi, pool in enumerate(order):
+ for p in pool:
+ if p not in b.used:
+ b.used.add(p)
+ if kind == "pwm" and pi > 0:
+ b.warnings.append(f"no free PWM pin left: pin {p} gives on/off only (set 'pin' explicitly)")
+ return p
+ b.warnings.append(f"ran out of free {kind} pins; reusing a pin - set 'pin' explicitly")
+ pool = order[0] or sp["digital"]
+ return pool[0]
+
+ def _assign_pins(self, b: Board, needs_i2c: bool, needs_spi: bool) -> None:
+ sp = b.spec
+ if needs_i2c:
+ b.used.update(sp["i2c"])
+ if needs_spi:
+ b.used.update(sp["spi"])
+ # AVR timers: Servo takes Timer1 (Uno/Nano pins 9, 10; Mega Timer5: 44-46), tone() takes Timer2
+ # (Uno/Nano pins 3, 11; Mega 9, 10) - analogWrite() on those pins then stops working.
+ if sp["arch"] == "avr":
+ mega = b.key == "mega"
+ if b.by_role("servo"):
+ b.pwm_avoid |= {"44", "45", "46"} if mega else {"9", "10"}
+ if b.by_role("buzzer"):
+ b.pwm_avoid |= {"9", "10"} if mega else {"3", "11"}
+ # explicit pins first
+ for c in b.comps:
+ needs = self._pin_needs(c)
+ if not needs:
+ continue
+ props = c.e.props
+ given: dict[str, Any] = {}
+ if isinstance(props.get("pins"), (list, tuple)):
+ for (logical, _), v in zip(needs, props["pins"]):
+ given[logical] = v
+ if "pin" in props and not isinstance(props["pin"], (list, tuple)):
+ given[needs[0][0]] = props["pin"]
+ if "trig_pin" in props:
+ given["trig"] = props["trig_pin"]
+ if "echo_pin" in props:
+ given["echo"] = props["echo_pin"]
+ for logical, v in given.items():
+ p = self._norm_pin(b.key, v)
+ if p is None:
+ b.warnings.append(f"{c.e.name}: pin {v!r} not valid for {sp['title']}; choosing a free pin")
+ continue
+ if p in b.used:
+ owner = next((o.e.name for o in b.comps if p in o.pins.values()), "a bus")
+ b.warnings.append(f"{c.e.name}: pin {p} is already used by {owner}")
+ if c.role in ("temp", "light", "pot", "analog") and p not in sp["analog"]:
+ why = (" (ADC1 pins 32-39 only: ADC2 stops working while WiFi is on)"
+ if b.key == "esp32" else "")
+ b.warnings.append(f"{c.e.name}: pin {p} is not a usable analog input on {sp['title']}{why}")
+ kind = dict(needs).get(logical)
+ if kind == "pwm" and c.role != "servo" and c.role != "buzzer":
+ if p not in sp["pwm"]:
+ b.warnings.append(f"{c.e.name}: pin {p} has no PWM on {sp['title']}; speed/brightness "
+ f"will be on/off only")
+ elif p in b.pwm_avoid:
+ b.warnings.append(f"{c.e.name}: PWM on pin {p} stops working while Servo/tone() use its "
+ f"timer; pick another PWM pin")
+ c.pins[logical] = p
+ c.explicit.add(logical)
+ b.used.add(p)
+ # then free pins; scarce analog pins first
+ for kind in ("analog", "pwm", "digital"):
+ for c in b.comps:
+ for logical, k in self._pin_needs(c):
+ if k == kind and logical not in c.pins:
+ prefer = sp["led"] if (c.role == "led" and kind == "digital"
+ and not b.by_role("led")[0].pins.get("pin")) else ""
+ if c.role == "led" and c is not b.by_role("led")[0]:
+ prefer = ""
+ c.pins[logical] = self._alloc(b, kind, prefer)
+
+ # ------------------------------------------------------------------ naming
+ @staticmethod
+ def _safe(n: str, taken: set | None = None) -> str:
+ n = ident(n) or "obj"
+ if n in CPP_RESERVED or n in PY_RESERVED or n in LOCAL_NAMES or n.startswith(("nlcl", "_", "user_", "remote_",
+ "publish_", "recv_", "poll_", "tx_")):
+ n = n.lstrip("_") + "_obj"
+ if taken is not None:
+ base, i = n, 2
+ while n in taken:
+ n = f"{base}{i}"
+ i += 1
+ taken.add(n)
+ return n
+
+ @staticmethod
+ def _mname(f: str) -> str:
+ n = ident(f) or "value"
+ if n in CPP_RESERVED or n in PY_RESERVED:
+ n += "_"
+ return n
+
+ @staticmethod
+ def _ctype(v: Any) -> str | None:
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "long" if -2147483648 <= v <= 2147483647 else "float" # long is 32-bit on AVR
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, str):
+ return "String"
+ return None
+
+ def _member(self, c: Comp, f: str, ctype: str = "float", value: Any = None) -> Member:
+ f = ident(f) or "value"
+ m = c.members.get(f)
+ if m is None:
+ if value is None:
+ value = {"bool": False, "long": 0, "float": 0.0, "String": ""}[ctype]
+ m = Member(self._mname(f), f, ctype, value)
+ c.members[f] = m
+ return m
+
+ # ------------------------------------------------------------------ c / python literals
+ @staticmethod
+ def _cstr(s: Any) -> str:
+ s = str(s).replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\r", "")
+ return f'"{s}"'
+
+ def _clit(self, m: Member) -> str:
+ v = m.value
+ if m.ctype == "bool":
+ return "true" if v else "false"
+ if m.ctype == "long":
+ try:
+ return str(max(-2147483647, min(2147483647, int(v))))
+ except (TypeError, ValueError, OverflowError):
+ return "0"
+ if m.ctype == "float":
+ try:
+ f = float(v)
+ return repr(f) if math.isfinite(f) else "0.0"
+ except (TypeError, ValueError, OverflowError):
+ return "0.0"
+ return self._cstr(v)
+
+ def _plit(self, m: Member) -> str:
+ v = m.value
+ try:
+ return {"bool": lambda: "True" if v else "False", "long": lambda: str(int(v)),
+ "float": lambda: repr(float(v)) if math.isfinite(float(v)) else "0.0",
+ "String": lambda: repr(str(v))}[m.ctype]()
+ except (TypeError, ValueError, OverflowError):
+ return "0"
+
+ # ======================================================================
+ # Planning
+ # ======================================================================
+ def _plan(self, ctx: BuildContext) -> list[Board]:
+ ents = list(ctx.entities)
+ by_id = {e.id: e for e in ents}
+ taken: set[str] = set()
+ boards: list[Board] = []
+ board_of_ent: dict[str, Board] = {}
+ for e in ents:
+ if self._role(e) == "board":
+ sub = str(e.props.get("subtype", "") or "").lower()
+ words = [w for w in re.split(r"[^a-z0-9]+", f"{sub} {e.kind}".lower()) if w]
+ key = BOARD_KINDS.get(e.kind.lower()) or next(
+ (BOARD_KINDS[w] for w in words if w in BOARD_KINDS and w not in ("board", "microcontroller", "mcu")),
+ "uno")
+ if key == "pico" and (set(words) & {"w", "wifi", "wireless"}):
+ key = "pico_w"
+ for k2 in ("esp32", "esp8266", "nano", "mega", "stm32"):
+ if key == "uno" and k2 in sub:
+ key = k2
+ b = Board(key, BOARDS[key], self._safe(e.ident, taken), e)
+ boards.append(b)
+ board_of_ent[e.id] = b
+ netted = any(c.protocol in ("http", "mqtt", "websocket", "udp") for c in ctx.channels)
+ default: Board | None = None
+
+ def home(e: Entity) -> Board:
+ nonlocal default
+ p, seen = e.parent, set()
+ while p in by_id and p not in seen:
+ seen.add(p)
+ if p in board_of_ent and self._role(by_id[p]) == "board":
+ return board_of_ent[p]
+ p = by_id[p].parent
+ if boards:
+ return boards[0]
+ if default is None:
+ key = "esp32" if netted else "uno"
+ default = Board(key, BOARDS[key], self._safe(key, taken | {ident(x.name) for x in ents}), None)
+ taken.add(default.ident)
+ return default
+
+ for e in ents:
+ if e.id in board_of_ent:
+ continue
+ board_of_ent[e.id] = home(e)
+ if default is not None:
+ boards.append(default)
+ # components
+ for e in ents:
+ b = board_of_ent[e.id]
+ role = self._role(e)
+ c = Comp(e, role, b.ident if e is b.entity else self._safe(e.ident, taken))
+ for k, v in self._state_defaults(e, role).items():
+ self._member(c, k, self._ctype(v) or "float", v)
+ for k, v in e.props.items():
+ if k.startswith("_") or (k in SKIP_PROPS) or (k == "color" and role != "neopixel"):
+ continue
+ t = self._ctype(v)
+ if t is None:
+ continue
+ old = c.members.get(ident(k))
+ if old and old.ctype != t and not (old.ctype in ("long", "float") and t in ("long", "float", "bool")):
+ continue # keep the driver's type when the user gave an odd value
+ if old and old.ctype in ("long", "float") and t in ("long", "float", "bool"):
+ old.value = v
+ continue
+ if old and old.ctype == "bool" and t in ("long", "float"):
+ old.value = bool(v)
+ continue
+ self._member(c, k, t, v).value = v
+ self._member(c, "alive", "bool", True)
+ if e is b.entity:
+ b.comps.insert(0, c)
+ else:
+ b.comps.append(c)
+ comp_of = {c.e.id: (b, c) for b in boards for c in b.comps}
+ self._all_comps = [(b, c) for b in boards for c in b.comps]
+ # "set door angle to 90" inside another entity's behaviour reaches us as a default-valued
+ # 'door_angle' prop copied onto the owner: drop that shadow so names resolve to door.angle
+ for b, c in self._all_comps:
+ defaults = self._state_defaults(c.e, c.role)
+ for f in list(c.members):
+ m = c.members[f]
+ if f in defaults or f == "alive" or m.value not in (0, 0.0, "", False):
+ continue
+ pre = c.e.ident + "_"
+ if self._owned_prefix(c, f, [o for _, o in self._all_comps]) is not None or (f.startswith(pre) and self._known_prop(c, f[len(pre):])):
+ del c.members[f]
+ # channels
+ for ch in ctx.channels:
+ sb = comp_of.get(ch.src.id)
+ db = comp_of.get(ch.dst.id)
+ for b in boards:
+ out = sb is not None and sb[0] is b
+ inn = db is not None and db[0] is b
+ if not (out or inn):
+ continue
+ proto = {"uart": "serial", "websocket": "http", "wire": "gpio"}.get(ch.protocol, ch.protocol)
+ note = ""
+ if proto in ("http", "mqtt", "udp") and not b.wifi and not (out and inn):
+ note = (f"{b.spec['title']} has no WiFi: '{ch.protocol}' channel falls back to serial JSON "
+ f"(run the python bridge, or use an esp32 / pico_w board)")
+ b.warnings.append(note)
+ proto = "serial"
+ if proto not in ("serial", "http", "mqtt", "udp", "i2c", "spi", "gpio"):
+ note = f"protocol '{ch.protocol}' not supported on boards; using serial JSON"
+ b.warnings.append(note)
+ proto = "serial"
+ b.chans.append(Chan(ch, out, inn, proto, sb[1] if out else None, db[1] if inn else None, note))
+ # pins
+ for b in boards:
+ sl = self._i2c_slave(b)
+ if sl is not None:
+ b.warnings.append(f"'{sl.ch.id}': this board is the I2C slave at {self._i2c_addr(sl.ch)} "
+ f"(MicroPython main.py has no portable I2C slave: use the Arduino sketch)")
+ if b.by_role("oled", "lcd") or any(x.transport == "i2c" and not x.local and x is not sl
+ for x in b.chans):
+ b.warnings.append("this board is an I2C slave AND drives other I2C parts: use a second bus "
+ "or a serial channel instead")
+ for x in b.chans:
+ if x.transport == "spi" and not x.local and x.ch.src.domain == x.ch.dst.domain == "embedded" and x.inn:
+ b.warnings.append(f"'{x.ch.id}': board-to-board SPI needs an SPI slave sketch (not generated); "
+ f"prefer i2c or serial between two boards")
+ needs_i2c = bool(b.by_role("oled", "lcd")) or any(x.transport == "i2c" and not x.local for x in b.chans)
+ needs_spi = any(x.transport == "spi" and not x.local for x in b.chans)
+ self._assign_pins(b, needs_i2c, needs_spi)
+ for x in b.chans:
+ if x.local:
+ continue
+ if x.transport == "spi":
+ x.pins["cs"] = b.spec["ss"] if b.spec["ss"] not in b.used else self._alloc(b, "digital")
+ b.used.add(x.pins["cs"])
+ if x.transport == "gpio":
+ for f in x.ch.fields:
+ x.pins[f] = self._alloc(b, "digital")
+ n = 0
+ for c in b.comps:
+ for bh in c.e.behaviors:
+ if isinstance(bh, dict) and bh.get("on") and isinstance(bh.get("do"), list):
+ b.behs.append(Beh(n, c, bh))
+ n += 1
+ return boards
+
+ # ======================================================================
+ # Name resolution (shared by C++ and MicroPython)
+ # ======================================================================
+ def _ref(self, b: Board, owner: Comp | None, n: str) -> tuple[str, str, str]:
+ """identifier -> (cpp code, python code, ctype)."""
+ n = str(n)
+ if "." in n:
+ ent, prop = n.split(".", 1)
+ ent, prop = ident(ent), ident(prop.replace(".", "_"))
+ c = next((c for c in b.comps if c.e.ident == ent or c.var == ent), None)
+ if prop.startswith(ent + "_") and (c is None or prop not in c.members):
+ prop = prop[len(ent) + 1:] # "visits.visits_count" -> visits.count
+ elif c is not None and prop not in c.members:
+ sp = self._owned_prefix(c, prop, b.comps) # "knob.visits_count" -> visits.count
+ if sp is not None:
+ m = self._member(sp[0], sp[1])
+ return f"{sp[0].var}.{m.name}", f"{sp[0].var}.{m.name}", m.ctype
+ if c is not None:
+ m = self._member(c, prop)
+ return f"{c.var}.{m.name}", f"{c.var}.{m.name}", m.ctype
+ return self._remote(b, ent, prop)
+ n = ident(n)
+ sp = self._split_owned(b, owner, n) if "_of_" in n else None
+ if sp is not None:
+ m = self._member(sp[0], sp[1])
+ return f"{sp[0].var}.{m.name}", f"{sp[0].var}.{m.name}", m.ctype
+ # another component's name wins over a same-named prop (the parser copies names it sees onto the owner)
+ other = next((c for c in b.comps if c is not owner and c.role != "board" and n in (c.e.ident, c.var)), None)
+ if owner is not None and n in owner.members and other is None:
+ m = owner.members[n]
+ return f"{owner.var}.{m.name}", f"{owner.var}.{m.name}", m.ctype
+ for c in b.comps:
+ if c.e.ident == n or c.var == n:
+ f = PRIMARY.get(c.role) or next((k for k in c.members if k != "alive"), "alive")
+ m = self._member(c, f)
+ return f"{c.var}.{m.name}", f"{c.var}.{m.name}", m.ctype
+ for c in sorted(b.comps, key=lambda c: c.role in ("generic", "board")):
+ if n in c.members:
+ m = c.members[n]
+ return f"{c.var}.{m.name}", f"{c.var}.{m.name}", m.ctype
+ for x in b.chans:
+ if x.inn and not x.local and n in x.ch.fields:
+ return self._remote(b, x.ch.src.ident, n)
+ sp = self._split_owned(b, owner, n)
+ if sp is not None:
+ m = self._member(sp[0], sp[1])
+ return f"{sp[0].var}.{m.name}", f"{sp[0].var}.{m.name}", m.ctype
+ far = self._owned_prefix(owner, n, [c for bb, c in getattr(self, "_all_comps", []) if bb is not b])
+ if far is not None: # a part on another board: only reachable through a channel
+ w = (f"'{far[0].e.name}.{far[1]}' lives on another board; connect {far[0].e.name} to this board "
+ f"to receive it (0 until then)")
+ if w not in b.warnings:
+ b.warnings.append(w)
+ return self._remote(b, far[0].e.ident, far[1])
+ target = owner or (b.comps[0] if b.comps else None)
+ if target is None:
+ return self._remote(b, "local", n)
+ m = self._member(target, n)
+ return f"{target.var}.{m.name}", f"{target.var}.{m.name}", m.ctype
+
+ @staticmethod
+ def _split_owned(b: Board, owner: Comp | None, n: str) -> tuple[Comp, str] | None:
+ """'led1.on' / 'led1_on' (dots are flattened by norm_name) -> (led1 component, 'on')."""
+ n = str(n)
+ if "." in n:
+ ent, prop = n.split(".", 1)
+ ent, prop = ident(ent), ident(prop.replace(".", "_"))
+ c = next((c for c in b.comps if c.e.ident == ent or c.var == ent), None)
+ return (c, prop) if c is not None and prop else None
+ n = ident(n)
+ mo = re.fullmatch(r"(\w+?)_of_(?:the_)?(\w+)", n) # "angle of servo" phrasing -> servo.angle
+ if mo:
+ c = next((c for c in b.comps if mo.group(2) in (c.e.ident, c.var)), None)
+ if c is not None:
+ return c, mo.group(1)
+ if owner is not None and n in owner.members:
+ return None
+ return EmbeddedModule._owned_prefix(owner, n, b.comps)
+
+ @staticmethod
+ def _owned_prefix(owner: Comp | None, n: str, comps: list) -> tuple[Comp, str] | None:
+ """'door_angle' -> (door, 'angle') when door is a component with that state/driver prop."""
+ for c in sorted(comps, key=lambda c: -len(c.e.ident)):
+ for pre in {c.e.ident, c.var}:
+ if c is not owner and n.startswith(pre + "_") and len(n) > len(pre) + 1:
+ prop = n[len(pre) + 1:]
+ if EmbeddedModule._known_prop(c, prop):
+ return c, prop
+ return None
+
+ @staticmethod
+ def _known_prop(c: Comp, prop: str) -> bool:
+ return prop in c.members or prop == PRIMARY.get(c.role) or prop in DRIVER_PROPS.get(c.role, ())
+
+ @staticmethod
+ def _baud(b: Board) -> int:
+ """Baud of the board's serial channels (the USB serial port is shared), default 115200."""
+ for x in b.chans:
+ if x.transport == "serial" and not x.local and x.ch.protocol in ("serial", "uart"):
+ v = _int(x.ch.config.get("baud"), 115200)
+ if v in (300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 74880, 115200,
+ 230400, 250000, 460800, 500000, 921600, 1000000, 2000000):
+ return v
+ return 115200
+
+ def _remote(self, b: Board, ent: str, prop: str) -> tuple[str, str, str]:
+ key = f"{ent}.{prop}"
+ var = b.remotes.setdefault(key, f"remote_{ident(ent)}_{ident(prop)}")
+ return var, f"REMOTE.get({key!r}, 0)", "float"
+
+ def _expr(self, b: Board, owner: Comp | None, e: Any, lang: str) -> str:
+ i = 0 if lang == "cpp" else 1
+ if isinstance(e, str):
+ # "when the led is on" arrives as `led == on`: compare with the state words, not a prop called 'on'
+ e = re.sub(r"(==|!=)\s*(on|high|pressed|open|detected|triggered|active|present)\b(?!\s*[.(])", r"\1 true", e)
+ e = re.sub(r"(==|!=)\s*(off|low|released|closed|inactive|absent)\b(?!\s*[.(])", r"\1 false", e)
+ try:
+ return self.expr(e, "cpp" if lang == "cpp" else "python", lambda n: self._ref(b, owner, n)[i])
+ except Exception:
+ return "0"
+
+ # ======================================================================
+ # Behaviour actions -> (cpp lines, python lines)
+ # ======================================================================
+ def _action(self, b: Board, c: Comp, a: dict) -> tuple[list[str], list[str]]:
+ op = a.get("op")
+ v = c.var
+ if op in ("set", "add"):
+ raw = str(a.get("value", "0"))
+ is_str = bool(re.fullmatch(r"\"[^\"]*\"|'[^']*'", raw.strip()))
+ is_bool = raw.strip() in ("true", "false")
+ hint = "String" if is_str else "bool" if is_bool and op == "set" else "float"
+ prop = ident(a.get("prop", "value")) or "value"
+ pre = c.e.ident + "_"
+ if prop.startswith(pre) and self._known_prop(c, prop[len(pre):]): # "increase visits count" -> visits.count
+ prop = prop[len(pre):]
+ a = dict(a, prop=prop)
+ sp = self._split_owned(b, c, a.get("prop", "value"))
+ if sp is not None: # "set led1.on to ..." -> the other component on this board
+ c, prop = sp
+ v = c.var
+ m = self._member(c, prop, hint)
+ if is_str:
+ lit = raw.strip()[1:-1]
+ ce, pe = self._cstr(lit), repr(lit)
+ else:
+ ce, pe = self._expr(b, c, raw, "cpp"), self._expr(b, c, raw, "py")
+ if m.ctype == "String":
+ if not is_str:
+ ce = f"String({ce})"
+ return ([f"{v}.{m.name} {'=' if op == 'set' else '+='} {ce};"],
+ [f"{v}.{m.name} {'=' if op == 'set' else '+='} {pe if is_str else f'str({pe})'}"])
+ if is_str:
+ note = f"cannot store text in numeric property '{prop}'"
+ return [f"// {note}"], [f"pass # {note}"]
+ if (c.role, prop) in PWM_PROPS and op == "set":
+ # "set lamp brightness to knob value": rescale a raw analog reading to the 0..255 PWM range
+ src = self._analog_src(b, raw)
+ if src is not None:
+ ce = f"(({ce}) * 255.0f / NLCL_ADC_MAX)"
+ pe = f"(({pe}) * 255 // 4095)"
+ cl, pl = [f"{v}.{m.name} = {ce};"], [f"{v}.{m.name} = {pe}"]
+ if c.role != "neopixel" and "on" in c.members:
+ # a brightness / speed above 0 means "running" (0 switches it off)
+ cl.append(f"{v}.on = {v}.{m.name} > 0;")
+ pl.append(f"{v}.on = {v}.{m.name} > 0")
+ return cl, pl
+ if op == "set":
+ return [f"{v}.{m.name} = {ce};"], [f"{v}.{m.name} = {pe}"]
+ return [f"{v}.{m.name} += {ce};"], [f"{v}.{m.name} += {pe}"]
+ if op == "toggle":
+ prop = ident(a.get("prop", "on")) or "on"
+ sp = self._split_owned(b, c, a.get("prop", "on"))
+ if sp is not None:
+ c, prop = sp
+ v = c.var
+ if prop not in c.members:
+ # "toggle the led" where led is another entity name
+ tgt = next((x for x in b.comps if x.e.ident == prop or x.var == prop), None)
+ if tgt is not None:
+ m = self._member(tgt, PRIMARY.get(tgt.role, "on"), "bool")
+ return [f"{tgt.var}.{m.name} = !{tgt.var}.{m.name};"], \
+ [f"{tgt.var}.{m.name} = not {tgt.var}.{m.name}"]
+ m = self._member(c, prop, "bool")
+ if m.ctype == "String":
+ return [f"// cannot toggle text property '{prop}'"], [f"pass # cannot toggle '{prop}'"]
+ return [f"{v}.{m.name} = !{v}.{m.name};"], [f"{v}.{m.name} = not {v}.{m.name}"]
+ if op == "destroy":
+ return [f"{v}.alive = false; // destroyed: drivers switch it off", "return;"], \
+ [f"{v}.alive = False # destroyed: drivers switch it off", "return"]
+ if op == "log":
+ return self._log(b, c, str(a.get("text", "")))
+ if op == "move":
+ cl, pl = [], []
+ for ax in ("x", "y", "z"):
+ val = str(a.get(ax, "0")).strip()
+ if val in ("0", "0.0", "-0", ""):
+ continue
+ prop = "angle" if (c.role == "servo" and ax == "x") else ax
+ m = self._member(c, prop, "float")
+ cl.append(f"{v}.{m.name} += {self._expr(b, c, val, 'cpp')};")
+ pl.append(f"{v}.{m.name} += {self._expr(b, c, val, 'py')}")
+ return (cl or ["// move: no displacement"]), (pl or ["pass"])
+ if op == "send":
+ return self._send(b, c, a.get("to"), list(a.get("fields") or []))
+ if op == "call":
+ return self._call(b, c, ident(a.get("name", "action")) or "action", list(a.get("args") or []))
+ what = self._desc(a)
+ return [f"// unsupported action: {what}"], [f"pass # unsupported action: {what}"]
+
+ @staticmethod
+ def _desc(a: Any) -> str:
+ """describe_action that never raises (hand-written IR may carry odd values)."""
+ try:
+ what = describe_action(a) if isinstance(a, dict) and "op" in a else str(a)
+ except Exception:
+ what = str(a.get("op", a) if isinstance(a, dict) else a)
+ return " ".join(what.split()).rstrip("\\")
+
+ def _analog_src(self, b: Board, raw: str) -> Comp | None:
+ """The pot / light / analog component whose raw ADC reading `raw` is (else None)."""
+ n = ident(str(raw).strip().replace(".", "_"))
+ for c in b.comps:
+ if c.role not in ("pot", "light", "analog"):
+ continue
+ f = next((k for k in c.members if k not in ("alive", "on")), "value")
+ if f in PERCENT_FIELDS:
+ continue
+ if n in (c.e.ident, c.var, f"{c.e.ident}_{f}", f"{c.var}_{f}"):
+ return c
+ return None
+
+ def _log(self, b: Board, c: Comp, text: str) -> tuple[list[str], list[str]]:
+ mo = re.fullmatch(r"\s*(['\"])(.*)\1\s+on\s+(?:the\s+)?(\w+)\s*", text, re.S)
+ scr = next((x for x in b.comps if mo and x.role in ("oled", "lcd") and mo.group(3) in (x.e.ident, x.var)), None)
+ if scr is not None:
+ # "show 'light {ldr.light}' on screen" -> the display's text, not a serial log
+ parts = re.split(r"\{([A-Za-z_][\w.]*)\}", mo.group(2))
+ ce, pe = [], []
+ for i, p in enumerate(parts):
+ if i % 2 == 0:
+ if p:
+ ce.append(f"String({self._cstr(p)})")
+ pe.append(repr(p))
+ else:
+ rc, rp, t = self._ref(b, c, p)
+ ce.append(f"String(({rc}) ? \"true\" : \"false\")" if t == "bool" else f"String({rc})")
+ pe.append(f"str({rp})")
+ tm = self._member(scr, "text", "String")
+ return ([f"{scr.var}.{tm.name} = {' + '.join(ce) or 'String()'};"],
+ [f"{scr.var}.{tm.name} = {' + '.join(pe) or repr('')}"])
+ parts = re.split(r"\{([A-Za-z_][\w.]*)\}", text)
+ cl = ["{", " String m;"]
+ pp = []
+ for i, p in enumerate(parts):
+ if i % 2 == 0:
+ if p:
+ cl.append(f" m += {self._cstr(p)};")
+ pp.append(repr(p))
+ else:
+ ce, pe, t = self._ref(b, c, p)
+ cl.append(f" m += {ce} ? \"true\" : \"false\";" if t == "bool" else f" m += String({ce});")
+ if t == "bool":
+ cl[-1] = f" m += ({ce}) ? \"true\" : \"false\";"
+ pp.append(f"str({pe})")
+ cl += [f" nlclLog({self._cstr(c.e.name)}, m);", "}"]
+ return cl, [f"nlcl_log({c.e.name!r}, {' + '.join(pp) or repr('')})"]
+
+ def _send(self, b: Board, c: Comp, to: Any, fields: list[str]) -> tuple[list[str], list[str]]:
+ outs = [x for x in b.chans if x.out]
+ mine = [x for x in outs if x.src is c] or outs
+ if to:
+ t = ident(str(to))
+ mine = [x for x in mine if t in (x.ch.dst.ident, ident(x.ch.dst.name), ident(x.ch.dst.kind), x.cid)] or mine
+ if not mine:
+ return [f"// send: {c.e.name} has no outgoing channel (connect it to something)"], \
+ ["pass # send: no outgoing channel"]
+ cl, pl = [], []
+ for x in mine:
+ flds = [ident(f) for f in fields if ident(f)] or None
+ if flds and x.transport in ("serial", "http", "mqtt", "udp") and not x.local:
+ cl += ["{"] + [" " + s for s in self._json_build_cpp(b, x, flds)] + [f" nlclTx_{x.cid}(j.str());", "}"]
+ pl.append(f"tx_{x.cid}({self._json_build_py(b, x, flds)})")
+ else:
+ cl.append(f"nlclPublish_{x.cid}();")
+ pl.append(f"publish_{x.cid}()")
+ return cl, pl
+
+ def _call(self, b: Board, c: Comp, name: str, args: list) -> tuple[list[str], list[str]]:
+ bz = c if c.role == "buzzer" else next(iter(b.by_role("buzzer")), None)
+ if name in ("beep", "alarm", "ring", "buzz") or name.startswith("play"):
+ if bz is not None:
+ pin = bz.pins.get("pin", "0")
+ f = self._member(bz, "frequency", "long", 1000)
+ return [f"tone({self._pconst(bz)}, (unsigned int){bz.var}.{f.name}, 200); // {pin}"], \
+ [f"beep(_hw_{bz.var}, {bz.var}.{f.name}, 200)"]
+ return self._log(b, c, f"{name}!")
+ if name in ("stop", "close", "open"):
+ if c.role == "servo":
+ m = self._member(c, "angle", "long")
+ val = 90 if name == "open" else 0
+ return [f"{c.var}.{m.name} = {val};"], [f"{c.var}.{m.name} = {val}"]
+ if "on" in c.members:
+ val = name == "open"
+ return [f"{c.var}.on = {'true' if val else 'false'};"], [f"{c.var}.on = {val}"]
+ return self._log(b, c, f"{name}")
+ if name == "reset":
+ cl, pl = [], []
+ for m in c.members.values():
+ cl.append(f"{c.var}.{m.name} = {self._clit(m)};")
+ pl.append(f"{c.var}.{m.name} = {self._plit(m)}")
+ return cl, pl
+ argc = len(args)
+ b.calls[name] = max(argc, b.calls.get(name, 0))
+ ca = [self._expr(b, c, x, "cpp") for x in args]
+ pa = [self._expr(b, c, x, "py") for x in args]
+ n = b.calls[name]
+ ca += ["0"] * (n - len(ca))
+ return [f"user_{name}({', '.join(ca)});"], [f"user_{name}({', '.join(pa)})"]
+
+ # ======================================================================
+ # Channel helpers
+ # ======================================================================
+ def _field_ref(self, b: Board, x: Chan, f: str) -> tuple[str, str, str]:
+ src = x.src
+ f = ident(f) or "value"
+ if src is not None and f in src.members:
+ m = src.members[f]
+ return f"{src.var}.{m.name}", f"{src.var}.{m.name}", m.ctype
+ return self._ref(b, src, f)
+
+ def _json_build_cpp(self, b: Board, x: Chan, fields: list[str]) -> list[str]:
+ L = [f"NlclJson j({self._cstr(x.ch.id)}, {self._cstr(x.ch.src.name)});"]
+ for f in fields:
+ ce, _, t = self._field_ref(b, x, f)
+ L.append(f"j.add({self._cstr(f)}, {ce});")
+ return L
+
+ def _json_build_py(self, b: Board, x: Chan, fields: list[str]) -> str:
+ items = ", ".join(f"{f!r}: {self._field_ref(b, x, f)[1]}" for f in fields)
+ return f"json.dumps({{'channel': {x.ch.id!r}, 'from': {x.ch.src.name!r}, {items}}})"
+
+ def _pconst(self, c: Comp, logical: str = "pin") -> str:
+ return f"PIN_{c.var.upper()}" + ("" if logical == "pin" else f"_{logical.upper()}")
+
+ @staticmethod
+ def _pyint(b: Board, p: str) -> str:
+ """Pin as a MicroPython GPIO number."""
+ if re.fullmatch(r"\d+", p):
+ return p
+ return "0"
+
+ # ======================================================================
+ # generate
+ # ======================================================================
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
+ import traceback
+ files: dict[str, str] = {}
+ try:
+ boards = self._plan(ctx)
+ except Exception: # never break the build of the other modules
+ return {"README.md": "# embedded\n\nFirmware planning failed (please report):\n\n```\n"
+ + traceback.format_exc() + "```\n"}
+ for b in boards:
+ d = b.ident
+ try:
+ sec = self._sections(ctx, b)
+ files[f"{d}/{d}.ino"] = self._ino(ctx, b, sec)
+ files[f"{d}/platformio.ini"] = self._pio(b)
+ if b.spec["upy"]:
+ files[f"{d}/main.py"] = self._upy(ctx, b, sec)
+ if b.spec["wokwi"]:
+ files[f"{d}/diagram.json"] = self._diagram(b)
+ files[f"{d}/wokwi.toml"] = self._wokwi_toml(b)
+ files[f"{d}/libraries.txt"] = "\n".join(sorted(self._wokwi_libs(b))) + "\n"
+ except Exception:
+ files[f"{d}/GENERATION_ERROR.txt"] = "Generating this board failed (please report):\n\n" + \
+ traceback.format_exc()
+ try:
+ files["README.md"] = self._readme(ctx, boards)
+ except Exception:
+ files["README.md"] = "# embedded\n\nREADME generation failed:\n\n```\n" + traceback.format_exc() + "```\n"
+ return files
+
+ # ----------------------------------------------------------------------
+ def _sections(self, ctx: BuildContext, b: Board) -> dict:
+ """Generate behaviour/trigger code first (it may add members & remotes)."""
+ S: dict[str, list[str]] = {k: [] for k in (
+ "beh_c", "beh_p", "trig_c", "trig_p", "glob_c", "start_c", "start_p", "chg_init_c", "chg_init_p",
+ "cmd_c", "cmd_p")}
+ update_ms = 50
+ for bh in b.behs:
+ c, rule = bh.comp, bh.b
+ desc = f"{c.e.name}: on {rule['on']}" + (f" if {rule['if']}" if rule.get("if") else "") + " -> " + \
+ "; ".join(self._desc(a) for a in rule["do"] if isinstance(a, dict))
+ desc = " ".join(desc.split()).rstrip("\\") # one line; no trailing backslash (C++ line splice)
+ S["beh_c"] += [f"// {desc}", f"void nlcl_b{bh.n}() {{", f" if (!{c.var}.alive) return;"]
+ S["beh_p"] += [f"def nlcl_b{bh.n}():", f" # {desc}", f" if not {c.var}.alive:", " return"]
+ cond = rule.get("if")
+ if cond:
+ ce, pe = self._expr(b, c, cond, "cpp"), self._expr(b, c, cond, "py")
+ edge = bh.trig == "update" and any(a.get("op") in ("log", "send", "call", "toggle", "add", "destroy")
+ for a in rule["do"] if isinstance(a, dict))
+ if edge: # fire once when the condition becomes true (avoid flooding)
+ S["beh_c"] += [" static bool was = false;", f" bool cond = ({ce});",
+ " if (!cond) { was = false; return; }", " if (was) return;", " was = true;"]
+ S["beh_p"] += [f" if not ({pe}):", f" _ST['was{bh.n}'] = False", " return",
+ f" if _ST.get('was{bh.n}'):", " return", f" _ST['was{bh.n}'] = True"]
+ else:
+ S["beh_c"].append(f" if (!({ce})) return;")
+ S["beh_p"] += [f" if not ({pe}):", " return"]
+ for a in rule["do"]:
+ if not isinstance(a, dict):
+ continue
+ cl, pl = self._action(b, c, a)
+ S["beh_c"] += [" " + s for s in cl]
+ S["beh_p"] += [" " + s for s in pl]
+ S["beh_c"] += ["}", ""]
+ S["beh_p"] += [""]
+ # ---- triggers
+ groups: dict[str, list[Beh]] = {}
+ for bh in b.behs:
+ groups.setdefault(bh.trig, []).append(bh)
+ for bh in groups.get("start", []):
+ S["start_c"].append(f"nlcl_b{bh.n}();")
+ S["start_p"].append(f"nlcl_b{bh.n}()")
+ # input: buttons / switches / serial commands
+ inputs: dict[str, list[Beh]] = {}
+ for bh in groups.get("input", []):
+ inputs.setdefault(ident(bh.arg) or "any", []).append(bh)
+ for key, lst in inputs.items():
+ calls_c = " ".join(f"nlcl_b{x.n}();" for x in lst)
+ calls_p = "; ".join(f"nlcl_b{x.n}()" for x in lst)
+ src = next((c for c in b.comps if c.role in ("button", "switch", "pir")
+ and (c.e.ident == key or c.var == key)), None) or \
+ next((c for c in b.comps if c.role in ("button", "switch", "pir")
+ and key in (ident(c.e.kind), c.role, ident(str(c.e.props.get("subtype", ""))))), None)
+ if key == "any" and src is None:
+ src = next(iter(b.by_role("button")), None)
+ if src is not None:
+ f = PRIMARY[src.role]
+ S["glob_c"] += [f"bool nlclPrev_{src.var}_{key} = false;", f"unsigned long nlclDeb_{src.var}_{key} = 0;"]
+ S["trig_c"] += [f" // input:{key} -> rising edge of {src.e.name}.{f} (debounced)",
+ f" if ({src.var}.{f} && !nlclPrev_{src.var}_{key} && now - nlclDeb_{src.var}_{key} > 40) "
+ f"{{ nlclDeb_{src.var}_{key} = now; {calls_c} }}",
+ f" nlclPrev_{src.var}_{key} = {src.var}.{f};"]
+ S["trig_p"] += [f" # input:{key} -> rising edge of {src.e.name}.{f}",
+ f" if {src.var}.{f} and not _ST.get('prev_{src.var}_{key}') "
+ f"and time.ticks_diff(now, _ST.get('deb_{src.var}_{key}', 0)) > 40:",
+ f" _ST['deb_{src.var}_{key}'] = now",
+ f" {calls_p}",
+ f" _ST['prev_{src.var}_{key}'] = {src.var}.{f}"]
+ # also reachable as a typed serial command (e.g. "space" or "button")
+ words = {key, key.replace("_", " ")}
+ if key == "space":
+ words.add(" ")
+ cond_c = " || ".join(f"cmd.equalsIgnoreCase({self._cstr(w)})" for w in sorted(words))
+ S["cmd_c"].append(f" if ({cond_c}) {{ {calls_c} return; }}")
+ S["cmd_p"] += [f" if cmd.lower() in {sorted(words)!r}:", f" {calls_p}", " return"]
+ for i, bh in enumerate(groups.get("timer", [])):
+ try:
+ ms = max(1, int(bh.arg))
+ except ValueError:
+ ms = 1000
+ S["glob_c"].append(f"unsigned long nlclT_{bh.n} = 0;")
+ S["trig_c"] += [f" if (now - nlclT_{bh.n} >= {ms}UL) {{ nlclT_{bh.n} = now; nlcl_b{bh.n}(); }} // every {ms} ms"]
+ S["trig_p"] += [f" if time.ticks_diff(now, _ST.get('t{bh.n}', 0)) >= {ms}: # every {ms} ms",
+ f" _ST['t{bh.n}'] = now", f" nlcl_b{bh.n}()"]
+ if groups.get("update"):
+ S["glob_c"].append("unsigned long nlclT_update = 0;")
+ S["trig_c"] += [f" if (now - nlclT_update >= {update_ms}UL) {{ // update behaviours ({1000 // update_ms} Hz)",
+ " nlclT_update = now;"] + [f" nlcl_b{x.n}();" for x in groups["update"]] + [" }"]
+ S["trig_p"] += [f" if time.ticks_diff(now, _ST.get('tu', 0)) >= {update_ms}:", " _ST['tu'] = now"] + \
+ [f" nlcl_b{x.n}()" for x in groups["update"]]
+ for bh in groups.get("change", []):
+ prop = str(bh.arg or "").strip() if "." in str(bh.arg or "") else (ident(bh.arg) or "value")
+ ce, pe, t = self._ref(b, bh.comp, prop)
+ S["glob_c"].append(f"{t} nlclChg_{bh.n};")
+ S["chg_init_c"].append(f"nlclChg_{bh.n} = {ce};")
+ S["chg_init_p"].append(f"_ST['chg{bh.n}'] = {pe}")
+ S["trig_c"] += [f" if ({ce} != nlclChg_{bh.n}) {{ nlclChg_{bh.n} = {ce}; nlcl_b{bh.n}(); }} // change:{prop}"]
+ S["trig_p"] += [f" if {pe} != _ST.get('chg{bh.n}'): # change:{prop}",
+ f" _ST['chg{bh.n}'] = {pe}", f" nlcl_b{bh.n}()"]
+ if groups.get("collision"):
+ ds = b.by_role("distance")
+ calls_c = " ".join(f"nlcl_b{x.n}();" for x in groups["collision"])
+ calls_p = "; ".join(f"nlcl_b{x.n}()" for x in groups["collision"])
+ if ds:
+ conds_c, conds_p = [], []
+ for dc in ds:
+ lim = dc.e.props.get("collision_cm", 10)
+ lim = lim if isinstance(lim, (int, float)) and not isinstance(lim, bool) else 10
+ conds_c.append(f"({dc.var}.distance > 0 && {dc.var}.distance < {float(lim)})")
+ conds_p.append(f"(0 < {dc.var}.distance < {float(lim)})")
+ S["glob_c"].append("bool nlclPrevCollision = false;")
+ S["trig_c"] += [" { // collision = an ultrasonic sensor sees an obstacle closer than collision_cm",
+ f" bool hit = {' || '.join(conds_c)};",
+ f" if (hit && !nlclPrevCollision) {{ {calls_c} }}",
+ " nlclPrevCollision = hit;", " }"]
+ S["trig_p"] += [f" hit = {' or '.join(conds_p)}",
+ " if hit and not _ST.get('col'):", f" {calls_p}", " _ST['col'] = hit"]
+ else:
+ S["trig_c"].append(" // collision behaviours need a distance (ultrasonic) sensor on this board")
+ S["trig_p"].append(" # collision behaviours need a distance (ultrasonic) sensor on this board")
+ return S
+
+ # ======================================================================
+ # Arduino C++
+ # ======================================================================
+ def _ino(self, ctx: BuildContext, b: Board, S: dict) -> str:
+ sp = b.spec
+ arch = sp["arch"]
+ roles = {c.role for c in b.comps}
+ net = [x for x in b.chans if not x.local and x.transport in ("http", "mqtt", "udp")]
+ uses_wifi = bool(net) and bool(b.wifi)
+ uses_mqtt = any(x.transport == "mqtt" for x in net)
+ uses_http = any(x.transport == "http" for x in net)
+ uses_udp = any(x.transport == "udp" for x in net)
+ uses_wire = bool(roles & {"oled", "lcd"}) or any(x.transport == "i2c" and not x.local for x in b.chans)
+ uses_spi = any(x.transport == "spi" and not x.local for x in b.chans)
+ bus_chans = [x for x in b.chans if not x.local and x.transport in ("i2c", "spi")]
+ L: list[str] = []
+ A = L.append
+ A(f"// {ctx.system.name} - firmware for {sp['title']} ('{b.ident}')")
+ A("// Generated by NLCL (Natural Language Computational Language). Edit freely.")
+ A("//")
+ A(f"// arduino-cli compile --fqbn {sp['fqbn']} .")
+ A("// pio run (platformio.ini next to this file)")
+ if sp["wokwi"]:
+ A("// wokwi.com paste this sketch + diagram.json + libraries.txt, press Play")
+ A("//")
+ A(f"// Serial ({self._baud(b)} baud): lines starting with '{{' are channel JSON, '#' lines are logs,")
+ A("// any other line you type is a command that fires input: behaviours.")
+ if b.warnings:
+ A("//")
+ A("// NOTES:")
+ for w in dict.fromkeys(b.warnings):
+ A(f"// - {w}")
+ A("")
+ A("#include ")
+ A("#include ")
+ # ---- optional libraries
+ opt = []
+ if roles & {"dht"}:
+ opt.append(("NLCL_USE_DHT", "DHT sensor library (Adafruit) - DHT11/DHT22", [""]))
+ b.libs.add("DHT sensor library")
+ if "servo" in roles:
+ if arch == "esp32":
+ opt.append(("NLCL_USE_SERVO", "ESP32Servo (Kevin Harrington)", [""]))
+ b.libs.add("ESP32Servo")
+ else:
+ opt.append(("NLCL_USE_SERVO", "Servo (Arduino; bundled with most cores)", [""]))
+ if arch in ("avr", "stm32"):
+ b.libs.add("Servo")
+ if "neopixel" in roles:
+ opt.append(("NLCL_USE_NEOPIXEL", "Adafruit NeoPixel", [""]))
+ b.libs.add("Adafruit NeoPixel")
+ if "oled" in roles:
+ opt.append(("NLCL_USE_OLED", "Adafruit SSD1306 + Adafruit GFX Library",
+ ["", ""]))
+ b.libs.update({"Adafruit SSD1306", "Adafruit GFX Library"})
+ if "lcd" in roles:
+ opt.append(("NLCL_USE_LCD", "LiquidCrystal I2C (Frank de Brabander)", [""]))
+ b.libs.add("LiquidCrystal I2C")
+ if uses_mqtt:
+ opt.append(("NLCL_USE_MQTT", "PubSubClient (Nick O'Leary)", [""]))
+ b.libs.add("PubSubClient")
+ if opt:
+ A("")
+ A("// ---- optional libraries: install them (see README / libraries.txt) or set the flag")
+ A("// ---- to 0 to build with only the core (the part is then simulated / disabled).")
+ for flag, lib, incs in opt:
+ A(f"#define {flag} 1 // {lib}")
+ for flag, lib, incs in opt:
+ A(f"#if {flag}")
+ for inc in incs:
+ A(f"#include {inc}")
+ A("#endif")
+ if uses_wire:
+ A("#include ")
+ if uses_spi:
+ A("#include ")
+ if uses_wifi:
+ if b.wifi == "esp8266":
+ A("#include ")
+ if uses_http:
+ A("#include ")
+ else:
+ A("#include ")
+ if uses_http:
+ A("#include ")
+ if uses_udp:
+ A("#include ")
+ ssid = b.entity.props.get("wifi_ssid") if b.entity else None
+ pw = b.entity.props.get("wifi_password") if b.entity else None
+ host = b.entity.props.get("hub_host") if b.entity else None
+ hub_port = 8765
+ for x in net:
+ if x.transport == "http":
+ try:
+ hub_port = int(str(x.ch.hub_url).rsplit(":", 1)[1].split("/")[0])
+ except (ValueError, IndexError):
+ pass
+ A("")
+ A("// ---- network (Wokwi simulator: SSID \"Wokwi-GUEST\", empty password)")
+ A(f"#define WIFI_SSID {self._cstr(ssid or 'Wokwi-GUEST')}")
+ A(f"#define WIFI_PASS {self._cstr(pw or '')}")
+ A("// HUB_HOST = the PC running the NLCL hub (`python main.py` in the python folder).")
+ A("// 'localhost' would be the board itself! Real hardware: your PC's LAN IP (ipconfig / ip addr).")
+ A("// Wokwi + private IoT gateway (VS Code): \"host.wokwi.internal\" reaches your PC.")
+ A(f"#define HUB_HOST {self._cstr(host or 'host.wokwi.internal')}")
+ A(f"#define HUB_PORT {hub_port}")
+ A("")
+ A(f"#define NLCL_ADC_MAX {sp['adc_max']}.0f // full-scale analogRead() value on this board")
+ # ---- pins
+ A("")
+ A("// ---- pins")
+ for c in b.comps:
+ for logical, p in c.pins.items():
+ how = "set by you" if logical in c.explicit else "auto"
+ A(f"const int {self._pconst(c, logical)} = {p}; // {c.e.name} ({c.role}{'' if logical == 'pin' else ' ' + logical}, {how})")
+ for x in b.chans:
+ if x.transport == "spi" and "cs" in x.pins:
+ A(f"const int PIN_CS_{x.cid.upper()} = {x.pins['cs']}; // SPI chip-select for channel {x.ch.id}")
+ if x.transport == "gpio":
+ for f, p in x.pins.items():
+ A(f"const int PIN_{x.cid.upper()}_{ident(f).upper()} = {p}; // gpio channel {x.ch.id}: field {f}")
+ if uses_wire:
+ A(f"// I2C bus: SDA={sp['i2c'][0]} SCL={sp['i2c'][1]}")
+ if uses_spi:
+ A(f"// SPI bus: SCK={sp['spi'][0]} MISO={sp['spi'][1]} MOSI={sp['spi'][2]}")
+ # ---- library objects
+ lib_lines = []
+ for c in b.comps:
+ if c.role == "dht":
+ model = "DHT11" if "dht11" in self._words(c.e) else "DHT22"
+ lib_lines += ["#if NLCL_USE_DHT", f"DHT nlclDht_{c.var}({self._pconst(c)}, {model});", "#endif"]
+ elif c.role == "servo":
+ lib_lines += ["#if NLCL_USE_SERVO", f"Servo nlclServo_{c.var};", "#endif"]
+ elif c.role == "neopixel":
+ n = c.e.props.get("pixels", 1)
+ n = n if isinstance(n, int) and not isinstance(n, bool) and n > 0 else 1
+ lib_lines += ["#if NLCL_USE_NEOPIXEL",
+ f"Adafruit_NeoPixel nlclPix_{c.var}({n}, {self._pconst(c)}, NEO_GRB + NEO_KHZ800);", "#endif"]
+ elif c.role == "oled":
+ lib_lines += ["#if NLCL_USE_OLED", f"Adafruit_SSD1306 nlclOled_{c.var}(128, 64, &Wire, -1);", "#endif"]
+ elif c.role == "lcd":
+ lib_lines += ["#if NLCL_USE_LCD", f"LiquidCrystal_I2C nlclLcd_{c.var}(0x27, 16, 2);", "#endif"]
+ if uses_mqtt:
+ lib_lines += ["#if NLCL_USE_MQTT", "WiFiClient nlclMqttNet;", "PubSubClient nlclMqtt(nlclMqttNet);", "#endif"]
+ if uses_udp:
+ lib_lines += ["WiFiUDP nlclUdp;"]
+ if lib_lines:
+ A("")
+ A("// ---- driver objects")
+ L += lib_lines
+ # channels/transport code is produced before struct emission (may add members)
+ chan_c = self._chan_cpp(b)
+ # ---- entity state
+ A("")
+ A("// ---- entity state (one struct per NLCL entity; JSON field names = member names)")
+ for c in b.comps:
+ mem = " ".join(f"{m.ctype} {m.name} = {self._clit(m)};" for m in c.members.values())
+ A(f"struct NlclS_{c.var} {{ {mem} }} {c.var}; // {c.e.kind} '{c.e.name}'")
+ if b.remotes:
+ A("")
+ A("// latest values received from other modules (\"entity.field\")")
+ for key, var in sorted(b.remotes.items()):
+ A(f"float {var} = 0; // {key}")
+ # ---- helpers
+ L += self._cpp_helpers(b, uses_wifi, uses_http, uses_mqtt, uses_udp)
+ # ---- prototypes
+ A("")
+ A("// ---- prototypes")
+ for bh in b.behs:
+ A(f"void nlcl_b{bh.n}();")
+ for name, n in sorted(b.calls.items()):
+ A(f"void user_{name}({', '.join('float a' + str(i) for i in range(n))});")
+ for x in b.chans:
+ if x.out:
+ A(f"void nlclPublish_{x.cid}();")
+ if x.inn and not x.local:
+ A(f"void nlclRecv_{x.cid}(const String& msg);")
+ A("void nlclCommand(const String& cmd);")
+ # ---- globals for triggers
+ if S["glob_c"]:
+ A("")
+ A("// ---- trigger state")
+ L += S["glob_c"]
+ L += chan_c
+ # ---- behaviours
+ A("")
+ A("// ======================================================================")
+ A("// behaviours")
+ A("// ======================================================================")
+ L += S["beh_c"]
+ for name, n in sorted(b.calls.items()):
+ args = ", ".join("float a" + str(i) for i in range(n))
+ A(f"// '{name}' was requested by a behaviour: put your own code here.")
+ A(f"void user_{name}({args}) {{")
+ for i in range(n):
+ A(f" (void)a{i};")
+ A(f" nlclLog(\"call\", \"{name}()\");")
+ A("}")
+ A("")
+ A("// typed serial commands -> input: behaviours")
+ A("void nlclCommand(const String& cmd) {")
+ L += S["cmd_c"] or [" (void)cmd;"]
+ A("}")
+ # ---- inputs / outputs
+ L += self._io_cpp(b)
+ # ---- triggers
+ A("")
+ A("void nlclTriggers(unsigned long now) {")
+ L += S["trig_c"] or [" (void)now;"]
+ A("}")
+ # ---- setup / loop
+ A("")
+ A("void setup() {")
+ A(f" Serial.begin({self._baud(b)});")
+ if arch == "rp2040":
+ A(" { unsigned long t0 = millis(); while (!Serial && millis() - t0 < 1500) delay(10); } // USB serial")
+ A(f" Serial.println(\"# {b.ident}: NLCL firmware for {sp['title']} starting\");")
+ L += [" " + s for s in self._setup_cpp(b, uses_wire, uses_spi, uses_wifi, uses_mqtt, uses_udp)]
+ if S["start_c"]:
+ A(" // start behaviours")
+ L += [" " + s for s in S["start_c"]]
+ L += [" " + s for s in S["chg_init_c"]]
+ A("}")
+ A("")
+ A("void loop() {")
+ A(" unsigned long now = millis();")
+ A(" nlclReadInputs(now); // sensors, buttons")
+ A(" nlclPollSerial(); // serial JSON channels + typed commands")
+ A(" nlclComms(now); // network / bus channels: receive + periodic publish")
+ A(" nlclTriggers(now); // behaviours")
+ A(" nlclWriteOutputs(now); // leds, motors, servos, displays ...")
+ A("}")
+ return "\n".join(L) + "\n"
+
+ def _cpp_helpers(self, b: Board, wifi: bool, http: bool, mqtt: bool, udp: bool) -> list[str]:
+ L = ["", "// ---- helpers", "String nlclLastLog;",
+ "void nlclLog(const char* who, const String& msg) {",
+ " nlclLastLog = msg;",
+ " Serial.print(\"# \"); Serial.print(who); Serial.print(\": \"); Serial.println(msg);",
+ "}",
+ "",
+ "// Flat JSON builder: {\"channel\":\"id\",\"from\":\"name\",\"field\":value,...}",
+ "struct NlclJson {",
+ " String s;",
+ " NlclJson(const char* ch, const char* from) {",
+ " s = \"{\\\"channel\\\":\\\"\"; s += ch; s += \"\\\",\\\"from\\\":\\\"\"; s += from; s += \"\\\"\";",
+ " }",
+ " void key(const char* k) { s += \",\\\"\"; s += k; s += \"\\\":\"; }",
+ " void add(const char* k, bool v) { key(k); s += v ? \"true\" : \"false\"; }",
+ " void add(const char* k, int v) { key(k); s += String(v); }",
+ " void add(const char* k, long v) { key(k); s += String(v); }",
+ " void add(const char* k, float v) { key(k); if (isnan(v) || isinf(v)) s += \"null\"; else s += String(v, 3); }",
+ " void add(const char* k, const String& v) {",
+ " key(k); s += '\"';",
+ " for (unsigned i = 0; i < v.length(); i++) { char c = v[i]; if (c == '\"' || c == '\\\\') s += '\\\\'; s += c; }",
+ " s += '\"';",
+ " }",
+ " String str() const { return s + \"}\"; }",
+ "};",
+ "",
+ "// Minimal flat-JSON reader (no ArduinoJson needed): raw value of \"key\" (strings unquoted).",
+ "bool nlclJsonGet(const String& m, const char* key, String& out) {",
+ " String k = String(\"\\\"\") + key + \"\\\"\";",
+ " int i = m.indexOf(k);",
+ " while (i >= 0) {",
+ " int j = i + k.length();",
+ " int n = m.length();",
+ " while (j < n && m[j] == ' ') j++;",
+ " if (j < n && m[j] == ':') {",
+ " j++;",
+ " while (j < n && m[j] == ' ') j++;",
+ " if (j < n && m[j] == '\"') {",
+ " out = \"\";",
+ " for (int e = j + 1; e < n && m[e] != '\"'; e++) { if (m[e] == '\\\\' && e + 1 < n) e++; out += m[e]; }",
+ " return true;",
+ " }",
+ " int e = j;",
+ " while (e < n && m[e] != ',' && m[e] != '}') e++;",
+ " out = m.substring(j, e); out.trim();",
+ " return true;",
+ " }",
+ " i = m.indexOf(k, i + 1);",
+ " }",
+ " return false;",
+ "}",
+ "float nlclNum(const String& v) { if (v == \"true\") return 1; if (v == \"false\" || v == \"null\") return 0; return v.toFloat(); }",
+ "bool nlclBool(const String& v) { return v == \"true\" || (v != \"false\" && v.toFloat() != 0); }",
+ "int16_t nlclI16(float v) { if (v > 32767) v = 32767; if (v < -32768) v = -32768; return (int16_t)(v >= 0 ? v + 0.5f : v - 0.5f); }",
+ ]
+ if b.by_role("neopixel"):
+ L += ["",
+ "// colour name or #rrggbb -> 0xRRGGBB",
+ "uint32_t nlclColor(const String& c) {",
+ " if (c.startsWith(\"#\") && c.length() == 7) return (uint32_t)strtol(c.c_str() + 1, NULL, 16);"]
+ for nm, (r, g, bb) in COLORS.items():
+ L.append(f" if (c.equalsIgnoreCase(\"{nm}\")) return 0x{r:02X}{g:02X}{bb:02X}UL;")
+ L += [" return 0xFFFFFFUL;", "}"]
+ if wifi:
+ L += ["",
+ "// WiFi: never blocks for long; reconnects in the background.",
+ "bool nlclWifiUp() {",
+ " static unsigned long last = 0;",
+ " if (WiFi.status() == WL_CONNECTED) return true;",
+ " if (last != 0 && millis() - last < 10000UL) return false;",
+ " last = millis();",
+ " WiFi.begin(WIFI_SSID, WIFI_PASS);",
+ " return false;",
+ "}"]
+ if http:
+ L += ["",
+ "// NLCL hub: POST /channel/ stores the latest message, GET returns it (with \"_t\").",
+ "String nlclUrl(const char* path) { return String(\"http://\") + HUB_HOST + \":\" + String(HUB_PORT) + path; }",
+ "void nlclHttpPost(const char* path, const String& body) {",
+ " if (WiFi.status() != WL_CONNECTED) return;",
+ " WiFiClient client;",
+ " HTTPClient http;",
+ " http.setTimeout(2000);",
+ "#if defined(ESP32)",
+ " http.setConnectTimeout(1500);",
+ "#endif",
+ " if (!http.begin(client, nlclUrl(path))) return;",
+ " http.addHeader(\"Content-Type\", \"application/json\");",
+ " http.POST(body);",
+ " http.end();",
+ "}",
+ "String nlclHttpGet(const char* path) {",
+ " if (WiFi.status() != WL_CONNECTED) return String();",
+ " WiFiClient client;",
+ " HTTPClient http;",
+ " http.setTimeout(2000);",
+ "#if defined(ESP32)",
+ " http.setConnectTimeout(1500);",
+ "#endif",
+ " if (!http.begin(client, nlclUrl(path))) return String();",
+ " int code = http.GET();",
+ " String r = code == 200 ? http.getString() : String();",
+ " http.end();",
+ " return r;",
+ "}"]
+ return L
+
+ def _chan_cpp(self, b: Board) -> list[str]:
+ L = ["", "// ======================================================================",
+ "// channels", "// ======================================================================"]
+ if not b.chans:
+ L.append("// (no channels)")
+ mqtt_in = [x for x in b.chans if x.inn and not x.local and x.transport == "mqtt"]
+ for x in b.chans:
+ ch = x.ch
+ L.append(f"// {ch.id}: {ch.src.name} ({ch.src.domain}) -> {ch.dst.name} ({ch.dst.domain}) via "
+ f"{x.transport}{' (local)' if x.local else ''}; fields: {', '.join(ch.fields)}")
+ if x.note:
+ L.append(f"// NOTE: {x.note}")
+ if x.out and x.local:
+ L.append(f"void nlclPublish_{x.cid}() {{ // both ends on this board: copy directly")
+ for f in ch.fields:
+ ce, _, t = self._field_ref(b, x, f)
+ if x.dst is not None:
+ dm = self._member(x.dst, f, t)
+ if ce == f"{x.dst.var}.{dm.name}":
+ L.append(f" // {f}: '{ch.src.name}' has no such property (nothing to copy)")
+ else:
+ L.append(f" {x.dst.var}.{dm.name} = {ce};")
+ L += [f" {s}" for s in self._msg_calls_cpp(b, x)]
+ L.append("}")
+ continue
+ if x.out:
+ if x.transport in ("serial", "http", "mqtt", "udp"):
+ L.append(f"void nlclTx_{x.cid}(const String& line) {{")
+ if x.transport == "serial":
+ L.append(" Serial.println(line);")
+ elif x.transport == "http":
+ L.append(f" nlclHttpPost({self._cstr(ch.config.get('path', '/channel/' + ch.id))}, line);")
+ elif x.transport == "mqtt":
+ L += ["#if NLCL_USE_MQTT",
+ f" if (nlclMqtt.connected()) nlclMqtt.publish({self._cstr(ch.topic)}, line.c_str());",
+ "#else", " Serial.println(line); // MQTT library disabled: fall back to serial", "#endif"]
+ elif x.transport == "udp":
+ L += [" if (WiFi.status() != WL_CONNECTED) return;",
+ f" nlclUdp.beginPacket(HUB_HOST, {_int(ch.config.get('port'), 9876)});",
+ " nlclUdp.print(line);", " nlclUdp.endPacket();"]
+ L.append("}")
+ L.append(f"void nlclPublish_{x.cid}() {{")
+ L += [" " + s for s in self._json_build_cpp(b, x, ch.fields)]
+ L += [f" nlclTx_{x.cid}(j.str());", "}"]
+ elif x.transport in ("i2c", "spi"):
+ n = len(ch.fields)
+ L.append(f"// byte frame: 0x{FRAME_SYNC:02X}, {n}, then {n} x int16 big-endian "
+ f"({', '.join(ch.fields)}; rounded, true=1)")
+ L.append(f"void nlclPublish_{x.cid}() {{")
+ vals = ", ".join(f"nlclI16({self._num(self._field_ref(b, x, f))})" for f in ch.fields)
+ L.append(f" int16_t v[{n}] = {{{vals}}};")
+ if x.transport == "i2c":
+ L += [f" Wire.beginTransmission({self._i2c_addr(ch)});",
+ f" Wire.write((uint8_t)0x{FRAME_SYNC:02X});", f" Wire.write((uint8_t){n});",
+ f" for (int i = 0; i < {n}; i++) {{ Wire.write((uint8_t)((uint16_t)v[i] >> 8)); "
+ "Wire.write((uint8_t)(v[i] & 0xFF)); }",
+ " Wire.endTransmission();"]
+ else:
+ L += [" SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));",
+ f" digitalWrite(PIN_CS_{x.cid.upper()}, LOW);",
+ f" SPI.transfer((uint8_t)0x{FRAME_SYNC:02X});", f" SPI.transfer((uint8_t){n});",
+ f" for (int i = 0; i < {n}; i++) {{ SPI.transfer((uint8_t)((uint16_t)v[i] >> 8)); "
+ "SPI.transfer((uint8_t)(v[i] & 0xFF)); }",
+ f" digitalWrite(PIN_CS_{x.cid.upper()}, HIGH);",
+ " SPI.endTransaction();"]
+ L.append("}")
+ elif x.transport == "gpio":
+ L.append(f"void nlclPublish_{x.cid}() {{ // one pin per field: HIGH when value != 0")
+ for f in ch.fields:
+ L.append(f" digitalWrite(PIN_{x.cid.upper()}_{ident(f).upper()}, "
+ f"({self._num(self._field_ref(b, x, f))}) != 0 ? HIGH : LOW);")
+ L.append("}")
+ if x.inn:
+ L += self._recv_cpp(b, x)
+ if mqtt_in:
+ L += ["#if NLCL_USE_MQTT",
+ "void nlclMqttCallback(char* topic, byte* payload, unsigned int len) {",
+ " String msg; msg.reserve(len);",
+ " for (unsigned int i = 0; i < len; i++) msg += (char)payload[i];",
+ " String t(topic);"]
+ for x in mqtt_in:
+ L.append(f" if (t == {self._cstr(x.ch.topic)}) nlclRecv_{x.cid}(msg);")
+ L += ["}", "#endif"]
+ # serial line dispatcher
+ ser_in = [x for x in b.chans if x.inn and not x.local and x.transport == "serial"]
+ L += ["", "// serial: newline-terminated JSON for channels, anything else is a command",
+ "String nlclSerialBuf;",
+ "void nlclHandleLine(String line) {",
+ " line.trim();",
+ " if (line.length() == 0) return;",
+ " String ch;",
+ " if (line[0] == '{' && nlclJsonGet(line, \"channel\", ch)) {"]
+ for x in ser_in:
+ L.append(f" if (ch == {self._cstr(x.ch.id)}) nlclRecv_{x.cid}(line);")
+ L += [" return;", " }", " nlclCommand(line);", "}",
+ "void nlclPollSerial() {",
+ " while (Serial.available() > 0) {",
+ " char c = (char)Serial.read();",
+ " if (c == '\\n' || c == '\\r') { if (nlclSerialBuf.length()) nlclHandleLine(nlclSerialBuf); nlclSerialBuf = \"\"; }",
+ " else if (nlclSerialBuf.length() < 300) nlclSerialBuf += c;",
+ " }",
+ "}"]
+ # comms (polling + periodic publish)
+ L += ["", "void nlclComms(unsigned long now) {"]
+ body = []
+ if any(not x.local and x.transport in ("http", "mqtt", "udp") for x in b.chans) and b.wifi:
+ body.append("bool up = nlclWifiUp();")
+ if any(x.transport == "mqtt" and not x.local for x in b.chans):
+ body += ["#if NLCL_USE_MQTT",
+ "static unsigned long lastTry = 0;",
+ "if (up && !nlclMqtt.connected() && (lastTry == 0 || now - lastTry > 5000UL)) {",
+ " lastTry = now;",
+ " String id = String(\"nlcl-\") + String((unsigned long)random(0xFFFFFF), HEX);",
+ " if (nlclMqtt.connect(id.c_str())) {"]
+ for x in mqtt_in:
+ body.append(f" nlclMqtt.subscribe({self._cstr(x.ch.topic)});")
+ body += [" }", "}", "if (up) nlclMqtt.loop();", "#endif"]
+ if any(x.transport == "udp" and x.inn and not x.local for x in b.chans):
+ body += ["if (up) {",
+ " int n = nlclUdp.parsePacket();",
+ " if (n > 0) {",
+ " char buf[300]; int r = nlclUdp.read(buf, sizeof(buf) - 1); if (r < 0) r = 0; buf[r] = 0;",
+ " String m(buf); String ch;",
+ " if (nlclJsonGet(m, \"channel\", ch)) {"]
+ for x in b.chans:
+ if x.transport == "udp" and x.inn and not x.local:
+ body.append(f" if (ch == {self._cstr(x.ch.id)}) nlclRecv_{x.cid}(m);")
+ body += [" }", " }", "}"]
+ body.append("(void)up;")
+ for x in b.chans:
+ iv = max(1, _int(x.ch.config.get("interval_ms"), 1000))
+ if x.inn and not x.local and x is self._i2c_slave(b):
+ body += [f"nlclPoll_{x.cid}(); // I2C slave: handle data received in the interrupt"]
+ elif x.inn and not x.local and x.transport in ("http", "i2c", "spi", "gpio"):
+ body += [f"{{ static unsigned long t = 0; if (now - t >= {iv}UL) {{ t = now; nlclPoll_{x.cid}(); }} }}"]
+ if x.out:
+ body += [f"{{ static unsigned long t = 0; if (now - t >= {iv}UL) {{ t = now; nlclPublish_{x.cid}(); }} }}"
+ f" // {x.ch.id} every {iv} ms"]
+ L += [" " + s if not s.startswith("#") else s for s in body] or [" (void)now;"]
+ if not body:
+ pass
+ L.append(" (void)now;")
+ L.append("}")
+ return L
+
+ @staticmethod
+ def _num(ref: tuple[str, str, str]) -> str:
+ code, _, t = ref
+ return "0" if t == "String" else f"(float)({code})"
+
+ @staticmethod
+ def _i2c_slave(b: Board):
+ """Inbound I2C channel from another board: this board must be the I2C *slave* (both masters can't talk)."""
+ return next((x for x in b.chans if x.inn and not x.out and not x.local and x.transport == "i2c"
+ and x.ch.src.domain == "embedded"), None)
+
+ @staticmethod
+ def _i2c_addr(ch: Channel) -> str:
+ a = ch.config.get("address", "0x42")
+ try:
+ v = int(str(a), 0)
+ except ValueError:
+ v = 0x42
+ return f"0x{max(8, min(0x77, v)):02X}"
+
+ def _msg_calls_cpp(self, b: Board, x: Chan) -> list[str]:
+ out = []
+ for bh in b.behs:
+ if bh.trig != "message":
+ continue
+ arg = ident(bh.arg)
+ if arg in (x.ch.src.ident, x.cid, ident(x.ch.src.kind)) or (arg == "any" and x.dst is bh.comp):
+ out.append(f"nlcl_b{bh.n}(); // message:{bh.arg}")
+ return out
+
+ def _recv_cpp(self, b: Board, x: Chan) -> list[str]:
+ ch = x.ch
+ L = []
+ if x.transport in ("serial", "http", "mqtt", "udp"):
+ L += [f"void nlclRecv_{x.cid}(const String& msg) {{", " String v;"]
+ for f in ch.fields:
+ key = f"{ch.src.ident}.{ident(f)}"
+ var = b.remotes.setdefault(key, f"remote_{ch.src.ident}_{ident(f)}")
+ line = f" if (nlclJsonGet(msg, {self._cstr(f)}, v)) {{ {var} = nlclNum(v);"
+ if x.dst is not None and ident(f) in x.dst.members:
+ m = x.dst.members[ident(f)]
+ conv = {"bool": "nlclBool(v)", "long": "(long)nlclNum(v)", "float": "nlclNum(v)",
+ "String": "v"}[m.ctype]
+ line += f" {x.dst.var}.{m.name} = {conv};"
+ L.append(line + " }")
+ L += [f" {s}" for s in self._msg_calls_cpp(b, x)]
+ L.append("}")
+ if x.transport == "http":
+ L += [f"String nlclLastT_{x.cid};",
+ f"void nlclPoll_{x.cid}() {{ // GET latest message from the hub; act only on new ones",
+ f" String r = nlclHttpGet({self._cstr(ch.config.get('path', '/channel/' + ch.id))});",
+ " String t;",
+ f" if (r.length() > 2 && nlclJsonGet(r, \"_t\", t) && t != nlclLastT_{x.cid}) "
+ f"{{ nlclLastT_{x.cid} = t; nlclRecv_{x.cid}(r); }}",
+ "}"]
+ return L
+ # bus receivers: values arrive as int16 frames / pin levels
+ n = len(ch.fields)
+ L.append(f"void nlclStore_{x.cid}(const int16_t* v) {{")
+ for i, f in enumerate(ch.fields):
+ key = f"{ch.src.ident}.{ident(f)}"
+ var = b.remotes.setdefault(key, f"remote_{ch.src.ident}_{ident(f)}")
+ line = f" {var} = v[{i}];"
+ if x.dst is not None and ident(f) in x.dst.members:
+ m = x.dst.members[ident(f)]
+ if m.ctype == "String":
+ line += f" {x.dst.var}.{m.name} = String(v[{i}]);"
+ elif m.ctype == "bool":
+ line += f" {x.dst.var}.{m.name} = v[{i}] != 0;"
+ else:
+ line += f" {x.dst.var}.{m.name} = v[{i}];"
+ L.append(line)
+ L += [f" {s}" for s in self._msg_calls_cpp(b, x)]
+ L.append("}")
+ if x is self._i2c_slave(b):
+ k = max(n, 1)
+ return L + [
+ f"// I2C slave at {self._i2c_addr(ch)}: the other board writes 0x{FRAME_SYNC:02X}, {n}, "
+ f"{n} x int16 big-endian (field order)",
+ f"volatile int16_t nlclI2cIn_{x.cid}[{k}];",
+ f"volatile bool nlclI2cNew_{x.cid} = false;",
+ f"void nlclI2cRx_{x.cid}(int count) {{ // runs in the I2C interrupt: copy bytes only",
+ " (void)count;",
+ " int i = 0;",
+ f" if (Wire.available() < 2 || Wire.read() != 0x{FRAME_SYNC:02X}) {{ while (Wire.available()) "
+ "Wire.read(); return; }",
+ " Wire.read(); // count",
+ f" while (Wire.available() >= 2 && i < {k}) {{ uint16_t hi = Wire.read(); uint16_t lo = Wire.read(); "
+ f"nlclI2cIn_{x.cid}[i++] = (int16_t)((hi << 8) | lo); }}",
+ " while (Wire.available()) Wire.read();",
+ f" nlclI2cNew_{x.cid} = true;",
+ "}",
+ f"void nlclPoll_{x.cid}() {{",
+ f" if (!nlclI2cNew_{x.cid}) return;",
+ f" int16_t v[{k}];",
+ f" noInterrupts(); for (int i = 0; i < {k}; i++) v[i] = nlclI2cIn_{x.cid}[i]; "
+ f"nlclI2cNew_{x.cid} = false; interrupts();",
+ f" nlclStore_{x.cid}(v);",
+ "}"]
+ L.append(f"void nlclPoll_{x.cid}() {{")
+ L.append(f" int16_t v[{max(n, 1)}] = {{0}};")
+ if x.transport == "i2c":
+ L += [f" // read request: the slave answers 0x{FRAME_SYNC:02X}, {n}, {n} x int16 big-endian",
+ f" uint8_t got = Wire.requestFrom((uint8_t){self._i2c_addr(ch)}, (uint8_t){2 + 2 * n});",
+ f" if (got < {2 + 2 * n} || Wire.read() != 0x{FRAME_SYNC:02X}) "
+ "{ while (Wire.available()) Wire.read(); return; }",
+ " Wire.read(); // count",
+ f" for (int i = 0; i < {n}; i++) {{ uint16_t hi = Wire.read(); uint16_t lo = Wire.read(); v[i] = (int16_t)((hi << 8) | lo); }}"]
+ elif x.transport == "spi":
+ L += [f" // read request 0x{FRAME_READ:02X}, then clock {1 + 2 * n} bytes: 0x{FRAME_SYNC:02X}, "
+ f"{n} x int16 big-endian",
+ " SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));",
+ f" digitalWrite(PIN_CS_{x.cid.upper()}, LOW);",
+ f" SPI.transfer((uint8_t)0x{FRAME_READ:02X});",
+ " uint8_t sync = SPI.transfer(0);",
+ f" for (int i = 0; i < {n}; i++) {{ uint16_t hi = SPI.transfer(0); uint16_t lo = SPI.transfer(0); v[i] = (int16_t)((hi << 8) | lo); }}",
+ f" digitalWrite(PIN_CS_{x.cid.upper()}, HIGH);",
+ " SPI.endTransaction();",
+ f" if (sync != 0x{FRAME_SYNC:02X}) return;"]
+ else: # gpio
+ L += [f" static int16_t last[{max(n, 1)}] = {{0}}; bool changed = false;"]
+ for i, f in enumerate(ch.fields):
+ L.append(f" v[{i}] = digitalRead(PIN_{x.cid.upper()}_{ident(f).upper()}) == HIGH ? 1 : 0;")
+ L += [f" for (int i = 0; i < {n}; i++) {{ if (v[i] != last[i]) changed = true; last[i] = v[i]; }}",
+ " if (!changed) return;"]
+ L += [f" nlclStore_{x.cid}(v);", "}"]
+ return L
+
+ # ---- drivers -----------------------------------------------------------
+ def _io_cpp(self, b: Board) -> list[str]:
+ R = ["", "// ======================================================================",
+ "// drivers", "// ======================================================================",
+ "void nlclReadInputs(unsigned long now) {"]
+ rd = []
+ for c in b.comps:
+ v, P = c.var, self._pconst(c)
+ if c.role == "button":
+ rd.append(f"{v}.pressed = digitalRead({P}) == LOW; // INPUT_PULLUP: pressed connects to GND")
+ elif c.role == "switch":
+ rd.append(f"{v}.on = digitalRead({P}) == LOW;")
+ elif c.role == "pir":
+ rd.append(f"{v}.motion = digitalRead({P}) == HIGH;")
+ elif c.role == "temp":
+ rd += [f"{{ // {c.e.name}: NTC thermistor divider (beta 3950), as wired in Wokwi",
+ f" float raw = analogRead({P});",
+ f" if (raw > 0 && raw < NLCL_ADC_MAX) {v}.temperature = 1.0f / (log(1.0f / (NLCL_ADC_MAX / raw - 1.0f)) / 3950.0f + 1.0f / 298.15f) - 273.15f;",
+ f" // LM35 instead: {v}.temperature = raw * (VREF / NLCL_ADC_MAX) * 100.0f;",
+ "}"]
+ elif c.role == "dht":
+ rd += [f"{{ static unsigned long t = 0; if (t == 0 || now - t >= 2000UL) {{ t = now; // DHT: max 0.5 Hz",
+ "#if NLCL_USE_DHT",
+ f" float tc = nlclDht_{v}.readTemperature(), h = nlclDht_{v}.readHumidity();",
+ f" if (!isnan(tc)) {v}.temperature = tc;",
+ f" if (!isnan(h)) {v}.humidity = h;",
+ "#else",
+ f" {v}.temperature = 22.0f + 3.0f * sin(now / 20000.0f); // simulated (library disabled)",
+ f" {v}.humidity = 50.0f + 10.0f * sin(now / 30000.0f);",
+ "#endif",
+ "} }"]
+ elif c.role == "distance":
+ T, E = self._pconst(c, "trig"), self._pconst(c, "echo")
+ rd += [f"{{ static unsigned long t = 0; if (now - t >= 60UL) {{ t = now; // HC-SR04",
+ f" digitalWrite({T}, LOW); delayMicroseconds(2);",
+ f" digitalWrite({T}, HIGH); delayMicroseconds(10); digitalWrite({T}, LOW);",
+ f" unsigned long us = pulseIn({E}, HIGH, 30000UL);",
+ f" if (us > 0) {v}.distance = us / 58.0f; // cm",
+ "} }"]
+ elif c.role in ("light", "pot", "analog"):
+ f = next((k for k in c.members if k != "alive" and k not in ("on",)), "value")
+ m = c.members[f]
+ if m.ctype == "String":
+ rd.append(f"{v}.{m.name} = String(analogRead({P}));")
+ elif m.ctype == "bool":
+ rd.append(f"{v}.{m.name} = analogRead({P}) > NLCL_ADC_MAX / 2;")
+ elif f in PERCENT_FIELDS:
+ rd.append(f"{v}.{m.name} = analogRead({P}) * 100.0f / NLCL_ADC_MAX; // 0..100 % "
+ f"(capacitive soil probes read high when dry: use 100 - ... for those)")
+ else:
+ rd.append(f"{v}.{m.name} = analogRead({P}); // 0..{b.spec['adc_max']}")
+ R += [" " + s if not s.startswith("#") else s for s in rd] or []
+ R += [" (void)now;", "}", "", "void nlclWriteOutputs(unsigned long now) {"]
+ wr = []
+ for c in b.comps:
+ v, P = c.var, self._pconst(c)
+ if c.role in ("led", "relay"):
+ if c.role == "led" and "brightness" in c.members:
+ br = c.members["brightness"]
+ val = f"(int){v}.{br.name}" if br.ctype != "String" else "255"
+ wr.append(f"analogWrite({P}, ({v}.alive && {v}.on) ? constrain({val}, 0, 255) : 0);")
+ else:
+ wr.append(f"digitalWrite({P}, ({v}.alive && {v}.on) ? HIGH : LOW);")
+ elif c.role in ("motor", "fan"):
+ sp_ = c.members.get("speed")
+ val = f"(int){v}.{sp_.name}" if sp_ and sp_.ctype != "String" else "255"
+ wr.append(f"analogWrite({P}, ({v}.alive && {v}.on) ? constrain({val}, 0, 255) : 0); // PWM to a driver/transistor")
+ elif c.role == "servo":
+ am = c.members["angle"]
+ wr += [f"{{ static int last = -1; int a = {v}.alive ? constrain((int){v}.{am.name}, 0, 180) : last;",
+ " if (a != last) { last = a;",
+ "#if NLCL_USE_SERVO",
+ f" nlclServo_{v}.write(a);",
+ "#endif",
+ " } }"]
+ elif c.role == "buzzer":
+ fm = c.members["frequency"]
+ fq = f"(unsigned int){v}.{fm.name}" if fm.ctype != "String" else "1000U"
+ wr += [f"{{ static bool last = false; bool s = {v}.alive && {v}.on;",
+ f" if (s != last) {{ last = s; if (s) tone({P}, {fq}); else noTone({P}); }} }}"]
+ elif c.role == "neopixel":
+ col, br = c.members["color"], c.members["brightness"]
+ colv = f"{v}.{col.name}" if col.ctype == "String" else "String(\"white\")"
+ brv = f"(int){v}.{br.name}" if br.ctype != "String" else "50"
+ wr += ["#if NLCL_USE_NEOPIXEL",
+ f"{{ static uint32_t last = 0xFFFFFFFFUL; uint32_t col = ({v}.alive && {v}.on) ? nlclColor({colv}) : 0;",
+ f" uint32_t key = col ^ ((uint32_t)constrain({brv}, 0, 255) << 24);",
+ f" if (key != last) {{ last = key; nlclPix_{v}.setBrightness(constrain({brv}, 0, 255));",
+ f" nlclPix_{v}.fill(col); nlclPix_{v}.show(); }} }}",
+ "#endif"]
+ elif c.role in ("oled", "lcd"):
+ tm = c.members["text"]
+ txt = f"{v}.{tm.name}" if tm.ctype == "String" else f"String({v}.{tm.name})"
+ lines = [f"String l1 = {txt}.length() ? {txt} : nlclLastLog;"]
+ shown = [s for s in b.comps if s.role in ("temp", "dht", "distance", "light", "pot", "analog", "pir")][:3]
+ rows = []
+ for s in shown:
+ for f, m in s.members.items():
+ if f == "alive" or m.ctype == "String":
+ continue
+ rows.append((f"{s.e.name[:8]} {f[:4]}", f"{s.var}.{m.name}"))
+ rows = rows[:3]
+ if c.role == "oled":
+ wr += ["#if NLCL_USE_OLED",
+ f"{{ static unsigned long t = 0; if (now - t >= 500UL) {{ t = now;",
+ f" {lines[0]}",
+ f" nlclOled_{v}.clearDisplay(); nlclOled_{v}.setTextSize(1); nlclOled_{v}.setTextColor(SSD1306_WHITE);",
+ f" nlclOled_{v}.setCursor(0, 0); nlclOled_{v}.println(l1);"]
+ for lab, code in rows:
+ wr.append(f" nlclOled_{v}.print(\"{lab}: \"); nlclOled_{v}.println({code});")
+ wr += [f" nlclOled_{v}.display();", "} }", "#endif"]
+ else:
+ wr += ["#if NLCL_USE_LCD",
+ f"{{ static unsigned long t = 0; if (now - t >= 500UL) {{ t = now;",
+ f" {lines[0]}",
+ f" nlclLcd_{v}.clear(); nlclLcd_{v}.setCursor(0, 0); nlclLcd_{v}.print(l1.substring(0, 16));"]
+ if rows:
+ lab, code = rows[0]
+ wr.append(f" nlclLcd_{v}.setCursor(0, 1); nlclLcd_{v}.print(String(\"{lab[:9]}:\") + String({code}));")
+ wr += ["} }", "#endif"]
+ R += [" " + s if not s.startswith("#") else s for s in wr]
+ R += [" (void)now;", "}"]
+ return R
+
+ def _setup_cpp(self, b: Board, wire: bool, spi: bool, wifi: bool, mqtt: bool, udp: bool) -> list[str]:
+ L = []
+ for c in b.comps:
+ v, P = c.var, self._pconst(c)
+ r = c.role
+ if r in ("led", "relay", "motor", "fan", "buzzer", "neopixel"):
+ L.append(f"pinMode({P}, OUTPUT);")
+ elif r in ("button", "switch"):
+ L.append(f"pinMode({P}, INPUT_PULLUP);")
+ elif r == "pir":
+ L.append(f"pinMode({P}, INPUT);")
+ elif r == "distance":
+ L += [f"pinMode({self._pconst(c, 'trig')}, OUTPUT);", f"pinMode({self._pconst(c, 'echo')}, INPUT);"]
+ elif r == "dht":
+ L += ["#if NLCL_USE_DHT", f"nlclDht_{v}.begin();", "#endif"]
+ elif r == "servo":
+ L += ["#if NLCL_USE_SERVO", f"nlclServo_{v}.attach({P});", "#endif"]
+ for c in b.comps:
+ if c.role == "neopixel":
+ L += ["#if NLCL_USE_NEOPIXEL", f"nlclPix_{c.var}.begin();", "#endif"]
+ slave = self._i2c_slave(b)
+ if slave is not None:
+ addr = self._i2c_addr(slave.ch)
+ if b.spec["arch"] == "esp32":
+ L.append(f"Wire.begin((uint8_t){addr}, {b.spec['i2c'][0]}, {b.spec['i2c'][1]}, 100000); // I2C slave")
+ else:
+ L.append(f"Wire.begin((uint8_t){addr}); // I2C slave (another board is the master)")
+ L.append(f"Wire.onReceive(nlclI2cRx_{slave.cid});")
+ elif wire:
+ if b.spec["arch"] == "esp32":
+ L.append(f"Wire.begin({b.spec['i2c'][0]}, {b.spec['i2c'][1]}); // SDA, SCL")
+ else:
+ L.append("Wire.begin();")
+ for c in b.comps:
+ if c.role == "oled":
+ L += ["#if NLCL_USE_OLED",
+ f"if (!nlclOled_{c.var}.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println(\"# {c.e.name}: SSD1306 not found\");",
+ "#endif"]
+ if c.role == "lcd":
+ L += ["#if NLCL_USE_LCD", f"nlclLcd_{c.var}.init(); nlclLcd_{c.var}.backlight();", "#endif"]
+ if spi:
+ L.append("SPI.begin();")
+ for x in b.chans:
+ if x.transport == "spi" and "cs" in x.pins:
+ L += [f"pinMode(PIN_CS_{x.cid.upper()}, OUTPUT);", f"digitalWrite(PIN_CS_{x.cid.upper()}, HIGH);"]
+ for x in b.chans:
+ if x.transport == "gpio" and not x.local:
+ for f in x.pins:
+ L.append(f"pinMode(PIN_{x.cid.upper()}_{ident(f).upper()}, {'OUTPUT' if x.out else 'INPUT'});")
+ if wifi:
+ L += ["WiFi.mode(WIFI_STA);" if b.wifi != "picow" else "WiFi.mode(WIFI_STA);",
+ "WiFi.begin(WIFI_SSID, WIFI_PASS);",
+ "Serial.print(\"# connecting to WiFi \" WIFI_SSID);",
+ "{ unsigned long t0 = millis(); while (WiFi.status() != WL_CONNECTED && millis() - t0 < 15000UL) { delay(250); Serial.print('.'); } }",
+ "Serial.println(WiFi.status() == WL_CONNECTED ? \" ok\" : \" offline (will retry)\");"]
+ if mqtt:
+ broker = next((x.ch.config.get("broker", "broker.hivemq.com") for x in b.chans if x.transport == "mqtt"),
+ "broker.hivemq.com")
+ port = next((_int(x.ch.config.get("broker_port"), 1883) for x in b.chans if x.transport == "mqtt"), 1883)
+ L += ["#if NLCL_USE_MQTT", f"nlclMqtt.setServer({self._cstr(broker)}, {port});",
+ "nlclMqtt.setBufferSize(512);"]
+ if any(x.transport == "mqtt" and x.inn for x in b.chans):
+ L.append("nlclMqtt.setCallback(nlclMqttCallback);")
+ L.append("#endif")
+ if udp:
+ port = next((_int(x.ch.config.get("port"), 9876) for x in b.chans if x.transport == "udp" and x.inn), 0)
+ if port:
+ L.append(f"nlclUdp.begin({port});")
+ if b.spec["arch"] == "avr":
+ L.append("randomSeed(analogRead(A0) ^ micros());")
+ else:
+ L.append("randomSeed(micros());")
+ return L
+
+ # ======================================================================
+ # MicroPython
+ # ======================================================================
+ def _upy(self, ctx: BuildContext, b: Board, S: dict) -> str:
+ sp = b.spec
+ port = "esp32" if sp["arch"] == "esp32" else "rp2"
+ net = [x for x in b.chans if not x.local and x.transport in ("http", "mqtt", "udp")]
+ wifi = bool(net) and bool(b.wifi)
+ roles = {c.role for c in b.comps}
+ L: list[str] = []
+ A = L.append
+ A(f'"""{ctx.system.name} - MicroPython firmware for {sp["title"]} (\'{b.ident}\').')
+ A("")
+ A("Generated by NLCL; same behaviour as the Arduino sketch next to it.")
+ A("Flash MicroPython (micropython.org/download), then: mpremote cp main.py :main.py and reset.")
+ A("Serial (USB REPL): JSON lines are channel messages, '#' lines are logs, other lines are commands.")
+ A('"""')
+ A("import sys")
+ A("import time")
+ A("import json")
+ A("from machine import Pin, ADC, PWM")
+ if roles & {"oled", "lcd"} or any(x.transport == "i2c" and not x.local for x in b.chans):
+ A("from machine import I2C")
+ if any(x.transport == "spi" and not x.local for x in b.chans):
+ A("from machine import SPI")
+ if "distance" in roles:
+ A("from machine import time_pulse_us")
+ if "dht" in roles:
+ A("try:\n import dht\nexcept ImportError:\n dht = None")
+ if "neopixel" in roles:
+ A("try:\n import neopixel\nexcept ImportError:\n neopixel = None")
+ if "oled" in roles:
+ A("try:\n import ssd1306 # mpremote mip install ssd1306\nexcept ImportError:\n ssd1306 = None")
+ A("try:\n import select\n _POLL = select.poll()\n _POLL.register(sys.stdin, select.POLLIN)\nexcept Exception:\n _POLL = None")
+ if wifi:
+ A("try:\n import network\nexcept ImportError:\n network = None")
+ if any(x.transport == "http" for x in net):
+ A("try:\n import urequests as requests\nexcept ImportError:\n try:\n import requests\n except ImportError:\n requests = None")
+ if any(x.transport == "mqtt" for x in net):
+ A("try:\n from umqtt.simple import MQTTClient # mpremote mip install umqtt.simple\nexcept ImportError:\n MQTTClient = None")
+ if any(x.transport == "udp" for x in net):
+ A("import socket")
+ ssid = b.entity.props.get("wifi_ssid") if b.entity else None
+ pw = b.entity.props.get("wifi_password") if b.entity else None
+ host = b.entity.props.get("hub_host") if b.entity else None
+ hub_port = 8765
+ for x in net:
+ if x.transport == "http":
+ try:
+ hub_port = int(str(x.ch.hub_url).rsplit(":", 1)[1].split("/")[0])
+ except (ValueError, IndexError):
+ pass
+ A("")
+ A(f"WIFI_SSID = {str(ssid or 'Wokwi-GUEST')!r} # Wokwi simulator: 'Wokwi-GUEST', no password")
+ A(f"WIFI_PASS = {str(pw or '')!r}")
+ A(f"HUB_HOST = {str(host or 'host.wokwi.internal')!r} # PC running the NLCL hub (NOT localhost)")
+ A(f"HUB_PORT = {hub_port}")
+ A("")
+ A("ADC_MAX = 65535 # read_u16() full scale")
+ A("")
+ A("")
+ A("class Obj:")
+ A(" def __init__(self, **kw):")
+ A(" self.__dict__.update(kw)")
+ A("")
+ A("")
+ A("# ---- entity state")
+ for c in b.comps:
+ kw = ", ".join(f"{m.name}={self._plit(m)}" for m in c.members.values())
+ A(f"{c.var} = Obj({kw}) # {c.e.kind} '{c.e.name}'")
+ A("REMOTE = {} # latest values received from other modules ('entity.field')")
+ A("_ST = {} # trigger / driver state")
+ # ---- hardware
+ A("")
+ A("# ---- hardware")
+
+ def pn(c, logical="pin"):
+ return self._pyint(b, c.pins.get(logical, "0"))
+ for c in b.comps:
+ v, r = c.var, c.role
+ if r in ("led", "relay"):
+ if r == "led" and "brightness" in c.members:
+ A(f"_hw_{v} = PWM(Pin({pn(c)})) # {c.e.name}")
+ A(f"_hw_{v}.freq(1000)")
+ else:
+ A(f"_hw_{v} = Pin({pn(c)}, Pin.OUT) # {c.e.name}")
+ elif r in ("motor", "fan", "buzzer"):
+ A(f"_hw_{v} = PWM(Pin({pn(c)})) # {c.e.name}")
+ A(f"_hw_{v}.freq({1000 if r != 'buzzer' else 1000})")
+ A(f"_hw_{v}.duty_u16(0)")
+ elif r == "servo":
+ A(f"_hw_{v} = PWM(Pin({pn(c)})) # {c.e.name} (50 Hz servo pulses)")
+ A(f"_hw_{v}.freq(50)")
+ elif r in ("button", "switch"):
+ A(f"_hw_{v} = Pin({pn(c)}, Pin.IN, Pin.PULL_UP) # {c.e.name}")
+ elif r == "pir":
+ A(f"_hw_{v} = Pin({pn(c)}, Pin.IN) # {c.e.name}")
+ elif r in ("temp", "light", "pot", "analog"):
+ A(f"_hw_{v} = ADC(Pin({pn(c)})) # {c.e.name}")
+ if port == "esp32":
+ A(f"_hw_{v}.atten(ADC.ATTN_11DB) # full 0..3.3 V range")
+ elif r == "dht":
+ model = "DHT11" if "dht11" in self._words(c.e) else "DHT22"
+ A(f"_hw_{v} = dht.{model}(Pin({pn(c)})) if dht else None # {c.e.name}")
+ elif r == "distance":
+ A(f"_hw_{v}_trig = Pin({pn(c, 'trig')}, Pin.OUT) # {c.e.name}")
+ A(f"_hw_{v}_echo = Pin({pn(c, 'echo')}, Pin.IN)")
+ elif r == "neopixel":
+ n = c.e.props.get("pixels", 1)
+ n = n if isinstance(n, int) and not isinstance(n, bool) and n > 0 else 1
+ A(f"_hw_{v} = neopixel.NeoPixel(Pin({pn(c)}), {n}) if neopixel else None # {c.e.name}")
+ if roles & {"oled", "lcd"} or any(x.transport == "i2c" and not x.local for x in b.chans):
+ sda, scl = sp["i2c"]
+ A(f"_I2C = I2C(0, scl=Pin({scl}), sda=Pin({sda}), freq=400000)")
+ for c in b.comps:
+ if c.role == "oled":
+ A("try:")
+ A(f" _hw_{c.var} = ssd1306.SSD1306_I2C(128, 64, _I2C) if ssd1306 else None # {c.e.name}")
+ A("except Exception:")
+ A(f" _hw_{c.var} = None")
+ elif c.role == "lcd":
+ A(f"_hw_{c.var} = None # {c.e.name}: no built-in LCD driver in MicroPython; text goes to the REPL")
+ if any(x.transport == "spi" and not x.local for x in b.chans):
+ sck, miso, mosi = sp["spi"]
+ sid = 2 if port == "esp32" else 0
+ A(f"_SPI = SPI({sid}, baudrate=1000000, sck=Pin({sck}), mosi=Pin({mosi}), miso=Pin({miso}))")
+ for x in b.chans:
+ if x.transport == "spi" and "cs" in x.pins:
+ A(f"_CS_{x.cid} = Pin({self._pyint(b, x.pins['cs'])}, Pin.OUT, value=1)")
+ for x in b.chans:
+ if x.transport == "gpio" and not x.local:
+ for f, p in x.pins.items():
+ A(f"_GP_{x.cid}_{ident(f)} = Pin({self._pyint(b, p)}, {'Pin.OUT' if x.out else 'Pin.IN'}) # field {f}")
+ # ---- helpers
+ A("")
+ A("")
+ A("def nlcl_log(who, msg):")
+ A(" _ST['last_log'] = str(msg)")
+ A(" print('# %s: %s' % (who, msg))")
+ A("")
+ A("")
+ A("def i16(v):")
+ A(" try:")
+ A(" v = int(round(float(v)))")
+ A(" except (TypeError, ValueError):")
+ A(" v = 0")
+ A(" return max(-32768, min(32767, v))")
+ A("")
+ A("")
+ A("def to_num(v):")
+ A(" if v is True or v is False:")
+ A(" return 1 if v else 0")
+ A(" try:")
+ A(" return float(v)")
+ A(" except (TypeError, ValueError):")
+ A(" return 0")
+ if "buzzer" in roles:
+ A("")
+ A("")
+ A("def beep(pwm, freq, ms):")
+ A(" pwm.freq(int(freq) or 1000)")
+ A(" pwm.duty_u16(32768)")
+ A(" time.sleep_ms(ms)")
+ A(" pwm.duty_u16(0)")
+ A(" _ST.pop('bz', None)")
+ if "neopixel" in roles:
+ A("")
+ A("")
+ A(f"COLORS = {dict(COLORS)!r}")
+ A("")
+ A("")
+ A("def color(c):")
+ A(" c = str(c)")
+ A(" if c.startswith('#') and len(c) == 7:")
+ A(" return (int(c[1:3], 16), int(c[3:5], 16), int(c[5:7], 16))")
+ A(" return COLORS.get(c.lower(), (255, 255, 255))")
+ if wifi:
+ A("")
+ A("")
+ A("def wifi_up():")
+ A(" if network is None:")
+ A(" return False")
+ A(" w = _ST.get('wlan')")
+ A(" if w is None:")
+ A(" w = network.WLAN(network.STA_IF)")
+ A(" w.active(True)")
+ A(" _ST['wlan'] = w")
+ A(" if w.isconnected():")
+ A(" return True")
+ A(" now = time.ticks_ms()")
+ A(" if 'wifi_try' in _ST and time.ticks_diff(now, _ST['wifi_try']) < 10000:")
+ A(" return False")
+ A(" _ST['wifi_try'] = now")
+ A(" try:")
+ A(" w.connect(WIFI_SSID, WIFI_PASS)")
+ A(" except OSError:")
+ A(" pass")
+ A(" return False")
+ if any(x.transport == "http" for x in net):
+ A("")
+ A("")
+ A("def _http(method, path, body=None):")
+ A(" if requests is None or not wifi_up():")
+ A(" return None")
+ A(" url = 'http://%s:%d%s' % (HUB_HOST, HUB_PORT, path)")
+ A(" kw = {'headers': {'Content-Type': 'application/json'}} if body is not None else {}")
+ A(" try:")
+ A(" try:")
+ A(" r = requests.request(method, url, data=body, timeout=2, **kw)")
+ A(" except TypeError: # old urequests without timeout")
+ A(" r = requests.request(method, url, data=body, **kw)")
+ A(" txt = r.text if r.status_code == 200 else None")
+ A(" r.close()")
+ A(" return txt")
+ A(" except Exception:")
+ A(" return None")
+ if any(x.transport == "mqtt" for x in net):
+ broker = next((x.ch.config.get("broker", "broker.hivemq.com") for x in net if x.transport == "mqtt"),
+ "broker.hivemq.com")
+ bport = next((_int(x.ch.config.get("broker_port"), 1883) for x in net if x.transport == "mqtt"), 1883)
+ subs = [x for x in net if x.transport == "mqtt" and x.inn]
+ A("")
+ A("")
+ A("def _mqtt_msg(topic, msg):")
+ A(" t = topic.decode() if isinstance(topic, bytes) else topic")
+ A(" try:")
+ A(" m = json.loads(msg)")
+ A(" except ValueError:")
+ A(" return")
+ for x in subs:
+ A(f" if t == {x.ch.topic!r}:")
+ A(f" recv_{x.cid}(m)")
+ A("")
+ A("")
+ A("def mqtt_client():")
+ A(" c = _ST.get('mqtt')")
+ A(" if c is not None or MQTTClient is None or not wifi_up():")
+ A(" return c")
+ A(" now = time.ticks_ms()")
+ A(" if 'mqtt_try' in _ST and time.ticks_diff(now, _ST['mqtt_try']) < 5000:")
+ A(" return None")
+ A(" _ST['mqtt_try'] = now")
+ A(" try:")
+ A(f" c = MQTTClient('nlcl-%d' % (now & 0xFFFFFF), {broker!r}, port={bport})")
+ A(" c.set_callback(_mqtt_msg)")
+ A(" c.connect()")
+ for x in subs:
+ A(f" c.subscribe({x.ch.topic!r})")
+ A(" _ST['mqtt'] = c")
+ A(" except Exception:")
+ A(" c = None")
+ A(" return c")
+ if any(x.transport == "udp" for x in net):
+ A("")
+ A("")
+ A("def udp_sock():")
+ A(" s = _ST.get('udp')")
+ A(" if s is None:")
+ A(" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)")
+ inport = next((_int(x.ch.config.get("port"), 9876) for x in net if x.transport == "udp" and x.inn), 0)
+ if inport:
+ A(f" s.bind(('0.0.0.0', {inport}))")
+ A(" s.setblocking(False)")
+ A(" _ST['udp'] = s")
+ A(" return s")
+ # ---- channels
+ A("")
+ A("")
+ A("# ---- channels")
+ recv_map = []
+ for x in b.chans:
+ ch = x.ch
+ A(f"# {ch.id}: {ch.src.name} ({ch.src.domain}) -> {ch.dst.name} ({ch.dst.domain}) via {x.transport}"
+ f"{' (local)' if x.local else ''}; fields: {', '.join(ch.fields)}")
+ if x.out and x.local:
+ A(f"def publish_{x.cid}():")
+ for f in ch.fields:
+ _, pe, t = self._field_ref(b, x, f)
+ if x.dst is not None:
+ dm = self._member(x.dst, f, t)
+ if pe == f"{x.dst.var}.{dm.name}":
+ A(f" # {f}: '{ch.src.name}' has no such property (nothing to copy)")
+ else:
+ A(f" {x.dst.var}.{dm.name} = {pe}")
+ for s in self._msg_calls_py(b, x):
+ A(f" {s}")
+ A(" pass")
+ A("")
+ A("")
+ continue
+ if x.out:
+ if x.transport in ("serial", "http", "mqtt", "udp"):
+ A(f"def tx_{x.cid}(line):")
+ if x.transport == "serial":
+ A(" print(line)")
+ elif x.transport == "http":
+ A(f" _http('POST', {ch.config.get('path', '/channel/' + ch.id)!r}, line)")
+ elif x.transport == "mqtt":
+ A(" c = mqtt_client()")
+ A(" if c is not None:")
+ A(" try:")
+ A(f" c.publish({ch.topic!r}, line)")
+ A(" except Exception:")
+ A(" _ST.pop('mqtt', None)")
+ elif x.transport == "udp":
+ A(" if wifi_up():")
+ A(" try:")
+ A(f" udp_sock().sendto(line.encode(), (HUB_HOST, {_int(ch.config.get('port'), 9876)}))")
+ A(" except OSError:")
+ A(" pass")
+ A("")
+ A("")
+ A(f"def publish_{x.cid}():")
+ A(f" tx_{x.cid}({self._json_build_py(b, x, ch.fields)})")
+ elif x.transport in ("i2c", "spi"):
+ n = len(ch.fields)
+ vals = ", ".join(f"i16({self._field_ref(b, x, f)[1]})" for f in ch.fields)
+ A(f"def publish_{x.cid}(): # frame 0x{FRAME_SYNC:02X}, {n}, {n} x int16 big-endian")
+ A(f" vals = [{vals}]")
+ A(f" buf = bytearray([0x{FRAME_SYNC:02X}, {n}])")
+ A(" for v in vals:")
+ A(" buf += bytes([(v >> 8) & 0xFF, v & 0xFF])")
+ if x.transport == "i2c":
+ A(" try:")
+ A(f" _I2C.writeto({self._i2c_addr(ch)}, buf)")
+ A(" except OSError:")
+ A(" pass")
+ else:
+ A(f" _CS_{x.cid}.value(0)")
+ A(" _SPI.write(buf)")
+ A(f" _CS_{x.cid}.value(1)")
+ else:
+ A(f"def publish_{x.cid}(): # one pin per field")
+ for f in ch.fields:
+ A(f" _GP_{x.cid}_{ident(f)}.value(1 if to_num({self._field_ref(b, x, f)[1]}) else 0)")
+ if not ch.fields:
+ A(" pass")
+ A("")
+ A("")
+ if x.inn:
+ A(f"def recv_{x.cid}(msg):")
+ A(" if not isinstance(msg, dict):")
+ A(" return")
+ for f in ch.fields:
+ key = f"{ch.src.ident}.{ident(f)}"
+ A(f" if {f!r} in msg:")
+ A(f" REMOTE[{key!r}] = msg[{f!r}]")
+ if x.dst is not None and ident(f) in x.dst.members:
+ m = x.dst.members[ident(f)]
+ conv = {"bool": f"bool(to_num(msg[{f!r}]))", "long": f"int(to_num(msg[{f!r}]))",
+ "float": f"to_num(msg[{f!r}])", "String": f"str(msg[{f!r}])"}[m.ctype]
+ A(f" {x.dst.var}.{m.name} = {conv}")
+ for s in self._msg_calls_py(b, x):
+ A(f" {s}")
+ A("")
+ A("")
+ if x.transport in ("serial", "udp", "mqtt"):
+ recv_map.append(x)
+ if x.transport == "http":
+ A(f"def poll_{x.cid}(): # GET the latest message from the hub, act only on new ones")
+ A(f" r = _http('GET', {ch.config.get('path', '/channel/' + ch.id)!r})")
+ A(" if not r:")
+ A(" return")
+ A(" try:")
+ A(" m = json.loads(r)")
+ A(" except ValueError:")
+ A(" return")
+ A(f" if m.get('_t') is not None and m.get('_t') != _ST.get('last_t_{x.cid}'):")
+ A(f" _ST['last_t_{x.cid}'] = m.get('_t')")
+ A(f" recv_{x.cid}(m)")
+ A("")
+ A("")
+ elif x.transport in ("i2c", "spi", "gpio"):
+ n = len(ch.fields)
+ A(f"def poll_{x.cid}():")
+ if x.transport == "i2c":
+ A(" try:")
+ A(f" buf = _I2C.readfrom({self._i2c_addr(ch)}, {2 + 2 * n})")
+ A(" except OSError:")
+ A(" return")
+ A(f" if len(buf) < {2 + 2 * n} or buf[0] != 0x{FRAME_SYNC:02X}:")
+ A(" return")
+ A(" data = buf[2:]")
+ elif x.transport == "spi":
+ A(f" buf = bytearray({1 + 2 * n})")
+ A(f" _CS_{x.cid}.value(0)")
+ A(f" _SPI.write(bytes([0x{FRAME_READ:02X}]))")
+ A(" _SPI.readinto(buf, 0)")
+ A(f" _CS_{x.cid}.value(1)")
+ A(f" if buf[0] != 0x{FRAME_SYNC:02X}:")
+ A(" return")
+ A(" data = buf[1:]")
+ if x.transport in ("i2c", "spi"):
+ A(" vals = []")
+ A(f" for i in range({n}):")
+ A(" v = (data[2 * i] << 8) | data[2 * i + 1]")
+ A(" vals.append(v - 65536 if v & 0x8000 else v)")
+ else:
+ A(f" vals = [{', '.join(f'_GP_{x.cid}_{ident(f)}.value()' for f in ch.fields) or ''}]")
+ A(f" if vals == _ST.get('gp_{x.cid}'):")
+ A(" return")
+ A(f" _ST['gp_{x.cid}'] = vals")
+ A(f" recv_{x.cid}(dict(zip({list(ch.fields)!r}, vals)))")
+ A("")
+ A("")
+ A("def handle_line(line):")
+ A(" line = line.strip()")
+ A(" if not line:")
+ A(" return")
+ A(" if line.startswith('{'):")
+ A(" try:")
+ A(" m = json.loads(line)")
+ A(" except ValueError:")
+ A(" return")
+ A(" ch = m.get('channel')")
+ for x in recv_map:
+ if x.transport == "serial":
+ A(f" if ch == {x.ch.id!r}:")
+ A(f" recv_{x.cid}(m)")
+ A(" return")
+ A(" command(line)")
+ A("")
+ A("")
+ A("def poll_serial():")
+ A(" if _POLL is None:")
+ A(" return")
+ A(" while _POLL.poll(0):")
+ A(" c = sys.stdin.read(1)")
+ A(" if not c:")
+ A(" return")
+ A(" if c in '\\r\\n':")
+ A(" buf = _ST.get('buf', '')")
+ A(" _ST['buf'] = ''")
+ A(" handle_line(buf)")
+ A(" else:")
+ A(" _ST['buf'] = (_ST.get('buf', '') + c)[-300:]")
+ # ---- behaviours
+ A("")
+ A("")
+ A("# ---- behaviours")
+ L += S["beh_p"]
+ for name, n in sorted(b.calls.items()):
+ A("")
+ A(f"def user_{name}(*args): # '{name}' was requested by a behaviour: put your own code here")
+ A(f" nlcl_log('call', '{name}%r' % (args,))")
+ A("")
+ A("")
+ A("def command(cmd): # typed serial commands -> input: behaviours")
+ L += S["cmd_p"]
+ A(" pass")
+ # ---- drivers
+ L += self._io_py(b, port)
+ A("")
+ A("")
+ A("def comms(now):")
+ body = []
+ if wifi:
+ if any(x.transport == "mqtt" for x in net):
+ body += ["c = mqtt_client()", "if c is not None:", " try:", " c.check_msg()",
+ " except Exception:", " _ST.pop('mqtt', None)"]
+ if any(x.transport == "udp" and x.inn for x in net):
+ body += ["if wifi_up():", " try:", " data = udp_sock().recv(512)", " except OSError:",
+ " data = None", " if data:", " try:", " m = json.loads(data)",
+ " except ValueError:", " m = {}"]
+ for x in net:
+ if x.transport == "udp" and x.inn:
+ body += [f" if m.get('channel') == {x.ch.id!r}:", f" recv_{x.cid}(m)"]
+ for x in b.chans:
+ iv = max(1, _int(x.ch.config.get("interval_ms"), 1000))
+ if x.inn and not x.local and x.transport in ("http", "i2c", "spi", "gpio"):
+ body += [f"if time.ticks_diff(now, _ST.get('poll_{x.cid}', -{iv})) >= {iv}:",
+ f" _ST['poll_{x.cid}'] = now", f" poll_{x.cid}()"]
+ if x.out:
+ body += [f"if time.ticks_diff(now, _ST.get('pub_{x.cid}', -{iv})) >= {iv}: # {x.ch.id} every {iv} ms",
+ f" _ST['pub_{x.cid}'] = now", f" publish_{x.cid}()"]
+ L += [" " + s for s in body] or [" pass"]
+ A("")
+ A("")
+ A("def triggers(now):")
+ L += S["trig_p"] or [" pass"]
+ A("")
+ A("")
+ A("def setup():")
+ A(f" print('# {b.ident}: NLCL MicroPython firmware starting')")
+ if wifi:
+ A(" t0 = time.ticks_ms()")
+ A(" while not wifi_up() and time.ticks_diff(time.ticks_ms(), t0) < 15000:")
+ A(" time.sleep_ms(250)")
+ L += [" " + s for s in S["start_p"]]
+ L += [" " + s for s in S["chg_init_p"]]
+ A(" pass")
+ A("")
+ A("")
+ A("def loop():")
+ A(" now = time.ticks_ms()")
+ A(" read_inputs(now)")
+ A(" poll_serial()")
+ A(" comms(now)")
+ A(" triggers(now)")
+ A(" write_outputs(now)")
+ A("")
+ A("")
+ A("if __name__ == '__main__':")
+ A(" setup()")
+ A(" while True:")
+ A(" loop()")
+ A(" time.sleep_ms(2)")
+ return "\n".join(L) + "\n"
+
+ def _msg_calls_py(self, b: Board, x: Chan) -> list[str]:
+ return [s.split(";")[0].replace("();", "()").rstrip(";") + " # " + s.split("// ")[1]
+ for s in self._msg_calls_cpp(b, x)]
+
+ def _io_py(self, b: Board, port: str) -> list[str]:
+ L = ["", "", "# ---- drivers", "def read_inputs(now):"]
+ rd = []
+ for c in b.comps:
+ v, r = c.var, c.role
+ if r == "button":
+ rd.append(f"{v}.pressed = _hw_{v}.value() == 0 # pull-up: pressed = GND")
+ elif r == "switch":
+ rd.append(f"{v}.on = _hw_{v}.value() == 0")
+ elif r == "pir":
+ rd.append(f"{v}.motion = _hw_{v}.value() == 1")
+ elif r == "temp":
+ rd += [f"raw = _hw_{v}.read_u16() # NTC thermistor divider, beta 3950",
+ "if 0 < raw < ADC_MAX:",
+ " import math",
+ f" {v}.temperature = 1 / (math.log(1 / (ADC_MAX / raw - 1)) / 3950 + 1 / 298.15) - 273.15"]
+ elif r == "dht":
+ rd += [f"if _hw_{v} is not None and time.ticks_diff(now, _ST.get('dht_{v}', -2000)) >= 2000:",
+ f" _ST['dht_{v}'] = now",
+ " try:",
+ f" _hw_{v}.measure()",
+ f" {v}.temperature = _hw_{v}.temperature()",
+ f" {v}.humidity = _hw_{v}.humidity()",
+ " except OSError:",
+ " pass"]
+ elif r == "distance":
+ rd += [f"if time.ticks_diff(now, _ST.get('us_{v}', -60)) >= 60:",
+ f" _ST['us_{v}'] = now",
+ f" _hw_{v}_trig.value(0)",
+ " time.sleep_us(2)",
+ f" _hw_{v}_trig.value(1)",
+ " time.sleep_us(10)",
+ f" _hw_{v}_trig.value(0)",
+ f" us = time_pulse_us(_hw_{v}_echo, 1, 30000)",
+ " if us > 0:",
+ f" {v}.distance = us / 58.0 # cm"]
+ elif r in ("light", "pot", "analog"):
+ f = next((k for k in c.members if k != "alive" and k != "on"), "value")
+ m = c.members[f]
+ conv = {"String": "str({})", "bool": "{} > 32767", "long": "{} >> 4", "float": "{} / 16"}[m.ctype]
+ if f in PERCENT_FIELDS and m.ctype in ("long", "float"):
+ conv = "{} * 100 // 65535" if m.ctype == "long" else "{} * 100 / 65535"
+ rd.append(f"{v}.{m.name} = {conv.format(f'_hw_{v}.read_u16()')} # 0..100 %")
+ else:
+ rd.append(f"{v}.{m.name} = {conv.format(f'_hw_{v}.read_u16()')} # 0..4095")
+ L += [" " + s for s in rd] or [" pass"]
+ L += ["", "", "def write_outputs(now):"]
+ wr = []
+ for c in b.comps:
+ v, r = c.var, c.role
+ if r in ("led", "relay"):
+ if r == "led" and "brightness" in c.members and c.members["brightness"].ctype != "String":
+ wr.append(f"_hw_{v}.duty_u16(int(max(0, min(255, {v}.brightness))) * 257 if ({v}.alive and {v}.on) else 0)")
+ else:
+ wr.append(f"_hw_{v}.value(1 if ({v}.alive and {v}.on) else 0)")
+ elif r in ("motor", "fan"):
+ spm = c.members.get("speed")
+ sv = f"{v}.{spm.name}" if spm and spm.ctype != "String" else "255"
+ wr.append(f"_hw_{v}.duty_u16(int(max(0, min(255, {sv}))) * 257 if ({v}.alive and {v}.on) else 0)")
+ elif r == "servo":
+ am = c.members["angle"]
+ wr += [f"a = int(max(0, min(180, to_num({v}.{am.name}))))",
+ f"if {v}.alive and a != _ST.get('servo_{v}'):",
+ f" _ST['servo_{v}'] = a",
+ f" _hw_{v}.duty_u16(int((0.5 + a / 180 * 2.0) / 20 * 65535)) # 0.5..2.5 ms pulse"]
+ elif r == "buzzer":
+ fm = c.members["frequency"]
+ fv = f"{v}.{fm.name}" if fm.ctype != "String" else "1000"
+ wr += [f"s = bool({v}.alive and {v}.on)",
+ f"if s != _ST.get('bz_{v}', False):",
+ f" _ST['bz_{v}'] = s",
+ " if s:",
+ f" _hw_{v}.freq(int(to_num({fv})) or 1000)",
+ f" _hw_{v}.duty_u16(32768 if s else 0)"]
+ elif r == "neopixel":
+ cm, bm = c.members["color"], c.members["brightness"]
+ wr += [f"if _hw_{v} is not None:",
+ f" k = ({v}.alive and {v}.on, {v}.{cm.name}, {v}.{bm.name})",
+ f" if k != _ST.get('px_{v}'):",
+ f" _ST['px_{v}'] = k",
+ f" s = max(0, min(255, int(to_num({v}.{bm.name})))) / 255 if ({v}.alive and {v}.on) else 0",
+ f" _hw_{v}.fill(tuple(int(ch * s) for ch in color({v}.{cm.name})))",
+ f" _hw_{v}.write()"]
+ elif r in ("oled", "lcd"):
+ tm = c.members["text"]
+ wr += [f"if time.ticks_diff(now, _ST.get('disp_{v}', -500)) >= 500:",
+ f" _ST['disp_{v}'] = now",
+ f" l1 = str({v}.{tm.name}) or _ST.get('last_log', '')"]
+ rows = []
+ for s in b.comps:
+ if s.role in ("temp", "dht", "distance", "light", "pot", "analog", "pir"):
+ for f, m in s.members.items():
+ if f != "alive" and m.ctype != "String":
+ rows.append((f"{s.e.name[:8]} {f[:4]}", f"{s.var}.{m.name}"))
+ rows = rows[:3]
+ if r == "oled":
+ wr += [f" if _hw_{v} is not None:",
+ f" _hw_{v}.fill(0)",
+ f" _hw_{v}.text(l1[:16], 0, 0)"]
+ for i, (lab, code) in enumerate(rows):
+ wr.append(f" _hw_{v}.text('{lab}: ' + str({code}), 0, {12 * (i + 1)})")
+ wr.append(f" _hw_{v}.show()")
+ else:
+ wr += [f" if l1 != _ST.get('lcd_{v}'):", f" _ST['lcd_{v}'] = l1",
+ f" print('# {c.e.name} (lcd): ' + l1)"]
+ L += [" " + s for s in wr] or [" pass"]
+ return L
+
+ # ======================================================================
+ # PlatformIO / Wokwi
+ # ======================================================================
+ def _pio_libs(self, b: Board) -> list[str]:
+ m = {"DHT sensor library": "adafruit/DHT sensor library@^1.4.6",
+ "ESP32Servo": "madhephaestus/ESP32Servo@^3.0.5",
+ "Servo": "arduino-libraries/Servo@^1.2.1",
+ "Adafruit NeoPixel": "adafruit/Adafruit NeoPixel@^1.12.0",
+ "Adafruit SSD1306": "adafruit/Adafruit SSD1306@^2.5.9",
+ "Adafruit GFX Library": "adafruit/Adafruit GFX Library@^1.11.9",
+ "LiquidCrystal I2C": "marcoschwartz/LiquidCrystal_I2C@^1.1.4",
+ "PubSubClient": "knolleary/PubSubClient@^2.8"}
+ return [m[x] for x in sorted(b.libs) if x in m]
+
+ def _pio(self, b: Board) -> str:
+ platform, board, env = b.spec["pio"]
+ L = ["; PlatformIO project (free): pio run | pio run -t upload | pio device monitor",
+ "[platformio]", f"default_envs = {env}", "src_dir = .", "",
+ f"[env:{env}]"]
+ if platform == "raspberrypi":
+ L += ["platform = https://github.com/maxgerhardt/platform-raspberrypi.git",
+ f"board = {board}", "framework = arduino", "board_build.core = earlephilhower"]
+ else:
+ L += [f"platform = {platform}", f"board = {board}", "framework = arduino"]
+ L += [f"monitor_speed = {self._baud(b)}", "build_src_filter = -<*> +<*.ino>"]
+ libs = self._pio_libs(b)
+ if libs:
+ L.append("lib_deps =")
+ L += [f" {x}" for x in libs]
+ return "\n".join(L) + "\n"
+
+ def _wokwi_libs(self, b: Board) -> set[str]:
+ libs = set(b.libs)
+ if "DHT sensor library" in libs:
+ libs.add("Adafruit Unified Sensor")
+ return libs
+
+ def _wokwi_toml(self, b: Board) -> str:
+ env = b.spec["pio"][2]
+ fw = b.spec["fw"]
+ return ("# Wokwi for VS Code (free): run `pio run` first, then \"Wokwi: Start Simulator\".\n"
+ "# arduino-cli users: point these at build//.ino.hex|.bin|.elf instead.\n"
+ "[wokwi]\nversion = 1\n"
+ f"firmware = '.pio/build/{env}/firmware.{fw}'\n"
+ f"elf = '.pio/build/{env}/firmware.elf'\n")
+
+ def _wpin(self, b: Board, p: str) -> str:
+ wid = b.spec["wid"]
+ if b.key in ("pico", "pico_w"):
+ return f"{wid}:GP{p}"
+ if b.key == "esp32":
+ p = {"36": "VP", "39": "VN"}.get(p, p)
+ return f"{wid}:{p}"
+
+ def _diagram(self, b: Board) -> str:
+ sp = b.spec
+ wid = sp["wid"]
+ gnd = f"{wid}:{sp['gnd']}"
+ vcc = f"{wid}:{sp['vcc']}"
+ vcc5 = f"{wid}:{sp['vcc5']}"
+ parts = [{"type": sp["wokwi"], "id": wid, "top": 0, "left": 0, "attrs": {}}]
+ conns: list[list] = []
+ if b.key == "esp32":
+ conns += [[f"{wid}:TX", "$serialMonitor:RX", "", []], [f"{wid}:RX", "$serialMonitor:TX", "", []]]
+ elif b.key in ("pico", "pico_w"):
+ conns += [[f"{wid}:GP0", "$serialMonitor:RX", "", []], [f"{wid}:GP1", "$serialMonitor:TX", "", []]]
+ i2c = [self._wpin(b, sp["i2c"][0]), self._wpin(b, sp["i2c"][1])]
+ slot = 0
+ used_ids = {wid}
+
+ def place(ptype: str, c: Comp, attrs: dict | None = None) -> str:
+ nonlocal slot
+ pid = c.var[:20]
+ while pid in used_ids:
+ pid += "_"
+ used_ids.add(pid)
+ col, row = slot % 6, slot // 6
+ slot += 1
+ parts.append({"type": ptype, "id": pid, "top": -260 - row * 230, "left": col * 140 - 40,
+ "attrs": attrs or {}})
+ return pid
+
+ def w(a: str, z: str, color: str = "green"):
+ conns.append([a, z, color, []])
+
+ for c in b.comps:
+ r = c.role
+ P = self._wpin(b, c.pins["pin"]) if "pin" in c.pins else None
+ color = str(c.e.props.get("color", "")).lower()
+ if r == "led":
+ pid = place("wokwi-led", c, {"color": color if color in COLORS else "red", "label": c.e.name})
+ w(f"{pid}:A", P)
+ w(f"{pid}:C", gnd, "black")
+ elif r in ("motor", "fan"):
+ # Wokwi has no DC motor part: a blue LED shows the PWM output instead
+ pid = place("wokwi-led", c, {"color": "blue", "label": f"{c.e.name} ({r})"})
+ w(f"{pid}:A", P)
+ w(f"{pid}:C", gnd, "black")
+ elif r == "button":
+ pid = place("wokwi-pushbutton", c, {"color": color if color in COLORS else "green",
+ "label": c.e.name})
+ w(f"{pid}:1.l", P)
+ w(f"{pid}:2.l", gnd, "black")
+ elif r == "switch":
+ pid = place("wokwi-slide-switch", c)
+ w(f"{pid}:2", P)
+ w(f"{pid}:1", gnd, "black")
+ elif r == "pir":
+ pid = place("wokwi-pir-motion-sensor", c)
+ w(f"{pid}:VCC", vcc5, "red")
+ w(f"{pid}:OUT", P)
+ w(f"{pid}:GND", gnd, "black")
+ elif r == "temp":
+ pid = place("wokwi-ntc-temperature-sensor", c)
+ w(f"{pid}:VCC", vcc, "red")
+ w(f"{pid}:OUT", P)
+ w(f"{pid}:GND", gnd, "black")
+ elif r == "dht":
+ pid = place("wokwi-dht22", c)
+ w(f"{pid}:VCC", vcc, "red")
+ w(f"{pid}:SDA", P)
+ w(f"{pid}:GND", gnd, "black")
+ elif r == "distance":
+ pid = place("wokwi-hc-sr04", c)
+ w(f"{pid}:VCC", vcc5, "red")
+ w(f"{pid}:TRIG", self._wpin(b, c.pins["trig"]))
+ w(f"{pid}:ECHO", self._wpin(b, c.pins["echo"]), "orange")
+ w(f"{pid}:GND", gnd, "black")
+ elif r == "light":
+ pid = place("wokwi-photoresistor-sensor", c)
+ w(f"{pid}:VCC", vcc, "red")
+ w(f"{pid}:AO", P)
+ w(f"{pid}:GND", gnd, "black")
+ elif r in ("pot", "analog"):
+ pid = place("wokwi-potentiometer", c) # analog stand-in: turn the knob to change the value
+ w(f"{pid}:VCC", vcc, "red")
+ w(f"{pid}:SIG", P)
+ w(f"{pid}:GND", gnd, "black")
+ elif r == "servo":
+ pid = place("wokwi-servo", c)
+ w(f"{pid}:V+", vcc5, "red")
+ w(f"{pid}:PWM", P, "orange")
+ w(f"{pid}:GND", gnd, "black")
+ elif r == "relay":
+ pid = place("wokwi-relay-module", c)
+ w(f"{pid}:VCC", vcc5, "red")
+ w(f"{pid}:IN", P)
+ w(f"{pid}:GND", gnd, "black")
+ elif r == "buzzer":
+ pid = place("wokwi-buzzer", c, {"volume": "0.1"})
+ w(f"{pid}:2", P)
+ w(f"{pid}:1", gnd, "black")
+ elif r == "neopixel":
+ n = c.e.props.get("pixels", 1)
+ n = n if isinstance(n, int) and not isinstance(n, bool) and n > 0 else 1
+ if n > 1:
+ pid = place("wokwi-led-ring", c, {"pixels": str(n)})
+ w(f"{pid}:VCC", vcc5, "red")
+ w(f"{pid}:DIN", P)
+ w(f"{pid}:GND", gnd, "black")
+ else:
+ pid = place("wokwi-neopixel", c)
+ w(f"{pid}:VDD", vcc5, "red")
+ w(f"{pid}:DIN", P)
+ w(f"{pid}:VSS", gnd, "black")
+ elif r == "oled":
+ pid = place("board-ssd1306", c, {"i2cAddress": "0x3c"})
+ w(f"{pid}:VCC", vcc, "red")
+ w(f"{pid}:GND", gnd, "black")
+ w(f"{pid}:SDA", i2c[0], "blue")
+ w(f"{pid}:SCL", i2c[1], "purple")
+ elif r == "lcd":
+ pid = place("wokwi-lcd1602", c, {"pins": "i2c"})
+ w(f"{pid}:VCC", vcc5, "red")
+ w(f"{pid}:GND", gnd, "black")
+ w(f"{pid}:SDA", i2c[0], "blue")
+ w(f"{pid}:SCL", i2c[1], "purple")
+ doc = {"version": 1, "author": "NLCL", "editor": "wokwi", "parts": parts, "connections": conns,
+ "dependencies": {}}
+ return json.dumps(doc, indent=2) + "\n"
+
+ # ======================================================================
+ # README
+ # ======================================================================
+ def _readme(self, ctx: BuildContext, boards: list[Board]) -> str:
+ L = [f"# {ctx.system.name} - embedded firmware", "",
+ "Generated by NLCL. Each folder is one board; every file is plain source you can edit.", ""]
+ for b in boards:
+ sp = b.spec
+ d = b.ident
+ core = sp["fqbn"].split(":")[0] + ":" + sp["fqbn"].split(":")[1]
+ L += [f"## `{d}/` - {sp['title']}" + (" (implicit default board)" if b.entity is None else ""), ""]
+ L += ["| entity | kind | role | pins | state |", "|---|---|---|---|---|"]
+ for c in b.comps:
+ pins = ", ".join(f"{k}={v}" for k, v in c.pins.items()) or "-"
+ st = ", ".join(f"{m.field}" for m in c.members.values() if m.field != "alive")
+ L.append(f"| {c.e.name} | {c.e.kind} | {c.role} | {pins} | {st} |")
+ L.append("")
+ if b.warnings:
+ L.append("**Notes:**")
+ L += [f"- {w}" for w in dict.fromkeys(b.warnings)]
+ L.append("")
+ L += ["### Simulate for free (no hardware)", ""]
+ if sp["wokwi"]:
+ L += [f"1. Open https://wokwi.com and start a new **{sp['title']}** Arduino project.",
+ f"2. Paste `{d}.ino` into `sketch.ino`, replace `diagram.json` with ours"
+ + (", and add `libraries.txt`." if b.libs else "."),
+ "3. Press the green Play button. The Serial Monitor shows logs and channel JSON; "
+ "type a command (e.g. a button name) to fire `input:` behaviours.",
+ "",
+ "VS Code: install the free *Wokwi Simulator* extension, run `pio run` in this folder, then "
+ "*Wokwi: Start Simulator* (uses `wokwi.toml`).", ""]
+ if any(c.role in ("motor", "fan") for c in b.comps):
+ L += ["Wokwi has no DC motor part: motors/fans are shown as blue LEDs whose brightness is the PWM "
+ "output.", ""]
+ if any(c.role == "analog" for c in b.comps):
+ L += ["Generic analog sensors are simulated with a potentiometer.", ""]
+ if b.key in ("pico", "pico_w"):
+ L += ["Wokwi also runs `main.py` on a MicroPython Pico project.", ""]
+ elif b.key == "esp32":
+ L += ["Wokwi also runs `main.py` on a MicroPython ESP32 project.", ""]
+ else:
+ L += [f"Wokwi has no {sp['title']} part; use real hardware or switch the board kind to esp32/uno.", ""]
+ L += ["### Build and upload", "", "```sh",
+ "# arduino-cli (free)"]
+ if b.key in ("esp32",):
+ L.append("arduino-cli config add board_manager.additional_urls https://espressif.github.io/arduino-esp32/package_esp32_index.json")
+ elif b.key == "esp8266":
+ L.append("arduino-cli config add board_manager.additional_urls https://arduino.esp8266.com/stable/package_esp8266com_index.json")
+ elif b.key in ("pico", "pico_w"):
+ L.append("arduino-cli config add board_manager.additional_urls https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json")
+ elif b.key == "stm32":
+ L.append("arduino-cli config add board_manager.additional_urls https://github.com/stm32duino/BoardManagerFiles/raw/main/package_stmicroelectronics_index.json")
+ L.append(f"arduino-cli core install {core}")
+ if b.libs:
+ L.append("arduino-cli lib install " + " ".join(f'"{x}"' for x in sorted(self._wokwi_libs(b))))
+ L += [f"arduino-cli compile --fqbn {sp['fqbn']} {d}",
+ f"arduino-cli upload -p --fqbn {sp['fqbn']} {d}",
+ f"arduino-cli monitor -p -c baudrate={self._baud(b)}", "",
+ "# or PlatformIO (free)", f"pio run -d {d} -t upload && pio device monitor -b {self._baud(b)}", "```", ""]
+ if b.libs:
+ L += ["Optional libraries are switched on by `#define NLCL_USE_* 1` at the top of the sketch; set a flag "
+ "to 0 to build with only the core (that part is then simulated or disabled).", ""]
+ if sp["upy"]:
+ L += ["### MicroPython", "",
+ "```sh",
+ "pip install mpremote esptool # free tools",
+ f"mpremote cp {d}/main.py :main.py # then press reset",
+ "mpremote repl # logs + channel JSON",
+ "```", ""]
+ if b.by_role("oled"):
+ L += ["OLED: `mpremote mip install ssd1306` first.", ""]
+ if any(x.transport == "mqtt" for x in b.chans):
+ L += ["MQTT: `mpremote mip install umqtt.simple` if your firmware lacks it.", ""]
+ if b.chans:
+ L += ["### Channels", "", "| channel | direction | transport | fields | details |", "|---|---|---|---|---|"]
+ for x in b.chans:
+ ch = x.ch
+ dirn = "local" if x.local else ("out" if x.out else "in")
+ det = ""
+ if x.transport == "serial":
+ det = f"JSON line @ {ch.config.get('baud', 115200)} baud (USB serial)"
+ elif x.transport == "http":
+ det = f"hub `http://HUB_HOST:{str(ch.hub_url).rsplit(':', 1)[-1]}{ch.config.get('path', '')}`"
+ elif x.transport == "mqtt":
+ det = f"`{ch.config.get('broker')}:{ch.config.get('broker_port')}` topic `{ch.topic}`"
+ elif x.transport == "udp":
+ det = f"UDP port {ch.config.get('port', 9876)} on HUB_HOST"
+ elif x.transport == "i2c":
+ det = f"I2C master, slave address {self._i2c_addr(ch)}"
+ elif x.transport == "spi":
+ det = f"SPI master, CS pin {x.pins.get('cs', '?')}, mode 0, 1 MHz"
+ elif x.transport == "gpio":
+ det = "pins " + ", ".join(f"{f}={p}" for f, p in x.pins.items())
+ L.append(f"| {ch.id} ({ch.src.name} -> {ch.dst.name}) | {dirn} | {x.transport} | "
+ f"{', '.join(ch.fields)} | {det} |")
+ L.append("")
+ if any(x.transport in ("i2c", "spi") for x in b.chans):
+ L += ["**Bus byte protocol** (board is the master; same frame as the hardware module): a write is "
+ f"`0x{FRAME_SYNC:02X}, N, then N x int16 big-endian` (fields in channel order, values rounded, "
+ "true = 1). To read, I2C requests `2 + 2N` bytes and expects the same frame back; SPI sends "
+ f"`0x{FRAME_READ:02X}` then clocks `1 + 2N` bytes (`0x{FRAME_SYNC:02X}` + values).", ""]
+ if any(x.transport == "gpio" for x in b.chans):
+ L += ["**GPIO channels**: one wire per field, HIGH when the value is non-zero.", ""]
+ if any(x.transport in ("http", "udp", "mqtt") and not x.local for x in b.chans) and b.wifi:
+ L += ["Set `WIFI_SSID`, `WIFI_PASS` and `HUB_HOST` at the top of the sketch (and in `main.py`). "
+ "`HUB_HOST` must be the LAN IP of the PC running the python hub (`python main.py` in the "
+ "python folder) - `localhost` would be the board itself.", ""]
+ L += ["## Behaviour semantics", "",
+ "- `start` runs at the end of `setup()`; `update` runs 20 times per second; `timer:` uses `millis()`.",
+ "- `update` rules with a condition and a one-shot action (log, send, toggle, add, call, destroy) fire once "
+ "each time the condition becomes true; `set`/`move` rules apply continuously while it holds.",
+ "- `input:` fires on the debounced press of that button/switch, or when that word is typed on the "
+ "serial monitor.",
+ "- `change:` fires when the value changes; `message:` when a channel delivers data.",
+ "- `destroy` disables the entity: its outputs switch off and its behaviours stop.", ""]
+ return "\n".join(L)
+
+ # ======================================================================
+ # run
+ # ======================================================================
+ def run(self, ctx: BuildContext) -> RunResult | None:
+ cli = self.which("arduino-cli", "arduino-cli.exe")
+ if not cli:
+ return None
+ try:
+ boards = self._plan(ctx)
+ except Exception as e: # never crash the runtime
+ return RunResult(False, f"planning failed: {e}")
+ outs, ok, cmds = [], True, []
+ for b in boards:
+ d = ctx.outdir / b.ident
+ if not (d / f"{b.ident}.ino").exists():
+ return RunResult(False, "build first")
+ r = self.sh([cli, "compile", "--fqbn", b.spec["fqbn"], str(d)], ctx.outdir, timeout=300)
+ ok = ok and r.ok
+ cmds.append(r.command)
+ outs.append(f"== {b.ident} ({b.spec['fqbn']})\n{r.output}")
+ return RunResult(ok, "\n".join(outs), " && ".join(cmds))
+
+
+MODULE = EmbeddedModule()
diff --git a/nlcl/modules/game_mod.py b/nlcl/modules/game_mod.py
new file mode 100644
index 0000000000000000000000000000000000000000..62af0ea01e85c49a9dd616dca8b1329dc1ff1d18
--- /dev/null
+++ b/nlcl/modules/game_mod.py
@@ -0,0 +1,1876 @@
+"""Game domain: Unity (C#), Godot 4 (GDScript) and a self-contained HTML5 preview.
+
+Every entity becomes one script per engine. The scene is built in code (Unity:
+a RuntimeInitializeOnLoadMethod bootstrap, Godot: main.gd), so nothing has to
+be wired up by hand: drop the Scripts folder into Assets/ and press Play, or
+open godot/project.godot and press F5. preview.html simulates the same
+entities and behaviours in a browser (2D side view, AABB physics).
+
+Shared runtime code lives in _assets/game/: NlclEntity.cs, NlclHub.cs,
+NlclInput.cs (Unity), nlcl_world.gd (Godot), preview_runtime.js (preview).
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+import tempfile
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from ..ir import Entity, describe_action, expr_tokens, ident, pascal, validate_expr
+from .base import BuildContext, DomainModule, RunResult
+
+ASSETS = Path(__file__).parent / "_assets" / "game"
+
+# ---------------------------------------------------------------- kinds and looks
+KINDS: dict[str, dict] = {
+ "object": {},
+ "player": {"health": 100, "speed": 5, "movable": True, "collision": True, "gravity": True,
+ "jump_force": 8, "score": 0},
+ "character": {"health": 100, "speed": 5, "movable": True, "collision": True},
+ "npc": {"speed": 2, "collision": True},
+ "enemy": {"health": 30, "speed": 2, "damage": 10, "collision": True},
+ "coin": {"value": 1, "collision": True},
+ "pickup": {"value": 10, "collision": True},
+ "bullet": {"speed": 12, "damage": 10, "collision": True},
+ "projectile": {"speed": 12, "damage": 10, "collision": True},
+ "platform": {"collision": True},
+ "wall": {"collision": True},
+ "obstacle": {"damage": 10, "collision": True},
+ "spawner": {"spawn": "", "spawn_interval_ms": 2000, "max_spawn": 10, "collision": False},
+ "camera": {"follow": ""},
+ "level": {},
+ "cube": {},
+ "sphere": {},
+ "capsule": {},
+}
+# kind -> (shape, size (w, h, d), colour)
+LOOK = {
+ "object": ("cube", (1, 1, 1), "#94a3b8"),
+ "player": ("capsule", (0.8, 1.6, 0.8), "#3b82f6"),
+ "character": ("capsule", (0.8, 1.6, 0.8), "#6366f1"),
+ "npc": ("capsule", (0.8, 1.6, 0.8), "#a855f7"),
+ "enemy": ("cube", (1, 1, 1), "#ef4444"),
+ "coin": ("sphere", (0.6, 0.6, 0.6), "#facc15"),
+ "pickup": ("sphere", (0.7, 0.7, 0.7), "#22c55e"),
+ "bullet": ("sphere", (0.3, 0.3, 0.3), "#f97316"),
+ "projectile": ("sphere", (0.3, 0.3, 0.3), "#f97316"),
+ "platform": ("cube", (6, 0.5, 2), "#64748b"),
+ "wall": ("cube", (0.5, 4, 2), "#475569"),
+ "obstacle": ("cube", (1, 1, 1), "#b45309"),
+ "spawner": ("cube", (0.8, 0.8, 0.8), "#14b8a6"),
+ "camera": ("none", (0, 0, 0), ""),
+ "level": ("none", (0, 0, 0), ""),
+ "cube": ("cube", (1, 1, 1), "#94a3b8"),
+ "sphere": ("sphere", (1, 1, 1), "#94a3b8"),
+ "capsule": ("capsule", (1, 2, 1), "#94a3b8"),
+}
+SHAPES = {"cube": "cube", "box": "cube", "square": "cube", "rectangle": "cube", "sphere": "sphere",
+ "ball": "sphere", "circle": "sphere", "capsule": "capsule", "pill": "capsule",
+ "cylinder": "cylinder", "none": "none", "empty": "none", "invisible": "none"}
+AI_KINDS = {"enemy", "npc", "bullet", "projectile", "coin", "pickup", "platform", "wall", "obstacle",
+ "spawner", "camera", "level"}
+SOLID_KINDS = {"platform", "wall", "obstacle"}
+LAYOUT_PROPS = {"position", "pos", "x", "y", "z", "size", "width", "height", "depth", "radius",
+ "shape", "rotation", "scale"}
+REF_PROPS = ("spawn", "target", "follow") # string props that name another entity
+
+COLORS = {
+ "red": "#ef4444", "green": "#22c55e", "blue": "#3b82f6", "yellow": "#facc15", "orange": "#f97316",
+ "purple": "#a855f7", "violet": "#8b5cf6", "pink": "#ec4899", "cyan": "#06b6d4", "teal": "#14b8a6",
+ "white": "#f8fafc", "black": "#111827", "gray": "#9ca3af", "grey": "#9ca3af", "brown": "#92400e",
+ "gold": "#eab308", "silver": "#cbd5e1", "lime": "#84cc16", "magenta": "#d946ef", "navy": "#1e3a8a",
+ "maroon": "#7f1d1d", "olive": "#65a30d", "indigo": "#6366f1", "beige": "#e7d8b0",
+ "dark blue": "#1e40af", "light blue": "#93c5fd", "dark green": "#166534", "light green": "#86efac",
+ "dark red": "#991b1b", "darkblue": "#1e40af", "lightblue": "#93c5fd", "darkgreen": "#166534",
+}
+
+# ---------------------------------------------------------------- reserved names
+CS_KEYWORDS = set("""abstract as base bool break byte case catch char checked class const continue decimal
+default delegate do double else enum event explicit extern false finally fixed float for foreach goto if
+implicit in int interface internal is lock long namespace new null object operator out override params
+private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct
+switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while
+var dynamic value now fire field other key""".split())
+CS_MEMBERS = set("""name tag transform gameObject enabled isActiveAndEnabled useGUILayout hideFlags rigidbody
+rigidbody2D collider collider2D renderer camera light animation audio constantForce hingeJoint networkView
+particleSystem runInEditMode destroyCancellationToken didStart didAwake""".split())
+CS_TYPES = set("""Vector2 Vector3 Quaternion Time Mathf Debug KeyCode GameObject Color Rigidbody Collider
+Camera Light PrimitiveType Object Renderer Shader Material Physics Transform MonoBehaviour Component
+Behaviour BoxCollider SphereCollider CapsuleCollider ColorUtility RigidbodyConstraints LightType String
+Input Random Application Screen Mesh Ray RaycastHit Collision Coroutine Resources Texture Sprite
+RuntimeInitializeOnLoadMethod RuntimeInitializeLoadType RuntimeInitializeOnLoadMethodAttribute Math
+Action Array Exception Type Convert Console Enum Nlcl NlclGame NlclEntity NlclWorld NlclHub NlclInput
+NlclJson NlclSceneBuilder Ch Hit Log Jump Spawn Start Update Awake LateUpdate SetX SetY SetZ""".split())
+GD_RESERVED = set("""if elif else for while match break continue pass return class class_name extends is in
+as self signal func static const enum var breakpoint preload await yield super tool void and or not when
+true false null PI TAU INF NAN int float bool String Array Dictionary Vector2 Vector3 Color Object Node
+print str range len min max abs sign load
+name owner process_mode process_priority editor_description unique_name_in_owner scene_file_path
+multiplayer transform global_transform position rotation rotation_degrees quaternion basis scale
+rotation_edit_mode rotation_order top_level global_position global_basis global_rotation visible
+visibility_parent disable_mode collision_layer collision_mask collision_priority input_ray_pickable
+mass inertia center_of_mass physics_material_override gravity_scale custom_integrator continuous_cd
+contact_monitor max_contacts_reported sleeping can_sleep lock_rotation freeze freeze_mode
+linear_velocity linear_damp angular_velocity angular_damp constant_force constant_torque
+constant_linear_velocity constant_angular_velocity fov near far current size projection environment
+attributes keep_aspect cull_mask h_offset v_offset doppler_tracking frustum_offset compositor
+script delta event value field key other now fire""".split())
+
+UNITY_KEYS = {"space": "Space", "enter": "Return", "up": "UpArrow", "down": "DownArrow", "left": "LeftArrow",
+ "right": "RightArrow", "escape": "Escape", "shift": "LeftShift", "ctrl": "LeftControl",
+ "alt": "LeftAlt", "tab": "Tab", "backspace": "Backspace"}
+KEY_ALIASES = {"return": "enter", "esc": "escape", "spacebar": "space", "control": "ctrl",
+ "click": "mouse", "left click": "mouse", "mouse click": "mouse", "left mouse": "mouse",
+ "tap": "mouse", "touch": "mouse"}
+NUM_RE = re.compile(r"-?\d+(\.\d+)?")
+
+
+def _key(k: str) -> str:
+ k = re.sub(r"\b(key|arrow|button|bar|pressed)\b", " ", str(k).lower().replace("_", " "))
+ k = re.sub(r"\s+", " ", k).strip()
+ return KEY_ALIASES.get(k, k) or "space"
+
+
+def _ptype(v: Any) -> str:
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, (list, tuple)):
+ return "nlist" if all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in v) else "slist"
+ return "string"
+
+
+def _num(v: Any, d: float) -> float:
+ try:
+ f = float(v)
+ return f if f == f and abs(f) < 1e6 else d
+ except (TypeError, ValueError):
+ return d
+
+
+def _vec(v: Any) -> list[float] | None:
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
+ return [float(v)] * 3
+ if isinstance(v, str):
+ v = [x for x in re.split(r"[\s,;x]+", v.strip("()[] ")) if x]
+ if isinstance(v, (list, tuple)) and v:
+ out = [_num(x, 0.0) for x in list(v)[:3]]
+ return out + [0.0] * (3 - len(out))
+ return None
+
+
+def _f(x: float) -> str:
+ """Compact float for generated code."""
+ s = f"{round(float(x), 3):g}"
+ return s if s not in ("-0",) else "0"
+
+
+_BINOPS = {"&&", "||", "<", ">", "<=", ">=", "==", "!=", "+", "-", "*", "/", "%"}
+
+
+def _check_expr(expr: Any) -> str:
+ """validate_expr plus a grammar check (operands around every operator)."""
+ text = validate_expr(expr)
+ toks = expr_tokens(text)
+ pos = 0
+
+ def primary():
+ nonlocal pos
+ if pos >= len(toks):
+ raise ValueError("missing operand")
+ k, v = toks[pos]
+ if v in ("!", "-", "+") and k == "op":
+ pos += 1
+ return primary()
+ if v == "(":
+ pos += 1
+ binary()
+ if pos >= len(toks) or toks[pos][1] != ")":
+ raise ValueError("missing )")
+ pos += 1
+ return
+ if k == "op":
+ raise ValueError(f"unexpected {v!r}")
+ pos += 1
+
+ def binary():
+ nonlocal pos
+ primary()
+ while pos < len(toks) and toks[pos][0] == "op" and toks[pos][1] in _BINOPS:
+ pos += 1
+ primary()
+
+ binary()
+ if pos != len(toks):
+ raise ValueError(f"unexpected {toks[pos][1]!r}")
+ return text
+
+
+@dataclass
+class _Info:
+ e: Entity
+ id: str
+ cls: str
+ gd: str
+ kind: str
+ shape: str
+ size: tuple
+ color: str
+ controls: bool
+ auto_move: bool
+ gravity: bool
+ solid: bool
+ props: dict # name -> value (fields of the generated class)
+ behaviors: list
+ parent: str = "" # local parent id
+ pos: list = field(default_factory=lambda: [0.0, 0.0, 0.0]) # absolute
+ rel: list = field(default_factory=lambda: [0.0, 0.0, 0.0]) # relative to parent
+ explicit_pos: bool = False
+
+ @property
+ def visual(self) -> bool:
+ return self.shape != "none"
+
+
+class GameModule(DomainModule):
+ name = "game"
+ title = "Game (Unity C#, Godot 4, HTML5 preview)"
+ aliases = ("unity", "godot", "بازی")
+ keywords = ("game", "player", "enemy", "enemies", "coin", "coins", "platformer", "npc", "bullet",
+ "projectile", "pickup", "powerup", "spawner", "sprite", "boss", "arena", "unity", "godot",
+ "level", "hero", "monster", "zombie", "gem", "شخصیت", "دشمن", "سکه")
+ kinds = KINDS
+ suggested_props = ("health", "speed", "score", "damage", "color", "movable", "collision", "gravity",
+ "jump_force", "position", "size", "target", "spawn", "spawn_interval_ms")
+ protocols = ("http", "websocket")
+ toolchain = """Three free targets are generated in `game/`:
+
+* **HTML5 preview** - open `game/preview.html` in any browser (arrow keys/WASD move, space jumps,
+ click entities). Headless check: `node --check` on its script; the simulation also runs under
+ Node (`node preview.js 5` after extracting the `
+
+
+
+
+{title} preview
+
+
+
+
+
+
+
+ {title}
+
+ 0.0 s
+ {self._html(" | ".join(hints) or "no controls bound")}
+
+
+
+
+
+
+
+
+"""
+
+ @staticmethod
+ def _html(s: str) -> str:
+ return str(s).replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
+
+ # ================================================================== build
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
+ infos = self._analyse(ctx)
+ files: dict[str, str] = {}
+ for a in ("NlclEntity.cs", "NlclHub.cs", "NlclInput.cs"):
+ files[f"unity/Scripts/{a}"] = (ASSETS / a).read_text(encoding="utf-8")
+ files["unity/Scripts/NlclSceneBuilder.cs"] = self._cs_builder(ctx, infos)
+ for i in infos:
+ files[f"unity/Scripts/{i.cls}.cs"] = self._cs_entity(ctx, i)
+ files.update(self._godot(ctx, infos))
+ files["preview.html"] = self._preview(ctx, infos)
+ files["README.md"] = self._readme(ctx, infos)
+ return files
+
+ def _readme(self, ctx: BuildContext, infos: list[_Info]) -> str:
+ rows = "\n".join(f"| {i.e.name} | {i.kind} | `{i.cls}.cs` / `{i.gd}.gd` | {i.shape} | "
+ f"{'keys' if i.controls else ''}{' auto' if i.auto_move else ''}"
+ f"{' gravity' if i.gravity else ''}{' solid' if i.solid else ''} | "
+ f"{len(i.behaviors)} |" for i in infos)
+ ch = "\n".join(f"- `{c.id}`: {c.src.name} ({c.src.domain}) -> {c.dst.name} ({c.dst.domain}) via "
+ f"{c.protocol}, fields {', '.join(c.fields)}" for c in ctx.channels) or "- none"
+ return f"""# {ctx.project} - game module (generated by NLCL)
+
+| entity | kind | scripts | shape | flags | behaviours |
+|---|---|---|---|---|---|
+{rows}
+
+Channels (through the NLCL hub, start `python ../python/main.py` first):
+{ch}
+
+{self.toolchain}
+
+Conventions: x to the right, y up, z depth. Unity camera looks along +z, Godot along -z.
+Keyboard names: space, enter, up/down/left/right, a-z, 0-9, f1-f12, escape, shift, ctrl, alt, tab.
+"""
+
+ # ================================================================== run
+ def run(self, ctx: BuildContext) -> RunResult | None:
+ html = ctx.outdir / "preview.html"
+ if not html.exists():
+ return RunResult(False, "build first")
+ out = []
+ ok = True
+ try:
+ text = html.read_text(encoding="utf-8")
+ m = re.search(r"", text, re.S)
+ script = m.group(1) if m else ""
+ except OSError as e:
+ return RunResult(False, f"cannot read preview.html: {e}")
+ node = self.which("node", "nodejs")
+ cmd = ""
+ if node and script:
+ fd, tmp = tempfile.mkstemp(suffix=".js", prefix="nlcl_preview_")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ fh.write(script)
+ chk = self.sh([node, "--check", tmp], ctx.outdir, timeout=20)
+ cmd = chk.command
+ ok = chk.ok
+ out.append("node --check preview script: " + ("OK" if chk.ok else "FAILED\n" + chk.output))
+ if chk.ok:
+ sim = self.sh([node, tmp, "3"], ctx.outdir, timeout=20)
+ lines = sim.output.splitlines()
+ out.append("headless simulation (3 s):")
+ out += [" " + ln for ln in (lines[:25] + ([" ..."] if len(lines) > 40 else []) + lines[-15:]
+ if len(lines) > 40 else lines)]
+ ok = ok and sim.ok
+ finally:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ else:
+ out.append("node not found: skipped the JavaScript check")
+ cs = self._csharp_syntax(ctx)
+ if cs:
+ out.append(cs)
+ out.append(f"open {html} in a browser to play the preview")
+ if self.which("godot", "godot4"):
+ out.append(f"Godot: godot --path \"{ctx.outdir / 'godot'}\"")
+ return RunResult(ok, "\n".join(out), cmd)
+
+ def _csharp_syntax(self, ctx: BuildContext) -> str:
+ """Parse-only check of the Unity scripts with Roslyn from the .NET SDK (if installed)."""
+ dotnet = self.which("dotnet")
+ if not dotnet:
+ return ""
+ try:
+ sdks = self.sh([dotnet, "--list-sdks"], ctx.outdir, timeout=15).output.splitlines()
+ csc = None
+ for line in reversed(sdks):
+ m = re.match(r"(\S+)\s+\[(.+)\]", line.strip())
+ if m:
+ p = Path(m.group(2)) / m.group(1) / "Roslyn" / "bincore" / "csc.dll"
+ if p.exists():
+ csc = p
+ break
+ if not csc:
+ return ""
+ files = sorted(str(p) for p in (ctx.outdir / "unity" / "Scripts").glob("*.cs"))
+ tmpdir = tempfile.mkdtemp(prefix="nlcl_cs_")
+ r = self.sh([dotnet, str(csc), "-nologo", "-t:library", "-nostdlib-", f"-out:{tmpdir}/x.dll"] + files,
+ ctx.outdir, timeout=60)
+ syntax = [ln for ln in r.output.splitlines() if re.search(r"error CS1\d\d\d", ln)]
+ return ("C# syntax (Roslyn parse, Unity references not loaded): " +
+ ("OK" if not syntax else "ERRORS\n" + "\n".join(syntax[:20])))
+ except Exception as e:
+ return f"C# syntax check skipped: {e}"
+
+
+MODULE = GameModule()
diff --git a/nlcl/modules/hardware_mod.py b/nlcl/modules/hardware_mod.py
new file mode 100644
index 0000000000000000000000000000000000000000..501ad1d19c7596b552498bd6b698ab5ef3a7dd3d
--- /dev/null
+++ b/nlcl/modules/hardware_mod.py
@@ -0,0 +1,2132 @@
+"""Hardware domain: synthesizable Verilog-2005 RTL, testbench and Yosys script.
+
+Every hardware entity becomes one module (``rtl/.v``) with a single
+clocked ``always @(posedge clk)`` block (synchronous active-high reset):
+
+ reset values -> free-running timers / synchronisers -> kind core logic
+ -> values received from channels -> user behaviours (last NBA wins)
+
+``rtl/top.v`` instantiates every entity and wires the links:
+
+* hardware <-> hardware (any protocol) : parallel wires, same-named fields
+* embedded -> hardware via spi / i2c : ``nlcl_spi_slave`` / ``nlcl_i2c_slave``
+ (frame 0xA5, N, N x int16 big-endian, field order -- same as the embedded module)
+* gpio / wire with another domain : one pin per field (value != 0)
+* serial / http / mqtt / udp / websocket: a UART carrying the NLCL flat JSON
+ line ``{"channel":..,"from":..,:}\\n`` (``host_bridge.py`` relays
+ it to the hub / broker when the peer is not on the serial line itself)
+
+``sim/tb_top.v`` (Icarus / Verilator), ``synth.ys`` (Yosys) and a README are
+generated alongside. Nothing here ever raises on odd input: unknown kinds
+become a register bank and unknown names become (documented) registers.
+"""
+from __future__ import annotations
+
+import json
+import math
+import re
+from pathlib import Path
+
+from ..ir import Entity, describe_action, ident
+from .base import BuildContext, Channel, DomainModule, RunResult
+
+ASSETS = Path(__file__).parent / "_assets" / "hardware"
+
+VKEYWORDS = set("""always and assign automatic begin buf bufif0 bufif1 case casex casez cell cmos config deassign
+default defparam design disable edge else end endcase endconfig endfunction endgenerate endmodule endprimitive
+endspecify endtable endtask event for force forever fork function generate genvar highz0 highz1 if ifnone incdir
+include initial inout input instance integer join large liblist library localparam macromodule medium module nand
+negedge nmos nor noshowcancelled not notif0 notif1 or output parameter pmos posedge primitive pull0 pull1 pulldown
+pullup pulsestyle_onevent pulsestyle_ondetect rcmos real realtime reg release repeat rnmos rpmos rtran rtranif0
+rtranif1 scalared showcancelled signed small specify specparam strong0 strong1 supply0 supply1 table task time tran
+tranif0 tranif1 tri tri0 tri1 triand trior trireg unsigned use uwire vectored wait wand weak0 weak1 while wire wor
+xnor xor logic bit byte int""".split()) | set("""shortint longint string class interface package program property
+sequence final type var void return break continue struct union enum typedef import export extends const static virtual
+local protected rand randc priority unique chandle bind clocking constraint covergroup do foreach inside new null super
+this with wildcard assert assume cover expect alias before context dist solve tagged iff intersect throughout within
+modport ref restrict soft let checker global implies nettype interconnect untyped shortreal""".split())
+RESERVED = {"clk", "rst", "top", "tb_top"}
+PARAM_PROPS = {"width", "clock_hz", "baud", "interval_ms", "depth", "stable_ms", "divide_by", "frequency_hz",
+ "states", "init", "active_low", "pin", "pins", "board", "address", "subtype", "for_entity",
+ "position", "rotation", "scale", "size", "color", "label", "model", "units", "shape"}
+BUS_TO_WIRE = {"wire", "gpio"}
+SIM_CLOCK_HZ = 1_000_000
+
+# kind synonyms -> canonical kind
+KIND_ALIAS = {
+ "multiplexer": "mux", "state_machine": "fsm", "statemachine": "fsm", "led_driver": "blinker",
+ "memory": "ram", "bram": "ram", "dff": "flipflop", "flip_flop": "flipflop", "shifter": "shift_register",
+ "shiftregister": "shift_register", "clockdivider": "clock_divider", "prescaler": "clock_divider",
+ "uart": "uart_tx", "uart_transmitter": "uart_tx", "uart_receiver": "uart_rx", "seven_seg": "seven_segment",
+ "sevenseg": "seven_segment", "seg7": "seven_segment", "pwm_generator": "pwm", "debounce": "debouncer",
+ "register_bank": "object", "regfile": "object", "machine": "fsm", "finite_state_machine": "fsm",
+ "blink": "blinker", "divider": "clock_divider",
+}
+
+# kind -> spec. regs: name -> (width | "W", init) ; pins_in: 1-bit input pins ; pins_out: regs exposed as pins
+SPECS = {
+ "object": dict(regs={}, pins_in=[], pins_out=[], primary=[]),
+ "counter": dict(regs={"count": ("W", 0)}, pins_in=[], pins_out=[], primary=["count"]),
+ "register": dict(regs={"value": ("W", 0)}, pins_in=[], pins_out=[], primary=["value"]),
+ "adder": dict(regs={"a": ("W", 0), "b": ("W", 0), "sum": ("W", 0), "carry": (1, 0)},
+ pins_in=[], pins_out=[], primary=["sum", "carry"]),
+ "alu": dict(regs={"a": ("W", 0), "b": ("W", 0), "op": (3, 0), "result": ("W", 0), "zero": (1, 0)},
+ pins_in=[], pins_out=[], primary=["result", "zero"]),
+ "mux": dict(regs={"a": ("W", 0), "b": ("W", 0), "sel": (1, 0), "y": ("W", 0)},
+ pins_in=[], pins_out=[], primary=["y"]),
+ "comparator": dict(regs={"a": ("W", 0), "b": ("W", 0), "eq": (1, 0), "lt": (1, 0), "gt": (1, 0)},
+ pins_in=[], pins_out=[], primary=["eq", "lt", "gt"]),
+ "shift_register": dict(regs={"value": ("W", 0), "serial_in": (1, 0), "serial_out": (1, 0)},
+ pins_in=[], pins_out=["serial_out"], primary=["value"]),
+ "clock_divider": dict(regs={"clk_out": (1, 0), "tick": (1, 0)}, pins_in=[], pins_out=["clk_out"],
+ primary=["clk_out"]),
+ "pwm": dict(regs={"duty": ("W", 0), "out": (1, 0)}, pins_in=[], pins_out=["out"], primary=["out"]),
+ "uart_tx": dict(regs={"data": (8, 0), "start": (1, 0), "busy": (1, 0), "tx": (1, 1)},
+ pins_in=[], pins_out=["tx"], primary=["busy"]),
+ "uart_rx": dict(regs={"data": (8, 0), "valid": (1, 0)}, pins_in=["rx"], pins_out=[], primary=["data", "valid"]),
+ "fsm": dict(regs={}, pins_in=[], pins_out=[], primary=["state"]),
+ "blinker": dict(regs={"led": (1, 0)}, pins_in=[], pins_out=["led"], primary=["led"]),
+ "debouncer": dict(regs={"out": (1, 0), "pressed": (1, 0)}, pins_in=["btn"], pins_out=[], primary=["out"]),
+ "ram": dict(regs={"addr": ("A", 0), "data_in": ("W", 0), "we": (1, 0), "data_out": ("W", 0)},
+ pins_in=[], pins_out=[], primary=["data_out"]),
+ "flipflop": dict(regs={"d": (1, 0), "q": (1, 0)}, pins_in=[], pins_out=[], primary=["q"]),
+ "seven_segment": dict(regs={"value": ("W", 0), "seg": (7, 0)}, pins_in=[], pins_out=["seg"], primary=[]),
+}
+DEFAULT_WIDTH = {"flipflop": 1, "seven_segment": 4}
+
+
+def vname(s) -> str:
+ n = ident(str(s)) or "x"
+ if n in VKEYWORDS or n in RESERVED or n.startswith("nl_"):
+ n = n + "_v"
+ return n
+
+
+def clog2(n: int) -> int:
+ return max(1, math.ceil(math.log2(max(2, n))))
+
+
+def to_int(v, default=0) -> int:
+ try:
+ if isinstance(v, bool):
+ return int(v)
+ if isinstance(v, (int, float)):
+ return int(round(v))
+ return int(float(str(v)))
+ except (TypeError, ValueError, OverflowError):
+ return default
+
+
+def need_bits(v: int) -> int:
+ return max(1, abs(v).bit_length() + (1 if v < 0 else 0))
+
+
+def vstr(text: str) -> str:
+ """ASCII-safe body of a Verilog string literal."""
+ out = []
+ for ch in str(text):
+ if ch == "\\":
+ out.append("\\\\")
+ elif ch == '"':
+ out.append('\\"')
+ elif ch == "\n":
+ out.append("\\n")
+ elif 32 <= ord(ch) < 127:
+ out.append(ch)
+ else:
+ out.append("?")
+ return "".join(out)
+
+
+def vcom(text) -> str:
+ """ASCII-safe text for a // comment (no string escaping, single line)."""
+ return "".join(ch if 32 <= ord(ch) < 127 else (" " if ord(ch) in (9, 10, 13) else "?") for ch in str(text))
+
+
+def lit(v: int, w: int) -> str:
+ v = to_int(v)
+ if v < 0:
+ return f"-{w}'sd{min(-v, (1 << w) - 1)}"
+ return f"{w}'d{v & ((1 << w) - 1)}"
+
+
+class Reg:
+ __slots__ = ("name", "width", "signed", "init", "note")
+
+ def __init__(self, name, width, init=0, signed=False, note=""):
+ self.name, self.width, self.init, self.signed, self.note = name, width, init, signed, note
+
+ def decl(self) -> str:
+ rng = f"[{self.width - 1}:0] " if self.width > 1 else ""
+ return f"reg {'signed ' if self.signed else ''}{rng}{self.name};"
+
+
+class Plan:
+ """Everything needed to emit one entity module and its instance in top."""
+
+ def __init__(self, e: Entity):
+ self.e = e
+ self.mod = ""
+ self.kind = "object"
+ self.W = 8
+ self.clock_hz = 50_000_000
+ self.regs: dict[str, Reg] = {}
+ self.pins_in: list[str] = []
+ self.pins_out: list[str] = []
+ self.primary: list[str] = []
+ self.states: list[str] = []
+ self.xrefs: dict[tuple[str, str], str] = {} # (other ident, prop) -> port name
+ self.xstates: dict[str, "Plan"] = {} # port reading another fsm's state -> that plan
+ self.triggers: dict[str, str] = {} # trigger key -> port name in_
+ self.timers: list[int] = []
+ self.changes: list[str] = []
+ self.in_chans: list[Channel] = []
+ self.out_chans: list[Channel] = []
+ self.uses_send = False
+ self.uses_start = False
+ self.comments: list[str] = []
+ self.body: list[str] = [] # rendered behaviour lines
+ self.local_params: list[str] = []
+ self.skip: set = set() # behaviour indexes re-homed to another entity
+ self.extra: list[dict] = [] # behaviours re-homed here from another entity
+ self.moved: list[str] = [] # notes about re-homed behaviours
+
+
+class HardwareModule(DomainModule):
+ name = "hardware"
+ title = "Hardware (synthesizable Verilog-2005 RTL, testbench, Yosys)"
+ aliases = ("hardware", "verilog", "fpga", "rtl", "hdl", "سختافزار", "سخت_افزار", "سختافزاری")
+ keywords = ("fpga", "verilog", "rtl", "hdl", "asic", "cpld", "alu", "flipflop", "flip-flop", "dff", "mux",
+ "multiplexer", "demux", "register", "shift_register", "adder", "comparator", "debouncer",
+ "clock_divider", "yosys", "iverilog", "icarus", "gtkwave", "verilator", "testbench", "lut",
+ "bitstream", "ice40", "ecp5", "synthesis", "netlist", "uart_tx", "uart_rx", "bram",
+ "state_machine", "fsm", "seven_segment", "led_driver", "blinker")
+ kinds = {
+ "object": {"width": 8},
+ "counter": {"count": 0, "width": 8},
+ "register": {"value": 0, "width": 8},
+ "adder": {"a": 0, "b": 0, "sum": 0, "carry": False, "width": 8},
+ "alu": {"a": 0, "b": 0, "op": 0, "result": 0, "zero": False, "width": 8},
+ "mux": {"a": 0, "b": 0, "sel": False, "y": 0, "width": 8},
+ "multiplexer": {"a": 0, "b": 0, "sel": False, "y": 0, "width": 8},
+ "comparator": {"a": 0, "b": 0, "eq": False, "lt": False, "gt": False, "width": 8},
+ "shift_register": {"value": 0, "serial_in": False, "serial_out": False, "width": 8},
+ "clock_divider": {"divide_by": 2, "clk_out": False, "tick": False},
+ "pwm": {"duty": 0, "out": False, "width": 8},
+ "uart_tx": {"baud": 115200, "data": 0, "start": False, "busy": False, "tx": True},
+ "uart_rx": {"baud": 115200, "data": 0, "valid": False},
+ "fsm": {"states": ["idle", "run", "done"], "state": "idle"},
+ "state_machine": {"states": ["idle", "run", "done"], "state": "idle"},
+ "blinker": {"interval_ms": 500, "led": False},
+ "led_driver": {"interval_ms": 500, "led": False},
+ "debouncer": {"stable_ms": 10, "out": False, "pressed": False},
+ "ram": {"depth": 16, "addr": 0, "data_in": 0, "we": False, "data_out": 0, "width": 8},
+ "memory": {"depth": 16, "addr": 0, "data_in": 0, "we": False, "data_out": 0, "width": 8},
+ "flipflop": {"d": False, "q": False},
+ "dff": {"d": False, "q": False},
+ "seven_segment": {"value": 0, "seg": 0, "width": 4},
+ }
+ suggested_props = ("width", "clock_hz", "duty", "interval_ms", "baud", "states", "depth")
+ protocols = ("wire", "gpio", "spi", "i2c", "serial", "http", "mqtt", "udp", "websocket")
+ toolchain = """All tools are free / open source:
+
+- **Icarus Verilog + GTKWave** (simulate, view waves):
+ `iverilog -g2005 -DSIMULATION -s tb_top -o build/sim.vvp sim/tb_top.v -c files.f` (files.f lists rtl/*.v; works in PowerShell too)
+ then `vvp build/sim.vvp` and `gtkwave tb_top.vcd`
+ (Windows installer: bleyer.org/icarus ; Linux: `apt install iverilog gtkwave`)
+- **Verilator** (lint / fast C++ sim): `verilator --lint-only -Wall -Wno-fatal -DSIMULATION --top-module top -f files.f`
+- **Yosys** (synthesis, OSS CAD Suite): `yosys -s synth.ys` (generic gates + stats; edit for `synth_ice40` / `synth_ecp5`)
+- **No install**: paste `rtl/*.v` + `sim/tb_top.v` into https://www.edaplayground.com (Icarus, tick "Open EPWave")
+- `host_bridge.py` (stdlib; `pip install pyserial`) relays the FPGA UART JSON lines to the NLCL hub / MQTT / UDP."""
+
+ # ------------------------------------------------------------------ props
+ def default_props(self, kind: str) -> dict:
+ k = self._canon(kind)
+ base = self.kinds.get(kind) or self.kinds.get(k) or self.kinds["object"]
+ return json.loads(json.dumps(base))
+
+ def validate(self, e: Entity) -> list[str]:
+ out = []
+ try:
+ w = to_int(e.props.get("width", 8), 8)
+ if w < 1 or w > 32:
+ out.append(f"width {w} clamped to 1..32 bits")
+ kind = self._kind(e)
+ if kind == "object" and e.kind not in ("object", "register_bank"):
+ out.append(f"hardware kind '{e.kind}' is not built in; generated a register bank "
+ f"(known: {', '.join(k for k in SPECS if k != 'object')})")
+ if kind == "pwm" and to_int(e.props.get("duty", 0)) > (1 << max(1, min(32, w))) - 1:
+ out.append("duty is larger than 2^width-1 (output will be always high)")
+ if kind == "fsm" and not isinstance(e.props.get("states"), (list, tuple)):
+ out.append("fsm 'states' should be a list, e.g. states idle, run, done")
+ hz = to_int(e.props.get("clock_hz", 50_000_000), 0)
+ if hz <= 0:
+ out.append("clock_hz must be positive; using 50000000")
+ except Exception: # never raise
+ pass
+ return out
+
+ # ------------------------------------------------------------------ helpers
+ @staticmethod
+ def _canon(kind: str) -> str:
+ k = ident(kind or "object")
+ return KIND_ALIAS.get(k, k)
+
+ def _kind(self, e: Entity) -> str:
+ k = self._canon(e.kind)
+ if k in SPECS:
+ return k
+ sub = e.props.get("subtype")
+ if isinstance(sub, str) and self._canon(sub) in SPECS:
+ return self._canon(sub)
+ if k == "object" or k not in SPECS:
+ st = e.props.get("states")
+ if isinstance(st, (list, tuple)) and st:
+ return "fsm" # "a state machine" may arrive as kind=machine/object with states
+ # "a shift register" may arrive as kind=register name=shift_register
+ name = ident(e.name)
+ cands = sorted(set(SPECS) | set(KIND_ALIAS), key=len, reverse=True)
+ for c in cands:
+ if c != "object" and len(c) > 2 and c in name:
+ kk = KIND_ALIAS.get(c, c)
+ if kk in SPECS and kk != "object":
+ return kk
+ return "object"
+
+ @staticmethod
+ def _cid(c: Channel) -> str:
+ return vname("ch_" + ident(c.id))
+
+ @staticmethod
+ def _wire_like(c: Channel) -> bool:
+ return c.src.domain == c.dst.domain == "hardware"
+
+ # ------------------------------------------------------------------ planning
+ def _plan(self, ctx: BuildContext, e: Entity, used_mods: set) -> Plan:
+ p = Plan(e)
+ p.kind = self._kind(e)
+ spec = SPECS[p.kind]
+ p.W = max(1, min(32, to_int(e.props.get("width", DEFAULT_WIDTH.get(p.kind, 8)), 8)))
+ hz = to_int(e.props.get("clock_hz", 50_000_000), 50_000_000)
+ p.clock_hz = hz if hz > 0 else 50_000_000
+ mod = vname(e.ident)
+ if mod in used_mods or mod.startswith("nlcl_"):
+ mod = mod + "_m"
+ used_mods.add(mod)
+ p.mod = mod
+ p.pins_in = list(spec["pins_in"])
+ p.pins_out = list(spec["pins_out"])
+ p.primary = list(spec["primary"])
+ depth = max(2, min(65536, to_int(e.props.get("depth", 16), 16)))
+ for n, (w, init) in spec["regs"].items():
+ width = p.W if w == "W" else (clog2(depth) if w == "A" else w)
+ pv = e.props.get(n, init)
+ iv = to_int(pv, init) if isinstance(pv, (int, float, bool)) else init
+ if w == "W" and iv and need_bits(iv) > width:
+ width = min(32, need_bits(iv))
+ p.regs[n] = Reg(n, width, iv, iv < 0)
+ if p.kind == "fsm":
+ st = e.props.get("states")
+ if isinstance(st, str):
+ st = [s for s in re.split(r"[,\s]+", st) if s]
+ if not isinstance(st, (list, tuple)) or not st:
+ st = ["idle", "run", "done"]
+ seen = []
+ for s in st:
+ n = ident(str(s)) or f"s{len(seen)}"
+ if n not in seen:
+ seen.append(n)
+ # "set state to closed": a bare / quoted name that is not a property becomes a new state
+ for b in e.behaviors or []:
+ for a in b.get("do") or []:
+ if isinstance(a, dict) and a.get("op") == "set" and a.get("prop") == "state":
+ v = str(a.get("value", "")).strip().strip("'\"")
+ # (the interpreter may have auto-added the name as a 0 property)
+ if re.fullmatch(r"[A-Za-z_]\w*", v) and e.props.get(v, 0) in (0, None) \
+ and v not in ("true", "false") and ident(v) not in seen:
+ seen.append(ident(v))
+ p.states = seen
+ init = e.props.get("state", 0)
+ idx = seen.index(ident(str(init))) if isinstance(init, str) and ident(init) in seen else \
+ max(0, min(len(seen) - 1, to_int(init, 0)))
+ p.regs["state"] = Reg("state", clog2(len(seen)), idx, note="one of S_*")
+ # free-form numeric / bool props
+ idents = sorted({x.ident for x in ctx.entities}, key=len, reverse=True)
+ for k, v in e.props.items():
+ if k.startswith("_") or k in PARAM_PROPS:
+ continue
+ n = vname(k)
+ if n in p.regs or n in p.pins_in:
+ continue
+ if any(ident(k).startswith(o + "_") and len(ident(k)) > len(o) + 1 for o in idents) or \
+ (ident(k) in idents and ident(k) != e.ident):
+ continue # "traffic state" flattened to traffic_state: resolved as traffic.state by the namer
+ if ident(k) == e.ident and p.primary and p.primary[0] in p.regs:
+ continue # "" used as a property means its main value
+ if p.kind == "fsm" and (ident(k) == e.ident or ident(k) in p.states):
+ continue
+ if isinstance(v, bool):
+ p.regs[n] = Reg(n, 1, int(v))
+ elif isinstance(v, (int, float)):
+ iv = to_int(v)
+ note = f"float {v} stored as integer" if isinstance(v, float) and v != iv else ""
+ p.regs[n] = Reg(n, min(32, max(p.W, need_bits(iv))), iv, iv < 0, note)
+ else:
+ txt = json.dumps(v, ensure_ascii=True) if not isinstance(v, str) else vstr(v)
+ p.comments.append(f"{k} = {txt} (not synthesizable data, kept as a note)")
+ # channel fields exist on both ends
+ for c in ctx.channels_for(e):
+ if c.dst.id == e.id:
+ p.in_chans.append(c)
+ if c.src.id == e.id:
+ p.out_chans.append(c)
+ for f in c.fields:
+ n = vname(f)
+ if n not in p.regs and n not in p.pins_in:
+ if c.dst.id == e.id and not self._wire_like(c) and c.protocol not in BUS_TO_WIRE:
+ # other domains send int16 words: keep sign and range (e.g. -5 or 300 degrees)
+ p.regs[n] = Reg(n, max(p.W, 16), 0, True, note=f"channel field ({c.id}), int16")
+ else:
+ p.regs[n] = Reg(n, p.W, 0, note=f"channel field ({c.id})")
+ if p.kind == "object":
+ p.primary = list(p.regs)[:8]
+ return p
+
+ # ------------------------------------------------------------------ expressions
+ def _namer(self, ctx: BuildContext, p: Plan, plans: dict[str, Plan]):
+ e = p.e
+
+ def local(n: str) -> str:
+ v = vname(n)
+ if p.states and ident(n) in p.states:
+ return f"S_{ident(n).upper()}"
+ if v in p.pins_in:
+ return v
+ if v not in p.regs and ident(n) == e.ident:
+ # "increase leds by 1" on the register named leds -> its main value
+ main = [x for x in p.primary if x in p.regs] or list(p.regs)
+ if main:
+ return main[0]
+ if v not in p.regs:
+ # "temperature" while a sensor called temp delivers its 'value' over a link
+ idn = ident(n)
+ for c in p.in_chans:
+ s_id, s_kind = c.src.ident, ident(c.src.kind)
+ if len(idn) >= 3 and (idn.startswith(s_id) or (len(s_id) >= 3 and s_id.startswith(idn))
+ or idn == s_kind):
+ fl = [vname(x) for x in c.fields if vname(x) in p.regs]
+ num = [x for x in fl if p.regs[x].width > 1]
+ pick = "value" if "value" in fl else (num[0] if len(num) == 1 else None)
+ if pick:
+ return pick
+ p.regs[v] = Reg(v, p.W, 0, note="implicit: first used in a behaviour")
+ return v
+
+ def f(n: str) -> str:
+ if "." not in n and vname(n) not in p.regs and vname(n) not in p.pins_in:
+ # "traffic state" may arrive flattened as traffic_state -> traffic.state
+ idn = ident(n)
+ for other in sorted(plans, key=len, reverse=True):
+ if idn.startswith(other + "_") and len(idn) > len(other) + 1:
+ n = f"{other}.{idn[len(other) + 1:]}"
+ break
+ if "." not in n:
+ if n in plans and n != e.ident: # bare entity name -> its primary value
+ other = plans[n]
+ pr = (other.primary or list(other.regs) or ["value"])[0]
+ return f(f"{n}.{pr}")
+ return local(n)
+ ent, prop = n.split(".", 1)
+ prop = prop.replace(".", "_")
+ if ent in (e.ident, "self", "this"):
+ return local(prop)
+ if ent in plans: # same domain: wire from the other module
+ other = plans[ent]
+ pv = vname(prop)
+ if pv not in other.regs and pv not in other.pins_in:
+ other.regs[pv] = Reg(pv, other.W, 0, note=f"implicit: read by {e.ident}")
+ port = vname(f"x_{ent}_{prop}")
+ p.xrefs[(ent, pv)] = port
+ if pv == "state" and other.states:
+ p.xstates[port] = other
+ return port
+ # other domain: last value received via a channel
+ for c in p.in_chans:
+ if c.src.ident == ent and prop in [ident(x) for x in c.fields]:
+ return local(prop)
+ v = vname(f"x_{ent}_{prop}")
+ if v not in p.regs:
+ p.regs[v] = Reg(v, p.W, 0, note=f"{ent}.{prop}: no channel delivers it (connect {ent} to {e.ident})")
+ return v
+ return f
+
+ def _vexpr(self, ex, name) -> str:
+ try:
+ s = self.expr(ex, "verilog", name)
+ except Exception:
+ return "0 /* invalid expression */"
+ return re.sub(r"(? str:
+ # another fsm's state compared with a state name -> that fsm's encoding
+ for port, other in p.xstates.items():
+ def enc(m, other=other):
+ st = ident(m.group("lit"))
+ if st not in other.states:
+ return m.group(0)
+ w = other.regs["state"].width if "state" in other.regs else 8
+ return m.group(0).replace(f'"{m.group("lit")}"', f"{w}'d{other.states.index(st)}")
+ s = re.sub(rf'\b{port}\s*(==|!=)\s*"(?P[^"]*)"', enc, s)
+ s = re.sub(rf'"(?P[^"]*)"\s*(==|!=)\s*{port}\b', enc, s)
+ if not p.states:
+ return s
+ return re.sub(r'"([^"]*)"', lambda m: f"S_{ident(m.group(1)).upper()}" if ident(m.group(1)) in p.states
+ else m.group(0), s)
+
+ # ------------------------------------------------------------------ behaviours
+ def _render_behaviours(self, ctx: BuildContext, p: Plan, plans: dict[str, Plan]) -> None:
+ name = self._namer(ctx, p, plans)
+ L = []
+ own = [b for i, b in enumerate(p.e.behaviors or []) if i not in p.skip]
+ for i, b in enumerate(own + p.extra):
+ try:
+ L += self._behaviour(ctx, p, b, name, i)
+ except Exception as ex: # never raise
+ L.append(f"// behaviour {i} skipped: {vcom(ex)}")
+ p.body = L
+ # a register compared with / set to a constant wider than itself ("timer > 3000" on an
+ # implicit 8-bit register) would be silently truncated: widen it to fit the constant
+ try:
+ code = "\n".join(x for x in L if not x.lstrip().startswith("//"))
+ for r in p.regs.values():
+ if r.name == "state" and p.states:
+ continue
+ pat = rf"\b{re.escape(r.name)}\s*(?:==|!=|<=|>=|<|>|\+|-)\s*(\d+)\b(?!')"
+ vals = [int(m) for m in re.findall(pat, code)]
+ vals += [int(m) for m in re.findall(rf"(?=|<|>)\s*{re.escape(r.name)}\b", code)]
+ if vals and need_bits(max(vals)) > r.width and r.width > 1:
+ r.width = min(32, need_bits(max(vals)))
+ except Exception:
+ pass
+
+ def _behaviour(self, ctx, p: Plan, b: dict, name, i: int) -> list[str]:
+ on = str(b.get("on") or "update")
+ trig, label = None, on
+ if on == "start":
+ trig = "!nl_started"
+ p.uses_start = True
+ elif on == "update":
+ trig = None
+ elif on.startswith("timer:"):
+ ms = min(10**12, max(1, to_int(on.split(":", 1)[1], 1000)))
+ if ms not in p.timers:
+ p.timers.append(ms)
+ trig = f"nl_tick_{ms}"
+ elif on.startswith("input:") and p.kind == "debouncer" and \
+ ident(on.split(":", 1)[1]) in (p.e.ident, "button", "btn", "press", "pressed", "key"):
+ trig = "pressed" # the debounced one-clock press pulse
+ elif on.startswith("input:") or on == "collision":
+ key = vname(on.split(":", 1)[1] if ":" in on else "collision")
+ port = vname(f"in_{key}")
+ p.triggers[key] = port
+ trig = f"nl_{port}_rise"
+ elif on.startswith("change:"):
+ prop = name(on.split(":", 1)[1])
+ if prop.startswith("S_"):
+ return [f"// on {vcom(label)}: a constant never changes"]
+ if prop not in p.changes:
+ p.changes.append(prop)
+ trig = f"({prop} != nl_prev_{prop})"
+ elif on.startswith("message:"):
+ src = on.split(":", 1)[1]
+ conds = []
+ for c in p.in_chans:
+ if src in ("any", "*") or c.src.ident == ident(src) or c.src.name == src or c.src.id == src:
+ cid = self._cid(c)
+ if self._wire_like(c) or c.protocol in BUS_TO_WIRE:
+ diffs = " || ".join(f"({self._conv_in(p, cid, vname(fl))} != {vname(fl)})" for fl in c.fields
+ if vname(fl) in p.regs) or "1'b0"
+ conds.append(f"(i_{cid}_we && ({diffs}))")
+ else:
+ conds.append(f"i_{cid}_we")
+ trig = " || ".join(conds) if conds else "1'b0 /* no channel from " + vstr(src) + " */"
+ if len(conds) > 1:
+ trig = f"({trig})"
+ else:
+ trig = "1'b0 /* unsupported trigger */"
+ cond = None
+ if b.get("if"):
+ cond = self._fix_states(p, self._vexpr(b["if"], name))
+ parts = []
+ if trig:
+ parts.append(trig if re.fullmatch(r"!?\w+|\(.*\)", trig) else f"({trig})")
+ if cond:
+ parts.append(f"({cond})")
+ test = " && ".join(parts)
+ acts = []
+ for a in b.get("do") or []:
+ acts += self._action(p, a, name)
+ head = f"// on {vcom(label)}" + (f" if {vcom(b.get('if'))}" if b.get("if") else "")
+ if not test:
+ return [head] + acts
+ return [head, f"if ({test}) begin"] + [" " + x for x in acts] + ["end"]
+
+ @staticmethod
+ def _target_of(prop: str, src: str, plans: dict) -> str | None:
+ n = ident(str(prop).split(".", 1)[0]) if "." in str(prop) else ident(prop)
+ if "." in str(prop):
+ return n if n in plans else None
+ if n in plans:
+ return n
+ for o in sorted(plans, key=len, reverse=True):
+ if n.startswith(o + "_") and len(n) > len(o) + 1:
+ return o
+ return None
+
+ def _rehome(self, plans: dict[str, Plan]) -> None:
+ """A register lives in exactly one module, so a behaviour whose actions all write another
+ hardware entity ("when button is pressed, increase pulses by 1" stored on button) is moved
+ into that entity; its trigger / condition then read the source through a cross-module port."""
+ for src, p in list(plans.items()):
+ for i, b in enumerate(p.e.behaviors or []):
+ if not isinstance(b, dict):
+ continue
+ on = str(b.get("on") or "update")
+ if on.startswith("message:"):
+ continue
+ writes = [a for a in b.get("do") or [] if isinstance(a, dict) and a.get("op") in ("set", "add", "toggle")]
+ others = [a for a in b.get("do") or [] if isinstance(a, dict) and a.get("op") not in ("set", "add", "toggle", "log")]
+ if not writes or others:
+ continue
+ tg = {self._target_of(a.get("prop", ""), src, plans) for a in writes}
+ if len(tg) != 1:
+ continue
+ t = tg.pop()
+ srcp = set(p.regs) | set(p.pins_in)
+ if t is None:
+ # "set duty to 200" while a clock divider is in focus: the one other entity whose
+ # kind owns every written register gets the behaviour
+ props = {vname(a.get("prop", "")) for a in writes}
+ own = set(SPECS[p.kind]["regs"]) | set(p.pins_in) | ({"state"} if p.states else set())
+ if props & own:
+ continue
+ cands = [k for k, o in plans.items() if k != src and props <= (
+ set(SPECS[o.kind]["regs"]) | ({"state"} if o.states else set()))]
+ if len(cands) != 1:
+ continue
+ t = cands[0]
+ srcp = own # names the source merely picked up stay bare (resolved in the target)
+ if t == src:
+ continue
+ q = plans[t]
+
+ def qual(ex, src=src, srcp=srcp):
+ if ex is None:
+ return None
+ parts = re.split(r'("[^"]*")', str(ex))
+ for j in range(0, len(parts), 2):
+ parts[j] = re.sub(r'(? str:
+ r = p.regs.get(f)
+ w = r.width if r else p.W
+ port = f"i_{cid}_{f}"
+ if w == 1:
+ return f"({port} != 32'd0)"
+ return f"{port}[{w - 1}:0]"
+
+ def _action(self, p: Plan, a: dict, name) -> list[str]:
+ op = a.get("op")
+ if op in ("set", "add", "toggle"):
+ prop = name(a["prop"])
+ if prop.startswith("S_") or prop in p.pins_in:
+ return [f"// cannot assign {vcom(a['prop'])} (constant or input pin)"]
+ if prop.startswith("x_") and prop not in p.regs:
+ return [f"// {vcom(a['prop'])} belongs to another module; send it through a link instead"]
+ r = p.regs.get(prop)
+ w = r.width if r else p.W
+ if op == "toggle":
+ return [f"{prop} <= !{prop};" if w > 1 else f"{prop} <= ~{prop};"]
+ val = self._fix_states(p, self._vexpr(a.get("value", 0), name))
+ if op == "add":
+ m = re.fullmatch(r"-\s*(.+)", val.strip())
+ if m:
+ # "decrease health by 10": a free-form register may go below zero, so it becomes
+ # signed (one extra bit keeps its range) and "health < 1" still fires after 5 - 10
+ if r is not None and not r.signed and r.width > 1 and r.name not in SPECS[p.kind]["regs"] \
+ and r.name != "state":
+ r.signed = True
+ r.width = min(32, r.width + 1)
+ inner = m.group(1)
+ if not re.fullmatch(r"[\w']+|\(.*\)", inner):
+ inner = f"({inner})"
+ return [f"{prop} <= {prop} - {inner};"]
+ return [f"{prop} <= {prop} + {val};"]
+ if w == 1 and val not in ("1'b0", "1'b1", "0", "1"):
+ val = f"(({val}) != 0)"
+ return [f"{prop} <= {val};"]
+ if op == "destroy":
+ return ["nl_alive <= 1'b0; // destroy: module stops updating"]
+ if op == "log":
+ text = str(a.get("text", ""))
+ args = []
+
+ def sub(m):
+ try:
+ args.append(name(ident(m.group(1)) if "." not in m.group(1) else m.group(1)))
+ except Exception:
+ return "?"
+ return "@@NLARG@@"
+ t = re.sub(r"\{([^{}]+)\}", sub, text.replace("@@NLARG@@", ""))
+ t = vstr(t).replace("%", "%%").replace("@@NLARG@@", "%0d")
+ argtxt = "".join(f", {x}" for x in args)
+ return ["`ifdef SIMULATION",
+ f'$display("[%0t] {p.e.ident}: {t}", $time{argtxt});',
+ "`endif"]
+ if op == "move":
+ out = []
+ for ax in ("x", "y", "z"):
+ v = str(a.get(ax, "0"))
+ if v not in ("0", "0.0"):
+ reg = name(f"pos_{ax}")
+ out.append(f"{reg} <= {reg} + {self._vexpr(v, name)};")
+ return out or ["// move by zero"]
+ if op == "send":
+ p.uses_send = True
+ return ["nl_send <= 1'b1; // publish linked fields now"]
+ if op == "call":
+ args = ", ".join(self._vexpr(x, name) for x in a.get("args", []))
+ fn = vstr(a.get("name", "fn"))
+ return [f"// TODO: call {fn}({args}) - implement as logic here",
+ "`ifdef SIMULATION", f'$display("[%0t] {p.e.ident}: call {fn}", $time);', "`endif"]
+ return [f"// {vcom(describe_action(a)) if isinstance(a, dict) and 'op' in a else 'unknown action'}"]
+
+ # ------------------------------------------------------------------ kind core logic
+ def _core(self, p: Plan) -> tuple[list[str], list[str], list[str], list[str]]:
+ """-> (declarations, reset lines, free-running lines, gated core lines)."""
+ k, W, R, e = p.kind, p.W, p.regs, p.e
+ D, RS, FR, C = [], [], [], []
+ has = lambda n: n in R # noqa: E731
+
+ def ms_param(name, ms):
+ D.append(f"localparam [39:0] {name}_RAW = (40'd0 + CLOCK_HZ / 1000) * 40'd{ms};")
+ D.append(f"localparam [39:0] {name} = ({name}_RAW == 40'd0) ? 40'd1 : {name}_RAW;")
+
+ driven = any(re.search(r"^\s*count <=", x) for x in p.body)
+ if k == "counter" and driven and not has("enable") and not has("step"):
+ C.append("// count is written by the behaviours below (no free-running increment)")
+ elif k == "counter":
+ step = "step" if has("step") else f"{R['count'].width}'d1"
+ inner = []
+ if has("max"):
+ inner = [f"if (max != 0 && count >= max) count <= {R['count'].width}'d0;",
+ f"else count <= count + {step};"]
+ else:
+ inner = [f"count <= count + {step};"]
+ if has("enable"):
+ C += ["if (enable) begin"] + [" " + x for x in inner] + ["end"]
+ else:
+ C += inner
+ elif k == "register":
+ if has("load") and has("d"):
+ C.append("if (load) value <= d;")
+ else:
+ C.append("// holds 'value'; written by behaviours / channels (add props d + load for a load port)")
+ elif k == "adder":
+ cin = " + cin" if has("cin") else ""
+ C.append(f"{{carry, sum}} <= a + b{cin};")
+ elif k == "alu":
+ rw = R["result"].width
+ D += [f"// op: 0 ADD, 1 SUB, 2 AND, 3 OR, 4 XOR, 5 SHL1, 6 SHR1, 7 SLT",
+ f"wire [{rw - 1}:0] nl_alu_y = (op == 3'd0) ? a + b :",
+ " (op == 3'd1) ? a - b :",
+ " (op == 3'd2) ? a & b :",
+ " (op == 3'd3) ? a | b :",
+ " (op == 3'd4) ? a ^ b :",
+ " (op == 3'd5) ? a << 1 :",
+ " (op == 3'd6) ? a >> 1 :",
+ f" ((a < b) ? {rw}'d1 : {rw}'d0);"]
+ C += ["result <= nl_alu_y;", f"zero <= (nl_alu_y == {rw}'d0);"]
+ elif k == "mux":
+ C.append("y <= sel ? b : a;")
+ elif k == "comparator":
+ C += ["eq <= (a == b);", "lt <= (a < b);", "gt <= (a > b);"]
+ elif k == "shift_register":
+ vw = R["value"].width
+ sh = f"value <= {{value[{vw - 2}:0], serial_in}};" if vw > 1 else "value <= serial_in;"
+ C += (["if (shift) begin", " " + sh, "end"] if has("shift") else [sh])
+ C.append(f"serial_out <= value[{vw - 1}];" if vw > 1 else "serial_out <= value;")
+ elif k == "clock_divider":
+ fq = to_int(e.props.get("frequency_hz", 0), 0)
+ if fq > 0:
+ D.append(f"localparam [39:0] NL_HALF_RAW = (40'd0 + CLOCK_HZ) / (40'd2 * 40'd{fq});")
+ else:
+ dv = max(2, to_int(e.props.get("divide_by", 2), 2))
+ D.append(f"localparam [39:0] NL_HALF_RAW = 40'd{dv // 2};")
+ D += ["localparam [39:0] NL_HALF = (NL_HALF_RAW == 40'd0) ? 40'd1 : NL_HALF_RAW;",
+ "reg [39:0] nl_div;"]
+ RS.append("nl_div <= 40'd0;")
+ C += ["tick <= 1'b0;",
+ "if (nl_div >= NL_HALF - 40'd1) begin",
+ " nl_div <= 40'd0;",
+ " clk_out <= ~clk_out;",
+ " tick <= ~clk_out; // one-clk pulse on every rising edge of clk_out",
+ "end else begin",
+ " nl_div <= nl_div + 40'd1;",
+ "end"]
+ elif k == "pwm":
+ dw = R["duty"].width
+ fq = to_int(e.props.get("frequency_hz", 0), 0)
+ if fq > 0:
+ D.append(f"localparam [39:0] NL_PRE_RAW = (40'd0 + CLOCK_HZ) / (40'd{fq} * 40'd{1 << dw});")
+ else:
+ D.append("localparam [39:0] NL_PRE_RAW = 40'd1; // set frequency_hz to slow the PWM down")
+ D += ["localparam [39:0] NL_PRE = (NL_PRE_RAW == 40'd0) ? 40'd1 : NL_PRE_RAW;",
+ f"reg [{dw - 1}:0] nl_pwm_cnt;", "reg [39:0] nl_pre;"]
+ RS += [f"nl_pwm_cnt <= {dw}'d0;", "nl_pre <= 40'd0;"]
+ C += ["if (nl_pre >= NL_PRE - 40'd1) begin",
+ " nl_pre <= 40'd0;",
+ f" nl_pwm_cnt <= nl_pwm_cnt + {dw}'d1;",
+ "end else begin",
+ " nl_pre <= nl_pre + 40'd1;",
+ "end",
+ ("out <= enable && (nl_pwm_cnt < duty);" if has("enable") else "out <= (nl_pwm_cnt < duty);")]
+ elif k == "uart_tx":
+ baud = max(1, to_int(e.props.get("baud", 115200), 115200))
+ D += [f"localparam [31:0] NL_BAUD_RAW = CLOCK_HZ / {baud};",
+ "localparam [31:0] NL_BAUD_DIV = (NL_BAUD_RAW == 0) ? 1 : NL_BAUD_RAW;",
+ "reg [31:0] nl_tx_div;", "reg [3:0] nl_tx_bit;", "reg [9:0] nl_tx_sh;"]
+ RS += ["nl_tx_div <= 32'd0;", "nl_tx_bit <= 4'd0;", "nl_tx_sh <= 10'h3FF;"]
+ dsl = "data[7:0]" if R["data"].width >= 8 else f"{{{8 - R['data'].width}'d0, data}}"
+ C += ["// 8N1: write 'data' then pulse 'start'; 'busy' is high while shifting",
+ "if (!busy) begin",
+ " tx <= 1'b1;",
+ " if (start) begin",
+ f" nl_tx_sh <= {{1'b1, {dsl}, 1'b0}};",
+ " nl_tx_bit <= 4'd0;",
+ " nl_tx_div <= 32'd0;",
+ " busy <= 1'b1;",
+ " start <= 1'b0;",
+ " end",
+ "end else begin",
+ " tx <= nl_tx_sh[0];",
+ " if (nl_tx_div == NL_BAUD_DIV - 1) begin",
+ " nl_tx_div <= 32'd0;",
+ " nl_tx_sh <= {1'b1, nl_tx_sh[9:1]};",
+ " if (nl_tx_bit == 4'd9) busy <= 1'b0;",
+ " else nl_tx_bit <= nl_tx_bit + 4'd1;",
+ " end else begin",
+ " nl_tx_div <= nl_tx_div + 32'd1;",
+ " end",
+ "end"]
+ elif k == "uart_rx":
+ baud = max(1, to_int(e.props.get("baud", 115200), 115200))
+ D += [f"localparam [31:0] NL_BAUD_RAW = CLOCK_HZ / {baud};",
+ "localparam [31:0] NL_BAUD_DIV = (NL_BAUD_RAW == 0) ? 1 : NL_BAUD_RAW;",
+ "reg [2:0] nl_rx_s;", "reg nl_rx_busy;", "reg [31:0] nl_rx_div;", "reg [3:0] nl_rx_bit;",
+ "reg [7:0] nl_rx_sh;"]
+ RS += ["nl_rx_s <= 3'b111;", "nl_rx_busy <= 1'b0;", "nl_rx_div <= 32'd0;", "nl_rx_bit <= 4'd0;",
+ "nl_rx_sh <= 8'd0;"]
+ FR.append("nl_rx_s <= {nl_rx_s[1:0], rx};")
+ dw = R["data"].width
+ dval = "nl_rx_sh" if dw == 8 else (f"nl_rx_sh[{dw - 1}:0]" if dw < 8 else f"{{{dw - 8}'d0, nl_rx_sh}}")
+ C += ["// 8N1 receiver: 'data' + one-clk 'valid' pulse per byte",
+ "valid <= 1'b0;",
+ "if (!nl_rx_busy) begin",
+ " if (!nl_rx_s[2]) begin",
+ " nl_rx_busy <= 1'b1;",
+ " nl_rx_div <= NL_BAUD_DIV / 2;",
+ " nl_rx_bit <= 4'd0;",
+ " end",
+ "end else if (nl_rx_div >= NL_BAUD_DIV - 1) begin",
+ " nl_rx_div <= 32'd0;",
+ " if (nl_rx_bit == 4'd0) begin",
+ " if (nl_rx_s[2]) nl_rx_busy <= 1'b0; // glitch, not a start bit",
+ " else nl_rx_bit <= 4'd1;",
+ " end else if (nl_rx_bit <= 4'd8) begin",
+ " nl_rx_sh <= {nl_rx_s[2], nl_rx_sh[7:1]};",
+ " nl_rx_bit <= nl_rx_bit + 4'd1;",
+ " end else begin",
+ " nl_rx_busy <= 1'b0;",
+ " if (nl_rx_s[2]) begin",
+ f" data <= {dval};",
+ " valid <= 1'b1;",
+ " end",
+ " end",
+ "end else begin",
+ " nl_rx_div <= nl_rx_div + 32'd1;",
+ "end"]
+ elif k == "fsm":
+ for i, s in enumerate(p.states):
+ D.append(f"localparam [{R['state'].width - 1}:0] S_{s.upper()} = {R['state'].width}'d{i};")
+ writes_state = any(a.get("prop") == "state" for b in (e.behaviors or []) for a in b.get("do", [])
+ if isinstance(a, dict))
+ if not writes_state:
+ last = f"S_{p.states[-1].upper()}"
+ step = f" state <= (state == {last}) ? S_{p.states[0].upper()} : state + 1'b1;"
+ if "advance" in R: # a property / link drives it
+ D.append("reg nl_adv_q;")
+ RS.append("nl_adv_q <= 1'b0;")
+ C += ["// default sequencing: each rising edge of 'advance' moves to the next state",
+ "nl_adv_q <= advance;", "if (advance && !nl_adv_q)", step]
+ else: # no driver: expose 'advance' as a (synchronised) input pin
+ if "advance" not in p.pins_in:
+ p.pins_in.append("advance")
+ D.append("reg [2:0] nl_adv_s;")
+ RS.append("nl_adv_s <= 3'b000;")
+ FR.append("nl_adv_s <= {nl_adv_s[1:0], advance};")
+ C += ["// default sequencing: each rising edge of the 'advance' pin moves to the next state",
+ "if (nl_adv_s[2:1] == 2'b01)", step]
+ else:
+ C.append("// transitions are written by the behaviours below")
+ elif k == "blinker":
+ ms = max(1, to_int(e.props.get("interval_ms", 500), 500))
+ ms_param("NL_HALF", ms)
+ D.append("reg [39:0] nl_blink;")
+ RS.append("nl_blink <= 40'd0;")
+ body = ["if (nl_blink >= NL_HALF - 40'd1) begin", " nl_blink <= 40'd0;", " led <= ~led;",
+ "end else begin", " nl_blink <= nl_blink + 40'd1;", "end"]
+ C += (["if (enable) begin"] + [" " + x for x in body] + ["end"]) if has("enable") else body
+ elif k == "debouncer":
+ ms = max(1, to_int(e.props.get("stable_ms", 10), 10))
+ ms_param("NL_STABLE", ms)
+ D += ["reg [2:0] nl_btn_s;", "reg [39:0] nl_db_cnt;"]
+ RS += ["nl_btn_s <= 3'b000;", "nl_db_cnt <= 40'd0;"]
+ inv = "~" if e.props.get("active_low") else ""
+ FR.append(f"nl_btn_s <= {{nl_btn_s[1:0], {inv}btn}};")
+ C += ["pressed <= 1'b0;",
+ "if (nl_btn_s[2] == out) begin",
+ " nl_db_cnt <= 40'd0;",
+ "end else if (nl_db_cnt >= NL_STABLE - 40'd1) begin",
+ " nl_db_cnt <= 40'd0;",
+ " out <= nl_btn_s[2];",
+ " pressed <= nl_btn_s[2]; // one-clk pulse on a clean press",
+ "end else begin",
+ " nl_db_cnt <= nl_db_cnt + 40'd1;",
+ "end"]
+ elif k == "ram":
+ depth = max(2, min(65536, to_int(e.props.get("depth", 16), 16)))
+ dw = R["data_out"].width
+ D += [f"localparam DEPTH = {depth};", f"reg [{dw - 1}:0] nl_mem [0:DEPTH-1];"]
+ init = e.props.get("init")
+ if isinstance(init, (list, tuple)) and init:
+ D.append("initial begin")
+ for i, v in enumerate(list(init)[:depth]):
+ D.append(f" nl_mem[{i}] = {lit(to_int(v), dw)};")
+ D.append("end")
+ C += ["if (we) nl_mem[addr] <= data_in;", "data_out <= nl_mem[addr]; // synchronous read (BRAM)"]
+ elif k == "flipflop":
+ C.append("if (en) q <= d;" if has("en") else "q <= d;")
+ elif k == "seven_segment":
+ D += ["// segments {g,f,e,d,c,b,a}, active high (set active_low true for common-anode)",
+ "function [6:0] nl_seg7;", " input [3:0] v;", " begin", " case (v)"]
+ codes = [0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71]
+ for i, c in enumerate(codes):
+ D.append(f" 4'h{i:X}: nl_seg7 = 7'h{c:02X};")
+ D += [" default: nl_seg7 = 7'h00;", " endcase", " end", "endfunction"]
+ # "connect counter to display": show the first linked field when no link carries 'value'
+ src = "value"
+ linked = [vname(f) for c in p.in_chans for f in c.fields if vname(f) in R]
+ writes_value = any(isinstance(a, dict) and a.get("prop") == "value"
+ for b in (e.behaviors or []) for a in (b.get("do") or []))
+ if linked and "value" not in linked and not writes_value:
+ src = linked[0]
+ C.append(f"// shows linked field '{src}' (no link or behaviour writes 'value')")
+ vw = R[src].width
+ vv = f"{src}[3:0]" if vw >= 4 else (f"{{{4 - vw}'d0, {src}}}" if vw < 4 else src)
+ C.append(f"seg <= {'~' if e.props.get('active_low') else ''}nl_seg7({vv});")
+ else:
+ C.append("// register bank: one register per numeric/bool property")
+ return D, RS, FR, C
+
+ # ------------------------------------------------------------------ emit module
+ def _module(self, ctx: BuildContext, p: Plan) -> str:
+ D, RS, FR, C = self._core(p)
+ e = p.e
+ R = p.regs
+ L = ["`timescale 1ns / 1ps", "`default_nettype none",
+ f"// {e.name}: hardware {e.kind}" + (f" (built as {p.kind})" if p.kind != e.kind else "")
+ + " - generated by NLCL, edit freely.",
+ "// Synchronous active-high reset; every register updates on posedge clk."]
+ for c in p.comments:
+ L.append(f"// note: {c}")
+ for c in p.moved:
+ L.append(f"// note: {c}")
+ for b in e.behaviors or []:
+ try:
+ L.append("// rule: on " + vcom(b.get("on")) + (f" if {vcom(b.get('if'))}" if b.get("if") else "")
+ + " -> " + vcom("; ".join(describe_action(a) for a in b.get("do", []))))
+ except Exception:
+ pass
+ ports = ["input wire clk", "input wire rst"]
+ for pin in p.pins_in:
+ ports.append(f"input wire {pin}")
+ for key, port in p.triggers.items():
+ ports.append(f"input wire {port}")
+ for (ent, prop), port in p.xrefs.items():
+ w = self._other_width(ctx, ent, prop)
+ ports.append(f"input wire {self._rng(w)}{port}")
+ for c in p.in_chans:
+ cid = self._cid(c)
+ for f in c.fields:
+ ports.append(f"input wire [31:0] i_{cid}_{vname(f)}")
+ ports.append(f"input wire i_{cid}_we")
+ for n, r in R.items():
+ ports.append(f"output wire {'signed ' if r.signed else ''}{self._rng(r.width)}o_{n}")
+ if p.out_chans:
+ ports.append("output wire o_send")
+ L.append(f"module {p.mod} #(")
+ L.append(f" parameter CLOCK_HZ = {p.clock_hz}")
+ L.append(") (")
+ L.append(",\n".join(" " + x for x in ports))
+ L.append(");")
+ L.append(f" localparam WIDTH = {p.W};")
+ # declarations
+ for n, r in R.items():
+ L.append(f" {r.decl()}" + (f" // {vcom(r.note)}" if r.note else ""))
+ L.append(" reg nl_alive; // cleared by 'destroy'")
+ if p.uses_start:
+ L.append(" reg nl_started;")
+ if p.out_chans or p.uses_send:
+ L.append(" reg nl_send; // one-clk pulse from a 'send' action")
+ def tw(ms): # timer width: 40 bits, more for very long periods (e.g. hours at 100 MHz)
+ return min(64, max(40, (ms * max(p.clock_hz, 100_000_000) // 1000).bit_length() + 1))
+ for ms in p.timers:
+ t = tw(ms)
+ L.append(f" localparam [{t - 1}:0] NL_T{ms}_RAW = ({t}'d0 + CLOCK_HZ / 1000) * {t}'d{ms};")
+ L.append(f" localparam [{t - 1}:0] NL_T{ms} = (NL_T{ms}_RAW == {t}'d0) ? {t}'d1 : NL_T{ms}_RAW;")
+ L.append(f" reg [{t - 1}:0] nl_tmr_{ms};")
+ L.append(f" reg nl_tick_{ms}; // one-clk pulse every {ms} ms")
+ for key, port in p.triggers.items():
+ L.append(f" reg [2:0] nl_{port}_s;")
+ L.append(f" wire nl_{port}_rise = (nl_{port}_s[2:1] == 2'b01);")
+ for prop in p.changes:
+ r = R.get(prop)
+ L.append(f" reg {self._rng(r.width if r else p.W)}nl_prev_{prop};")
+ for d in D:
+ L.append(" " + d)
+ for n in R:
+ L.append(f" assign o_{n} = {n};")
+ if p.out_chans:
+ L.append(" assign o_send = " + ("nl_send;" if p.uses_send else "1'b0;"))
+ L.append("")
+ L.append(" always @(posedge clk) begin")
+ L.append(" if (rst) begin")
+ rs = [f"{n} <= {lit(r.init, r.width)};" for n, r in R.items()]
+ rs.append("nl_alive <= 1'b1;")
+ if p.uses_start:
+ rs.append("nl_started <= 1'b0;")
+ if p.out_chans or p.uses_send:
+ rs.append("nl_send <= 1'b0;")
+ for ms in p.timers:
+ rs += [f"nl_tmr_{ms} <= {tw(ms)}'d0;", f"nl_tick_{ms} <= 1'b0;"]
+ for key, port in p.triggers.items():
+ rs.append(f"nl_{port}_s <= 3'b000;")
+ for prop in p.changes:
+ r = R.get(prop)
+ rs.append(f"nl_prev_{prop} <= {lit(r.init if r else 0, r.width if r else p.W)};")
+ rs += RS
+ L += [" " + x for x in rs]
+ L.append(" end else begin")
+ fr = []
+ if p.out_chans or p.uses_send:
+ fr.append("nl_send <= 1'b0;")
+ for ms in p.timers:
+ t = tw(ms)
+ fr += [f"if (nl_tmr_{ms} >= NL_T{ms} - {t}'d1) begin",
+ f" nl_tmr_{ms} <= {t}'d0;", f" nl_tick_{ms} <= 1'b1;",
+ "end else begin", f" nl_tmr_{ms} <= nl_tmr_{ms} + {t}'d1;", f" nl_tick_{ms} <= 1'b0;", "end"]
+ for key, port in p.triggers.items():
+ fr.append(f"nl_{port}_s <= {{nl_{port}_s[1:0], {port}}};")
+ fr += FR
+ L += [" " + x for x in fr]
+ L.append(" if (nl_alive) begin")
+ g = ["// ---- " + p.kind + " core ----"] + C
+ if p.in_chans:
+ g.append("// ---- values received from links ----")
+ for c in p.in_chans:
+ cid = self._cid(c)
+ g.append(f"if (i_{cid}_we) begin // {vcom(c.src.name)} ({c.src.domain}) via {c.protocol}")
+ for f in c.fields:
+ fv = vname(f)
+ if fv in R:
+ g.append(f" {fv} <= {self._conv_in(p, cid, fv)};")
+ g.append("end")
+ if p.body:
+ g.append("// ---- behaviours ----")
+ g += p.body
+ if p.uses_start:
+ g.append("nl_started <= 1'b1;")
+ L += [" " + x for x in g]
+ L.append(" end")
+ for prop in p.changes:
+ L.append(f" nl_prev_{prop} <= {prop};")
+ L.append(" end")
+ L.append(" end")
+ L.append("endmodule")
+ L.append("`default_nettype wire")
+ return "\n".join(L) + "\n"
+
+ @staticmethod
+ def _rng(w: int) -> str:
+ return f"[{w - 1}:0] " if w > 1 else ""
+
+ def _other_width(self, ctx, ent: str, prop: str) -> int:
+ p = self._plans.get(ent)
+ if p and prop in p.regs:
+ return p.regs[prop].width
+ return 1 if p and prop in p.pins_in else (p.W if p else 8)
+
+ # ------------------------------------------------------------------ json uart bridges
+ def _json_tx(self, c: Channel, cid: str) -> str:
+ n = len(c.fields)
+ items: list[tuple[int, int, str]] = []
+
+ def text(s):
+ for ch in s.encode("ascii", "replace"):
+ items.append((0, ch, chr(ch) if 32 <= ch < 127 and ch not in (92,) else f"0x{ch:02X}"))
+ text('{"channel":' + json.dumps(str(c.id), ensure_ascii=True) + ',"from":'
+ + json.dumps(str(c.src.ident), ensure_ascii=True))
+ for i, f in enumerate(c.fields):
+ text(',' + json.dumps(str(f), ensure_ascii=True) + ':')
+ items.append((1, i, f"field {f}"))
+ text("}\n")
+ items.append((2, 0, "end"))
+ L = ["`timescale 1ns / 1ps", "`default_nettype none",
+ f"// UART JSON transmitter for channel {vcom(c.id)}: {vcom(c.src.name)} -> {vcom(c.dst.name)} "
+ f"({c.dst.domain}, {c.protocol})",
+ f"// Sends one line every INTERVAL_MS (or on 'send'): {vcom(''.join(chr(x[1]) if x[0] == 0 else '<' + x[2][6:] + '>' for x in items[:-1]).strip())}",
+ "// Field values are int16 (two's complement) printed in decimal.",
+ f"module nlcl_json_tx_{cid} #(",
+ " parameter CLOCK_HZ = 50000000,",
+ f" parameter BAUD = {int(c.config.get('baud', 115200))},",
+ f" parameter INTERVAL_MS = {max(1, to_int(c.config.get('interval_ms', 1000), 1000))}",
+ ") (",
+ " input wire clk,", " input wire rst,", " input wire send,",
+ f" input wire [{16 * n - 1}:0] words,", " output reg tx", ");",
+ " localparam [31:0] BAUD_RAW = CLOCK_HZ / BAUD;",
+ " localparam [31:0] BAUD_DIV = (BAUD_RAW == 0) ? 1 : BAUD_RAW;",
+ " localparam [39:0] TICKS_RAW = (40'd0 + CLOCK_HZ / 1000) * INTERVAL_MS;",
+ " localparam [39:0] TICKS = (TICKS_RAW == 40'd0) ? 40'd1 : TICKS_RAW;",
+ " localparam S_IDLE = 3'd0, S_FETCH = 3'd1, S_DIG = 3'd2, S_EMIT = 3'd3;",
+ " // template ROM: {kind[1:0], data[7:0]} kind 0 = literal byte, 1 = field index, 2 = end",
+ " function [9:0] rom;", " input [9:0] a;", " begin", " case (a)"]
+ for i, (kd, d, cm) in enumerate(items):
+ L.append(f" 10'd{i}: rom = {{2'd{kd}, 8'h{d:02X}}}; // {vcom(cm).replace('*/', '')}")
+ L += [" default: rom = {2'd2, 8'h00};", " endcase", " end", " endfunction",
+ " function [16:0] pw10;", " input [2:0] pl;", " begin", " case (pl)",
+ " 3'd0: pw10 = 17'd10000;", " 3'd1: pw10 = 17'd1000;",
+ " 3'd2: pw10 = 17'd100;", " 3'd3: pw10 = 17'd10;",
+ " default: pw10 = 17'd1;", " endcase", " end", " endfunction",
+ " reg [39:0] tmr;", " reg [9:0] idx;", " reg [2:0] st;", " reg [2:0] ret;",
+ " reg [2:0] place;", " reg [3:0] digit;", " reg [16:0] val;", " reg started;",
+ f" reg [{16 * n - 1}:0] snap;", " reg [7:0] ch;",
+ " reg [9:0] sh;", " reg [3:0] bitn;", " reg [31:0] div;", " reg ubusy;",
+ " wire [9:0] r = rom(idx);",
+ f" wire [15:0] cur = snap[{16 * n - 1} - 16*r[7:0] -: 16];",
+ "",
+ " always @(posedge clk) begin",
+ " if (rst) begin",
+ " tmr <= 40'd0; idx <= 10'd0; st <= S_IDLE; ret <= S_IDLE; place <= 3'd0;",
+ " digit <= 4'd0; val <= 17'd0; started <= 1'b0; snap <= 0; ch <= 8'd0;",
+ " sh <= 10'h3FF; bitn <= 4'd0; div <= 32'd0; ubusy <= 1'b0; tx <= 1'b1;",
+ " end else begin",
+ " tmr <= (tmr >= TICKS - 40'd1) ? 40'd0 : tmr + 40'd1;",
+ " // ---- 8N1 shifter ----",
+ " tx <= ubusy ? sh[0] : 1'b1;",
+ " if (ubusy) begin",
+ " if (div == BAUD_DIV - 1) begin",
+ " div <= 32'd0;",
+ " sh <= {1'b1, sh[9:1]};",
+ " if (bitn == 4'd9) ubusy <= 1'b0;",
+ " else bitn <= bitn + 4'd1;",
+ " end else begin",
+ " div <= div + 32'd1;",
+ " end",
+ " end",
+ " // ---- line formatter ----",
+ " case (st)",
+ " S_IDLE: if (send || tmr >= TICKS - 40'd1) begin",
+ " snap <= words;",
+ " idx <= 10'd0;",
+ " st <= S_FETCH;",
+ " end",
+ " S_FETCH: begin",
+ " case (r[9:8])",
+ " 2'd0: begin ch <= r[7:0]; idx <= idx + 10'd1; ret <= S_FETCH; st <= S_EMIT; end",
+ " 2'd1: begin",
+ " place <= 3'd0; digit <= 4'd0; started <= 1'b0;",
+ " if (cur[15]) begin",
+ " val <= {1'b0, ~cur + 16'd1};",
+ " ch <= 8'h2D; // '-'",
+ " ret <= S_DIG;",
+ " st <= S_EMIT;",
+ " end else begin",
+ " val <= {1'b0, cur};",
+ " st <= S_DIG;",
+ " end",
+ " end",
+ " default: st <= S_IDLE;",
+ " endcase",
+ " end",
+ " S_DIG: begin",
+ " if (val >= pw10(place)) begin",
+ " val <= val - pw10(place);",
+ " digit <= digit + 4'd1;",
+ " end else begin",
+ " digit <= 4'd0;",
+ " place <= place + 3'd1;",
+ " if (place == 3'd4) idx <= idx + 10'd1;",
+ " if (digit != 4'd0 || started || place == 3'd4) begin",
+ " ch <= 8'h30 + {4'd0, digit};",
+ " started <= 1'b1;",
+ " ret <= (place == 3'd4) ? S_FETCH : S_DIG;",
+ " st <= S_EMIT;",
+ " end",
+ " end",
+ " end",
+ " S_EMIT: if (!ubusy) begin",
+ " sh <= {1'b1, ch, 1'b0};",
+ " bitn <= 4'd0;",
+ " div <= 32'd0;",
+ " ubusy <= 1'b1;",
+ " st <= ret;",
+ " end",
+ " default: st <= S_IDLE;",
+ " endcase",
+ " end",
+ " end",
+ "endmodule", "`default_nettype wire"]
+ return "\n".join(L) + "\n"
+
+ def _json_rx(self, c: Channel, cid: str) -> str:
+ n = len(c.fields)
+ pats = ['"' + str(f) + '":' for f in c.fields]
+ chan_seen = '"channel":'
+ chan_id = '"channel":' + json.dumps(str(c.id), ensure_ascii=True)
+ K = max([len(x.encode("ascii", "replace")) for x in pats + [chan_seen, chan_id]] + [2])
+
+ def vl(s):
+ return '"' + vstr(s) + '"'
+ L = ["`timescale 1ns / 1ps", "`default_nettype none",
+ f"// UART JSON receiver for channel {vcom(c.id)}: {vcom(c.src.name)} ({c.src.domain}, {c.protocol}) "
+ f"-> {vcom(c.dst.name)}",
+ "// Parses newline-terminated flat JSON lines such as",
+ "// {" + (chan_id + ', "from": "x", ' + ", ".join(f"{p} 12" for p in pats)).encode("ascii", "replace").decode() + "}",
+ "// Spaces are ignored, integers / true / false accepted, fractions truncated.",
+ "// 'words' (int16 per field, field order) updates and 'valid' pulses at the end of each line",
+ "// that belongs to this channel (or carries no \"channel\" key).",
+ f"module nlcl_json_rx_{cid} #(",
+ " parameter CLOCK_HZ = 50000000,",
+ f" parameter BAUD = {int(c.config.get('baud', 115200))}",
+ ") (",
+ " input wire clk,", " input wire rst,", " input wire rx,",
+ f" output reg [{16 * n - 1}:0] words,", " output reg valid", ");",
+ " localparam [31:0] BAUD_RAW = CLOCK_HZ / BAUD;",
+ " localparam [31:0] BAUD_DIV = (BAUD_RAW == 0) ? 1 : BAUD_RAW;",
+ " localparam P_SCAN = 2'd0, P_PRE = 2'd1, P_NUM = 2'd2, P_SKIP = 2'd3;",
+ " // ---- 8N1 receiver ----",
+ " reg [2:0] rs;", " reg rbusy;", " reg [31:0] rdiv;", " reg [3:0] rbit;", " reg [7:0] rsh;",
+ " reg [7:0] rb;", " reg rbv;",
+ " // ---- parser ----",
+ f" reg [{8 * K - 1}:0] win;", f" wire [{8 * K - 1}:0] win_n = {{win[{8 * K - 9}:0], rb}};",
+ f" reg [{16 * n - 1}:0] buf_w;", " reg [1:0] ps;", " reg [7:0] fld;", " reg neg;",
+ " reg [19:0] acc;", " reg got;", " reg chan_seen;", " reg chan_ok;",
+ " wire is_digit = (rb >= 8'h30) && (rb <= 8'h39);",
+ " wire [3:0] dval = rb[3:0];",
+ f" wire m_chan = (win_n[{8 * len(chan_seen) - 1}:0] == {vl(chan_seen)});",
+ f" wire m_chan_id = (win_n[{8 * len(chan_id.encode('ascii', 'replace')) - 1}:0] == {vl(chan_id)});"]
+ for i, pt in enumerate(pats):
+ L.append(f" wire m_{i} = (win_n[{8 * len(pt.encode('ascii', 'replace')) - 1}:0] == {vl(pt)});")
+ L += [" wire [15:0] acc16 = acc[15:0];",
+ " wire [15:0] num = neg ? (~acc16 + 16'd1) : acc16;",
+ "",
+ " always @(posedge clk) begin",
+ " if (rst) begin",
+ " rs <= 3'b111; rbusy <= 1'b0; rdiv <= 32'd0; rbit <= 4'd0; rsh <= 8'd0;",
+ " rb <= 8'd0; rbv <= 1'b0; win <= 0; buf_w <= 0; words <= 0; valid <= 1'b0;",
+ " ps <= P_SCAN; fld <= 8'd0; neg <= 1'b0; acc <= 20'd0; got <= 1'b0;",
+ " chan_seen <= 1'b0; chan_ok <= 1'b0;",
+ " end else begin",
+ " rs <= {rs[1:0], rx};",
+ " rbv <= 1'b0;",
+ " valid <= 1'b0;",
+ " if (!rbusy) begin",
+ " if (!rs[2]) begin rbusy <= 1'b1; rdiv <= BAUD_DIV / 2; rbit <= 4'd0; end",
+ " end else if (rdiv >= BAUD_DIV - 1) begin",
+ " rdiv <= 32'd0;",
+ " if (rbit == 4'd0) begin",
+ " if (rs[2]) rbusy <= 1'b0; else rbit <= 4'd1;",
+ " end else if (rbit <= 4'd8) begin",
+ " rsh <= {rs[2], rsh[7:1]};",
+ " rbit <= rbit + 4'd1;",
+ " end else begin",
+ " rbusy <= 1'b0;",
+ " if (rs[2]) begin rb <= rsh; rbv <= 1'b1; end",
+ " end",
+ " end else begin",
+ " rdiv <= rdiv + 32'd1;",
+ " end",
+ " if (rbv) begin",
+ " if (rb == 8'h0A) begin",
+ " if (got && (chan_ok || !chan_seen)) begin",
+ " words <= buf_w;",
+ " valid <= 1'b1;",
+ " end",
+ " got <= 1'b0; chan_seen <= 1'b0; chan_ok <= 1'b0; ps <= P_SCAN; win <= 0;",
+ " end else if (rb == 8'h20 || rb == 8'h0D || rb == 8'h09) begin",
+ " if (ps == P_NUM) begin",
+ f" buf_w[{16 * n - 1} - 16*fld -: 16] <= num;",
+ " got <= 1'b1;",
+ " ps <= P_SCAN;",
+ " end",
+ " end else begin",
+ " win <= win_n;",
+ " case (ps)",
+ " P_SCAN: begin",
+ " if (m_chan) chan_seen <= 1'b1;",
+ " if (m_chan_id) chan_ok <= 1'b1;"]
+ for i in range(n):
+ L.append(f" if (m_{i}) begin fld <= 8'd{i}; ps <= P_PRE; end")
+ L += [" end",
+ " P_PRE: begin",
+ " neg <= 1'b0;",
+ " acc <= 20'd0;",
+ " if (rb == 8'h2D) begin neg <= 1'b1; ps <= P_NUM; end",
+ " else if (is_digit) begin acc <= {16'd0, dval}; ps <= P_NUM; end",
+ " else if (rb == 8'h74) begin // true",
+ f" buf_w[{16 * n - 1} - 16*fld -: 16] <= 16'd1; got <= 1'b1; ps <= P_SCAN;",
+ " end else if (rb == 8'h66) begin // false",
+ f" buf_w[{16 * n - 1} - 16*fld -: 16] <= 16'd0; got <= 1'b1; ps <= P_SCAN;",
+ " end else ps <= P_SCAN;",
+ " end",
+ " P_NUM: begin",
+ " if (is_digit) begin",
+ " if (acc < 20'd100000) acc <= acc * 20'd10 + {16'd0, dval};",
+ " end else begin",
+ f" buf_w[{16 * n - 1} - 16*fld -: 16] <= num;",
+ " got <= 1'b1;",
+ " ps <= (rb == 8'h2E) ? P_SKIP : P_SCAN; // '.' -> skip fraction",
+ " end",
+ " end",
+ " default: if (!is_digit) ps <= P_SCAN;",
+ " endcase",
+ " end",
+ " end",
+ " end",
+ " end",
+ "endmodule", "`default_nettype wire"]
+ return "\n".join(L) + "\n"
+
+ # ------------------------------------------------------------------ top
+ def _to16(self, expr: str, w: int, signed: bool) -> str:
+ if w == 16:
+ return expr
+ if w > 16:
+ return f"{expr}[15:0]"
+ if w == 1:
+ return f"{{15'd0, {expr}}}"
+ if signed:
+ return f"{{{{{16 - w}{{{expr}[{w - 1}]}}}}, {expr}}}"
+ return f"{{{16 - w}'d0, {expr}}}"
+
+ def _to32(self, expr: str, w: int, signed: bool) -> str:
+ if w >= 32:
+ return expr
+ if signed and w > 1:
+ return f"{{{{{32 - w}{{{expr}[{w - 1}]}}}}, {expr}}}"
+ return f"{{{32 - w}'d0, {expr}}}"
+
+ def _src_value(self, p: Plan, f: str, tports: dict) -> tuple[str, int, bool]:
+ fv = vname(f)
+ if fv in p.regs:
+ r = p.regs[fv]
+ return f"w_{p.e.ident}__{fv}", r.width, r.signed
+ if fv in p.pins_in:
+ return f"{p.e.ident}_{fv}", 1, False
+ return "1'b0", 1, False
+
+ def _top(self, ctx: BuildContext, plans: dict[str, Plan]) -> tuple[str, list[dict], dict[str, str]]:
+ """-> (top.v text, top port descriptors, extra rtl files)."""
+ ports: list[dict] = []
+ extra: dict[str, str] = {}
+ body: list[str] = []
+ hw_ids = {p.e.id for p in plans.values()}
+ conn: dict[str, dict[str, str]] = {k: {} for k in plans}
+
+ def port(name, d, w=1, **role):
+ ports.append(dict(name=name, dir=d, width=w, **role))
+
+ for key, p in plans.items():
+ for pin in p.pins_in:
+ port(f"{key}_{pin}", "input", 1, role="uart_rx" if p.kind == "uart_rx" else
+ ("button" if p.kind == "debouncer" else "pin"), ent=key,
+ baud=to_int(p.e.props.get("baud", 115200), 115200),
+ hold_ms=to_int(p.e.props.get("stable_ms", 10), 10) * 3)
+ conn[key][pin] = f"{key}_{pin}"
+ for trig, tport in p.triggers.items():
+ if trig in plans and trig != key:
+ other = plans[trig]
+ pr = (other.primary or list(other.regs) or [None])[0]
+ if pr and pr in other.regs:
+ conn[key][tport] = f"|w_{trig}__{pr}"
+ continue
+ port(f"{key}_{tport}", "input", 1, role="trigger", ent=key)
+ conn[key][tport] = f"{key}_{tport}"
+ for (ent, prop), xport in p.xrefs.items():
+ other = plans.get(ent)
+ if other and prop in other.regs:
+ conn[key][xport] = f"w_{ent}__{prop}"
+ elif other and prop in other.pins_in:
+ conn[key][xport] = f"{ent}_{prop}"
+ else:
+ conn[key][xport] = "0"
+ for n, r in p.regs.items():
+ body.append(f" wire {'signed ' if r.signed else ''}{self._rng(r.width)}w_{key}__{n};")
+ conn[key][f"o_{n}"] = f"w_{key}__{n}"
+ if p.out_chans:
+ body.append(f" wire w_{key}__send;")
+ conn[key]["o_send"] = f"w_{key}__send"
+ body.append("")
+ # ---- channels
+ seen = set()
+ for c in ctx.channels:
+ if c.id in seen:
+ continue
+ seen.add(c.id)
+ cid = self._cid(c)
+ sp = plans.get(c.src.ident) if c.src.id in hw_ids else None
+ dp = plans.get(c.dst.ident) if c.dst.id in hw_ids else None
+ n = len(c.fields)
+ body.append(f" // ---- {c.id}: {vcom(c.src.name)} ({c.src.domain}) -> {vcom(c.dst.name)} "
+ f"({c.dst.domain}) via {c.protocol}: {', '.join(vstr(f) for f in c.fields)}")
+ if sp and dp:
+ body.append(" // both ends are in the FPGA: parallel wires, receiver copies every clock")
+ for f in c.fields:
+ ex, w, sg = self._src_value(sp, f, conn)
+ conn[dp.e.ident][f"i_{cid}_{vname(f)}"] = self._to32(ex, w, sg)
+ conn[dp.e.ident][f"i_{cid}_we"] = "1'b1"
+ continue
+ if not sp and not dp:
+ continue
+ words = []
+ if sp:
+ for f in c.fields:
+ ex, w, sg = self._src_value(sp, f, conn)
+ words.append(self._to16(ex, w, sg))
+ proto = c.protocol
+ if proto in ("spi", "i2c"):
+ txw = "{" + ", ".join(words) + "}" if sp else f"{{{16 * n}{{1'b0}}}}"
+ body.append(f" wire [{16 * n - 1}:0] w_{cid}_rx;")
+ body.append(f" wire w_{cid}_valid;")
+ if proto == "spi":
+ for nm_, d in (("sclk", "input"), ("mosi", "input"), ("cs_n", "input"), ("miso", "output")):
+ port(f"{cid}_{nm_}", d, 1, role="spi", cid=cid, sig=nm_, n=n, send=bool(dp))
+ body += [f" wire w_{cid}_miso;",
+ f" assign {cid}_miso = {cid}_cs_n ? 1'bz : w_{cid}_miso; // tri-state when not selected",
+ f" nlcl_spi_slave #(.N({n})) u_{cid} (",
+ f" .clk(clk), .rst(rst), .sclk({cid}_sclk), .mosi({cid}_mosi), .cs_n({cid}_cs_n),",
+ f" .miso(w_{cid}_miso), .rx_words(w_{cid}_rx), .rx_valid(w_{cid}_valid),",
+ f" .tx_words({txw}));"]
+ else:
+ addr = self._i2c_addr(c.config.get("address", "0x42"))
+ port(f"{cid}_scl", "input", 1, role="i2c", cid=cid, sig="scl", n=n, addr=addr, send=bool(dp))
+ port(f"{cid}_sda", "inout", 1, role="i2c", cid=cid, sig="sda", n=n, addr=addr, send=bool(dp))
+ body += [f" wire w_{cid}_sda_oe;",
+ f" assign {cid}_sda = w_{cid}_sda_oe ? 1'b0 : 1'bz; // open drain, add a pull-up",
+ f" nlcl_i2c_slave #(.ADDR(7'h{addr:02X}), .N({n})) u_{cid} (",
+ f" .clk(clk), .rst(rst), .scl({cid}_scl), .sda_i({cid}_sda), .sda_oe(w_{cid}_sda_oe),",
+ f" .rx_words(w_{cid}_rx), .rx_valid(w_{cid}_valid), .tx_words({txw}));"]
+ if dp:
+ for i, f in enumerate(c.fields):
+ hi = 16 * (n - i) - 1
+ conn[dp.e.ident][f"i_{cid}_{vname(f)}"] = \
+ f"{{{{16{{w_{cid}_rx[{hi}]}}}}, w_{cid}_rx[{hi}:{hi - 15}]}}"
+ conn[dp.e.ident][f"i_{cid}_we"] = f"w_{cid}_valid"
+ elif proto in BUS_TO_WIRE:
+ if sp:
+ for f in c.fields:
+ ex, w, sg = self._src_value(sp, f, conn)
+ pn = f"{cid}_{vname(f)}"
+ port(pn, "output", 1, role="gpio_out")
+ body.append(f" assign {pn} = |{ex}; // HIGH when {vcom(f)} != 0")
+ else:
+ for f in c.fields:
+ pn = f"{cid}_{vname(f)}"
+ port(pn, "input", 1, role="pin", ent=dp.e.ident)
+ body += [f" reg [1:0] s_{pn};",
+ f" always @(posedge clk) s_{pn} <= rst ? 2'b00 : {{s_{pn}[0], {pn}}};"]
+ conn[dp.e.ident][f"i_{cid}_{vname(f)}"] = f"{{31'd0, s_{pn}[1]}}"
+ conn[dp.e.ident][f"i_{cid}_we"] = "1'b1"
+ else:
+ # serial / http / mqtt / udp / websocket -> UART JSON line
+ if sp:
+ port(f"{cid}_tx", "output", 1, role="uart_tx")
+ extra[f"rtl/nlcl_json_tx_{cid}.v"] = self._json_tx(c, cid)
+ send = f"w_{sp.e.ident}__send" if sp.out_chans else "1'b0"
+ body += [f" nlcl_json_tx_{cid} #(.CLOCK_HZ(CLOCK_HZ)) u_{cid} (",
+ f" .clk(clk), .rst(rst), .send({send}),",
+ f" .words({{{', '.join(words)}}}), .tx({cid}_tx));"]
+ else:
+ port(f"{cid}_rx", "input", 1, role="json_rx", cid=cid, chan=c.id,
+ fields=list(c.fields), baud=int(c.config.get("baud", 115200)))
+ extra[f"rtl/nlcl_json_rx_{cid}.v"] = self._json_rx(c, cid)
+ body += [f" wire [{16 * n - 1}:0] w_{cid}_rx;", f" wire w_{cid}_valid;",
+ f" nlcl_json_rx_{cid} #(.CLOCK_HZ(CLOCK_HZ)) u_{cid} (",
+ f" .clk(clk), .rst(rst), .rx({cid}_rx), .words(w_{cid}_rx), .valid(w_{cid}_valid));"]
+ for i, f in enumerate(c.fields):
+ hi = 16 * (n - i) - 1
+ conn[dp.e.ident][f"i_{cid}_{vname(f)}"] = \
+ f"{{{{16{{w_{cid}_rx[{hi}]}}}}, w_{cid}_rx[{hi}:{hi - 15}]}}"
+ conn[dp.e.ident][f"i_{cid}_we"] = f"w_{cid}_valid"
+ # ---- observable outputs
+ obs = []
+ for key, p in plans.items():
+ for n in list(dict.fromkeys(p.pins_out + p.primary)):
+ if n in p.regs:
+ r = p.regs[n]
+ port(f"{key}_{n}", "output", r.width, role="out")
+ obs.append(f" assign {key}_{n} = w_{key}__{n};")
+ # ---- instances
+ inst = []
+ for key, p in plans.items():
+ c = conn[key]
+ pl = [".clk(clk)", ".rst(rst)"]
+ for pin in p.pins_in:
+ pl.append(f".{pin}({c.get(pin, 1)})")
+ for trig, tport in p.triggers.items():
+ pl.append(f".{tport}({c.get(tport, '1' + chr(39) + 'b0')})")
+ for (ent, prop), xport in p.xrefs.items():
+ pl.append(f".{xport}({c.get(xport, '0')})")
+ for ch in p.in_chans:
+ cid = self._cid(ch)
+ for f in ch.fields:
+ pl.append(f".i_{cid}_{vname(f)}({c.get(f'i_{cid}_{vname(f)}', '32' + chr(39) + 'd0')})")
+ pl.append(f".i_{cid}_we({c.get(f'i_{cid}_we', '1' + chr(39) + 'b0')})")
+ for n in p.regs:
+ pl.append(f".o_{n}(w_{key}__{n})")
+ if p.out_chans:
+ pl.append(f".o_send(w_{key}__send)")
+ par = ctx.system.entities.get(p.e.parent) if p.e.parent else None
+ if par is not None:
+ inst.append(f" // {key} is part of {vcom(par.name)}"
+ + (f" ({par.domain})" if par.domain != "hardware" else ""))
+ inst.append(f" {p.mod} #(.CLOCK_HZ(CLOCK_HZ)) u_{key} (")
+ inst.append(",\n".join(" " + x for x in pl))
+ inst.append(" );")
+ L = ["`timescale 1ns / 1ps", "`default_nettype none",
+ f"// top.v - {vcom(ctx.system.name)}: every hardware entity instantiated and wired. Generated by NLCL.",
+ "// Ports: clk, rst (sync, active high), entity pins _, link pins _.",
+ "module top #(",
+ f" parameter CLOCK_HZ = {self._sys_clock(plans)}",
+ ") ("]
+ pdecl = [" input wire clk", " input wire rst"]
+ for pd in ports:
+ kw = {"input": "input wire", "output": "output wire", "inout": "inout wire"}[pd["dir"]]
+ pdecl.append(f" {kw} {self._rng(pd['width'])}{pd['name']}")
+ L.append(",\n".join(pdecl))
+ L.append(");")
+ L += body
+ L += obs
+ L.append("")
+ L += inst
+ L += ["endmodule", "`default_nettype wire"]
+ return "\n".join(L) + "\n", ports, extra
+
+ @staticmethod
+ def _sys_clock(plans) -> int:
+ for p in plans.values():
+ if "clock_hz" in p.e.props:
+ return p.clock_hz
+ return 50_000_000
+
+ @staticmethod
+ def _i2c_addr(a) -> int:
+ try:
+ if isinstance(a, int):
+ v = a
+ else:
+ s = str(a).strip().lower()
+ v = int(s, 16) if s.startswith("0x") else int(s)
+ return v & 0x7F
+ except (TypeError, ValueError):
+ return 0x42
+
+ # ------------------------------------------------------------------ testbench
+ def _tb(self, ctx: BuildContext, plans: dict[str, Plan], ports: list[dict]) -> str:
+ timers = [ms for p in plans.values() for ms in p.timers]
+ for p in plans.values():
+ if p.kind == "blinker":
+ timers.append(to_int(p.e.props.get("interval_ms", 500), 500) * 2)
+ for c in ctx.channels:
+ if c.protocol not in ("spi", "i2c", "wire", "gpio"):
+ timers.append(to_int(c.config.get("interval_ms", 1000), 1000))
+ ms = max(timers + [20])
+ cycles = int(min(3_000_000, max(50_000, ms * (SIM_CLOCK_HZ // 1000) * 3)))
+ L = ["`timescale 1ns / 1ps", "`default_nettype none",
+ "// tb_top.v - self-running testbench for top.v (generated by NLCL).",
+ f"// Simulated clock: {SIM_CLOCK_HZ} Hz (1 ms = {SIM_CLOCK_HZ // 1000} cycles); runs {cycles} cycles.",
+ "// iverilog -g2005 -DSIMULATION -s tb_top -o build/sim.vvp -c files.f sim/tb_top.v && vvp build/sim.vvp",
+ "// gtkwave tb_top.vcd",
+ "module tb_top;",
+ f" localparam integer SIM_CLOCK_HZ = {SIM_CLOCK_HZ};",
+ f" localparam integer CYCLES = {cycles};",
+ " localparam integer CLK_NS = 1000000000 / SIM_CLOCK_HZ;",
+ " reg clk = 1'b0;", " reg rst = 1'b1;",
+ " always #(CLK_NS / 2) clk = ~clk;"]
+ conns = [".clk(clk)", ".rst(rst)"]
+ stim: list[str] = []
+ outs = []
+ i2c_done, spi_done = set(), set()
+ for pd in ports:
+ nm, w = pd["name"], pd["width"]
+ role = pd.get("role")
+ if pd["dir"] == "output":
+ L.append(f" wire {self._rng(w)}{nm};")
+ conns.append(f".{nm}({nm})")
+ outs.append(nm)
+ continue
+ if pd["dir"] == "inout":
+ L += [f" wire {nm};", f" reg {nm}_low = 1'b0;", f" assign {nm} = {nm}_low ? 1'b0 : 1'bz;",
+ f" pullup({nm});"]
+ conns.append(f".{nm}({nm})")
+ continue
+ idle = 1 if role in ("uart_rx", "json_rx") or (role == "spi" and pd.get("sig") == "cs_n") or \
+ (role == "i2c") else 0
+ L.append(f" reg {self._rng(w)}{nm} = {w}'d{idle};")
+ conns.append(f".{nm}({nm})")
+ if role in ("trigger", "pin"):
+ stim.append(("pulse", nm, 200))
+ elif role == "button":
+ stim.append(("pulse", nm, max(1, pd.get("hold_ms", 30)) * (SIM_CLOCK_HZ // 1000)))
+ elif role == "uart_rx":
+ stim.append(("uart", nm, pd.get("baud", 115200), '"A"', 1))
+ elif role == "json_rx":
+ line = json.dumps(dict([("channel", pd["chan"]), ("from", "tb")] +
+ [(f, 10 * (i + 1) + 2) for i, f in enumerate(pd["fields"])]),
+ separators=(", ", ": ")) + "\n"
+ stim.append(("uart", nm, pd.get("baud", 115200), '"' + vstr(line) + '"',
+ len(line.encode("ascii", "replace"))))
+ for pd in ports:
+ if pd.get("role") == "spi" and pd["cid"] not in spi_done:
+ spi_done.add(pd["cid"])
+ stim.append(("spi", pd["cid"], pd["n"], pd.get("send")))
+ if pd.get("role") == "i2c" and pd["cid"] not in i2c_done:
+ i2c_done.add(pd["cid"])
+ stim.append(("i2c", pd["cid"], pd["n"], pd.get("addr", 0x42), pd.get("send")))
+ L.append("")
+ L.append(" top #(.CLOCK_HZ(SIM_CLOCK_HZ)) dut (")
+ L.append(",\n".join(" " + x for x in conns))
+ L.append(" );")
+ L.append("")
+ # tasks
+ L += [" task wait_cycles(input integer n);", " begin", " repeat (n) @(posedge clk);",
+ " end", " endtask"]
+ for s in stim:
+ if s[0] == "uart":
+ _, nm, baud, text, ln = s
+ bit = max(1, SIM_CLOCK_HZ // max(1, baud))
+ L += [f" task uart_{nm};",
+ f" reg [{8 * ln - 1}:0] msg;", " integer i, b;", " begin",
+ f" msg = {text};",
+ f" for (i = {ln - 1}; i >= 0; i = i - 1) begin",
+ f" {nm} = 1'b0; wait_cycles({bit});",
+ " for (b = 0; b < 8; b = b + 1) begin",
+ f" {nm} = msg[8*i + b]; wait_cycles({bit});",
+ " end",
+ f" {nm} = 1'b1; wait_cycles({bit * 2});",
+ " end", " end", " endtask"]
+ elif s[0] == "spi":
+ _, cid, n, send = s
+ L += [f" reg [7:0] spi_in_{cid};",
+ f" task spi_byte_{cid}(input [7:0] v);", " integer b;", " begin",
+ " for (b = 7; b >= 0; b = b - 1) begin",
+ f" {cid}_mosi = v[b]; wait_cycles(8);",
+ f" {cid}_sclk = 1'b1; spi_in_{cid} = {{spi_in_{cid}[6:0], {cid}_miso}}; wait_cycles(8);",
+ f" {cid}_sclk = 1'b0;",
+ " end", " wait_cycles(8);", " end", " endtask",
+ f" task spi_read_{cid}; // 0x5A, then 1 + 2N bytes: 0xA5 + int16 words",
+ " integer k;", " begin",
+ f" {cid}_cs_n = 1'b0; wait_cycles(16);",
+ f" spi_byte_{cid}(8'h5A);",
+ f" spi_byte_{cid}(8'h00);",
+ f' $display("[%0t ns] {cid}: sync byte %h (expect a5)", $time, spi_in_{cid});',
+ f" for (k = 0; k < {2 * n}; k = k + 1) begin",
+ f" spi_byte_{cid}(8'h00);",
+ f' $display("[%0t ns] {cid}: data byte %0d = %h", $time, k, spi_in_{cid});',
+ " end",
+ f" wait_cycles(16); {cid}_cs_n = 1'b1;", " end", " endtask",
+ f" task spi_frame_{cid};", " integer k;", " begin",
+ f" {cid}_cs_n = 1'b0; wait_cycles(16);",
+ f" spi_byte_{cid}(8'hA5); spi_byte_{cid}(8'd{n});",
+ f" for (k = 0; k < {n}; k = k + 1) begin",
+ f" spi_byte_{cid}(8'h00); spi_byte_{cid}(8'd20 + k[7:0] * 8'd10);",
+ " end",
+ f" wait_cycles(16); {cid}_cs_n = 1'b1;", " end", " endtask"]
+ elif s[0] == "i2c":
+ _, cid, n, addr, send = s
+ sda, scl = f"{cid}_sda_low", f"{cid}_scl"
+ L += [f" task i2c_byte_{cid}(input [7:0] v);", " integer b;", " begin",
+ " for (b = 7; b >= 0; b = b - 1) begin",
+ f" {sda} = ~v[b]; wait_cycles(16);",
+ f" {scl} = 1'b1; wait_cycles(16);",
+ f" {scl} = 1'b0; wait_cycles(4);",
+ " end",
+ f" {sda} = 1'b0; wait_cycles(16); // release for ACK",
+ f" {scl} = 1'b1; wait_cycles(16);",
+ f" {scl} = 1'b0; wait_cycles(16);", " end", " endtask",
+ f" task i2c_frame_{cid};", " integer k;", " begin",
+ f" {sda} = 1'b1; wait_cycles(16); // START: SDA low while SCL high",
+ f" {scl} = 1'b0; wait_cycles(16);",
+ f" i2c_byte_{cid}(8'h{(addr << 1) & 0xFE:02X});",
+ f" i2c_byte_{cid}(8'hA5); i2c_byte_{cid}(8'd{n});",
+ f" for (k = 0; k < {n}; k = k + 1) begin",
+ f" i2c_byte_{cid}(8'h00); i2c_byte_{cid}(8'd20 + k[7:0] * 8'd10);",
+ " end",
+ f" {sda} = 1'b1; wait_cycles(16);",
+ f" {scl} = 1'b1; wait_cycles(16);",
+ f" {sda} = 1'b0; wait_cycles(16); // STOP: SDA high while SCL high",
+ " end", " endtask"]
+ L += ["", " integer cyc;", " initial begin",
+ ' $dumpfile("tb_top.vcd");', " // depth 2 = testbench + every entity register in top (0 = all signals: huge VCD)",
+ " $dumpvars(2, tb_top);",
+ " wait_cycles(5);", " rst = 1'b0;", " end", ""]
+ # stimulus process
+ L += [" initial begin", " wait_cycles(20);"]
+ if not stim:
+ L.append(" // no external inputs: the design runs on its own")
+ for s in stim:
+ if s[0] == "pulse":
+ _, nm, hold = s
+ L += [f" repeat (3) begin", f" {s[1]} = 1'b1; wait_cycles({hold});",
+ f" {s[1]} = 1'b0; wait_cycles({hold});", " end"]
+ elif s[0] == "uart":
+ L.append(f" uart_{s[1]};")
+ elif s[0] == "spi":
+ L.append(f" spi_frame_{s[1]};" if s[3] else f" wait_cycles(CYCLES / 2); spi_read_{s[1]};")
+ elif s[0] == "i2c":
+ L.append(f" i2c_frame_{s[1]};" if s[4] else f" // {s[1]}: FPGA is the sender; the master reads it")
+ L += [" end", ""]
+ fmt = " ".join(f"{o}=%0d" for o in outs[:16])
+ args = "".join(f", {o}" for o in outs[:16])
+ L += [" initial begin", " wait_cycles(10);",
+ " for (cyc = 0; cyc < 10; cyc = cyc + 1) begin",
+ " wait_cycles(CYCLES / 10);",
+ f' $display("[%0t ns] {fmt}", $time{args});' if outs else
+ ' $display("[%0t ns] running", $time);',
+ " end",
+ ' $display("tb_top: done after %0d cycles", CYCLES);',
+ " $finish;", " end", "endmodule", "`default_nettype wire"]
+ return "\n".join(L) + "\n"
+
+ # ------------------------------------------------------------------ host bridge
+ def _bridge(self, ctx: BuildContext) -> str | None:
+ hw = {e.id for e in ctx.entities}
+ chans = []
+ for c in ctx.channels:
+ if c.protocol in ("http", "websocket", "mqtt", "udp") and (c.src.id in hw) != (c.dst.id in hw):
+ chans.append(dict(id=c.id, dir="out" if c.src.id in hw else "in", protocol=c.protocol,
+ src=c.src.ident, fields=list(c.fields), config=c.config,
+ pin=f"{self._cid(c)}_{'tx' if c.src.id in hw else 'rx'}"))
+ if not chans:
+ return None
+ return BRIDGE.replace("__CHANNELS__", json.dumps(chans, indent=4, ensure_ascii=True))
+
+ # ------------------------------------------------------------------ generate
+ @staticmethod
+ def _unique_view(ctx: BuildContext) -> BuildContext:
+ """Hardware entities whose identifier is empty (e.g. a Persian name) or clashes with
+ another one get a private ASCII name for this build, so no module is silently dropped."""
+ import copy
+ import dataclasses
+ seen, ren = set(), {}
+ for e in ctx.entities:
+ k = e.ident
+ if not k or k in seen:
+ base = k or (ident(e.kind) or "obj")
+ k = f"{base}_{ident(e.id) or len(seen)}"
+ while k in seen:
+ k += "_2"
+ ren[e.id] = dataclasses.replace(e, name=k)
+ seen.add(k)
+ if not ren:
+ return ctx
+ v = copy.copy(ctx)
+ v.entities = [ren.get(e.id, e) for e in ctx.entities]
+ v.channels = [dataclasses.replace(c, src=ren.get(c.src.id, c.src), dst=ren.get(c.dst.id, c.dst))
+ for c in ctx.channels]
+ return v
+
+ def _wire_view(self, ctx: BuildContext) -> BuildContext:
+ """FPGA-internal links (both ends hardware) are ours alone, so their default field list
+ (every numeric prop of the source, including names like 'alu1_result' that only refer to
+ other entities) is narrowed to the source's real outputs unless the user named fields."""
+ import copy
+ import dataclasses
+ links = getattr(ctx.system, "links", {}) or {}
+ idents = sorted({e.ident for e in ctx.entities}, key=len, reverse=True)
+
+ def bogus(f):
+ n = ident(f)
+ return n.startswith("_") or n in idents or any(n.startswith(o + "_") and len(n) > len(o) + 1
+ for o in idents)
+ out, changed = [], False
+ for c in ctx.channels:
+ lk = links.get(c.id)
+ explicit = bool(lk is not None and (getattr(lk, "props", {}) or {}).get("fields"))
+ if not self._wire_like(c) or explicit:
+ out.append(c)
+ continue
+ kind = self._kind(c.src)
+ fields = [f for f in c.fields if not bogus(f)]
+ prim = [f for f in SPECS[kind]["primary"] if f in fields or f in SPECS[kind]["regs"] or f == "state"]
+ if kind != "object" and prim:
+ fields = prim
+ fields = fields or list(c.fields)
+ if fields != list(c.fields):
+ changed = True
+ c = dataclasses.replace(c, fields=fields)
+ out.append(c)
+ if not changed:
+ return ctx
+ v = copy.copy(ctx)
+ v.channels = out
+ return v
+
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
+ try:
+ ctx = self._unique_view(ctx)
+ except Exception:
+ pass
+ try:
+ ctx = self._wire_view(ctx)
+ except Exception:
+ pass
+ files: dict[str, str] = {}
+ plans: dict[str, Plan] = {}
+ used: set = set()
+ self._plans = plans
+ for e in ctx.entities:
+ try:
+ plans[e.ident] = self._plan(ctx, e, used)
+ except Exception as ex: # never raise: fall back to an empty register bank
+ p = Plan(e)
+ p.mod = vname(e.ident) + "_m"
+ p.comments.append(f"planning failed: {vstr(ex)}")
+ plans[e.ident] = p
+ try: # a field received over an FPGA-internal link keeps the sender's width
+ for p in plans.values():
+ for c in p.in_chans:
+ q = plans.get(c.src.ident)
+ if not self._wire_like(c) or q is None:
+ continue
+ for f in c.fields:
+ r, sr = p.regs.get(vname(f)), q.regs.get(vname(f))
+ if r is not None and sr is not None and r.note.startswith("channel field"):
+ r.width = sr.width
+ except Exception:
+ pass
+ try:
+ self._rehome(plans)
+ except Exception:
+ pass
+ for p in plans.values():
+ self._render_behaviours(ctx, p, plans)
+ for p in plans.values():
+ # keep module names distinct from the signals inside (e.g. a mux called "sel")
+ if p.mod in p.regs or p.mod in p.pins_in:
+ base = p.mod + "_m"
+ while base in used or base in p.regs:
+ base += "_m"
+ used.add(base)
+ p.mod = base
+ for key, p in plans.items():
+ try:
+ files[f"rtl/{p.mod}.v"] = self._module(ctx, p)
+ except Exception as ex:
+ files[f"rtl/{p.mod}.v"] = (f"// generation failed for {vcom(p.e.name)}: {vcom(ex)}\n"
+ f"module {p.mod} (input wire clk, input wire rst);\nendmodule\n")
+ top, ports, extra = self._top(ctx, plans)
+ files["rtl/top.v"] = top
+ files.update(extra)
+ protos = {c.protocol for c in ctx.channels}
+ hw_ids = {p.e.id for p in plans.values()}
+ needs = {c.protocol for c in ctx.channels if (c.src.id in hw_ids) != (c.dst.id in hw_ids)}
+ if "spi" in needs:
+ files["rtl/nlcl_spi_slave.v"] = (ASSETS / "nlcl_spi_slave.v").read_text(encoding="utf-8")
+ if "i2c" in needs:
+ files["rtl/nlcl_i2c_slave.v"] = (ASSETS / "nlcl_i2c_slave.v").read_text(encoding="utf-8")
+ files["sim/tb_top.v"] = self._tb(ctx, plans, ports)
+ rtl = [k for k in files if k.startswith("rtl/")]
+ rtl = [k for k in rtl if k != "rtl/top.v"] + ["rtl/top.v"]
+ self._rtl_files = rtl
+ files["synth.ys"] = self._synth(rtl)
+ files["files.f"] = "\n".join(rtl) + "\n"
+ br = self._bridge(ctx)
+ if br:
+ files["host_bridge.py"] = br
+ files["README.md"] = self._readme(ctx, plans, ports, rtl, bool(br), protos)
+ return files
+
+ def _synth(self, rtl: list[str]) -> str:
+ return "\n".join([
+ "# Yosys synthesis script (generated by NLCL): yosys -s synth.ys",
+ "# generic gate-level synthesis + statistics; swap the 'synth' line for an FPGA flow:",
+ "# synth_ice40 -top top -json build/top_ice40.json (then nextpnr-ice40)",
+ "# synth_ecp5 -top top -json build/top_ecp5.json (then nextpnr-ecp5)",
+ "# synth_gowin -top top -json build/top_gowin.json",
+ *[f"read_verilog -defer {f}" for f in rtl],
+ "hierarchy -check -top top",
+ "proc",
+ "tribuf",
+ "synth -top top",
+ "check",
+ "stat",
+ "write_json build/top.json",
+ "write_verilog -noattr build/top_synth.v",
+ ""])
+
+ def _readme(self, ctx, plans, ports, rtl, bridge, protos) -> str:
+ L = [f"# {ctx.system.name} - hardware (Verilog-2005)", "",
+ "Generated by NLCL. Synthesizable RTL, a self-running testbench (stimulus + periodic $display + VCD) and a Yosys script.", "",
+ "## Files", "",
+ "| file | contents |", "|---|---|"]
+ for key, p in plans.items():
+ par = ctx.system.entities.get(p.e.parent) if p.e.parent else None
+ L.append(f"| `rtl/{p.mod}.v` | module `{p.mod}` (entity {key}) - {p.kind} ({p.W}-bit)"
+ + (f", part of {vcom(par.name)}" if par is not None else "") + " |")
+ for f in rtl:
+ if "nlcl_" in f:
+ L.append(f"| `{f}` | link adapter |")
+ L += ["| `rtl/top.v` | instantiates everything, wires the links |",
+ "| `sim/tb_top.v` | testbench: clock, reset, stimulus, VCD dump |",
+ "| `synth.ys` | Yosys script |", "| `files.f` | file list for tools |"]
+ if bridge:
+ L.append("| `host_bridge.py` | relays FPGA UART JSON lines to the hub / MQTT / UDP |")
+ L += ["", "## Top-level ports", "", "| port | dir | width | meaning |", "|---|---|---|---|",
+ "| clk | in | 1 | system clock (CLOCK_HZ parameter) |", "| rst | in | 1 | synchronous reset, active high |"]
+ for pd in ports:
+ L.append(f"| {pd['name']} | {pd['dir']} | {pd['width']} | {pd.get('role', '')} |")
+ L += ["", "## Simulate (free)", "", "```sh", "mkdir build",
+ "iverilog -g2005 -DSIMULATION -s tb_top -o build/sim.vvp sim/tb_top.v " + " ".join(rtl),
+ "vvp build/sim.vvp", "gtkwave tb_top.vcd", "```", "",
+ "- Icarus Verilog for Windows: https://bleyer.org/icarus/ (includes GTKWave); Linux `apt install iverilog gtkwave`.",
+ "- Verilator lint: `verilator --lint-only -Wall -Wno-fatal -DSIMULATION --top-module top " + " ".join(rtl) + "`",
+ "- No install: https://www.edaplayground.com - choose *Icarus Verilog 12*, paste `sim/tb_top.v` as testbench,",
+ " the `rtl/*.v` files as design, add `-DSIMULATION` to compile options, tick *Open EPWave after run*.",
+ "", "## Synthesize (free)", "",
+ "```sh", "mkdir build", "yosys -s synth.ys", "```",
+ "Yosys is part of the free OSS CAD Suite (github.com/YosysHQ/oss-cad-suite-build). For a real board",
+ "replace `synth` with `synth_ice40` / `synth_ecp5` and run nextpnr + the vendor-free packer.",
+ "", "## Behaviour mapping", "",
+ "- `update` -> every clock; `timer:` -> divider tick derived from `CLOCK_HZ`;",
+ " `input:` -> input port `_in_` with 2-FF synchroniser + rising-edge detect;",
+ " `change:
` -> compare with a delayed copy; `message:` -> link valid strobe.",
+ "- `set/add/toggle` -> non-blocking assignments; `log` -> `$display` under `ifdef SIMULATION`;",
+ " `destroy` -> clears the module's `nl_alive` register (it stops updating).",
+ "- Numbers are unsigned integers of the entity `width` (floats are rounded).",
+ "", "## Link byte protocols", "",
+ "- **wire / gpio between FPGA entities**: parallel buses, the receiver copies same-named fields every clock.",
+ "- **SPI (mode 0, MSB first) / I2C slave** (from a micro-controller): write frame `0xA5, N, N x int16 big-endian`",
+ " in field order; read: SPI master sends `0x5A` then clocks `1+2N` bytes (`0xA5` + words),",
+ " I2C read returns `0xA5, N, words`. SCLK <= clk/8, SCL <= clk/16.",
+ "- **serial / http / mqtt / udp**: 8N1 UART carrying one flat JSON line per message,",
+ " `{\"channel\":\"\",\"from\":\"\",\"\":}\\n` (int16 values).",
+ " Serial peers read it directly; for http/mqtt/udp run `python host_bridge.py --port COM5` on the PC",
+ " wired to the FPGA UART (USB-UART adapter) to relay it to the NLCL hub / broker.", ""]
+ return "\n".join(L)
+
+ # ------------------------------------------------------------------ run
+ def run(self, ctx: BuildContext) -> RunResult | None:
+ top = ctx.outdir / "rtl" / "top.v"
+ if not top.exists():
+ return RunResult(False, "build first")
+ rtl = sorted(str(p.relative_to(ctx.outdir)).replace("\\", "/") for p in (ctx.outdir / "rtl").glob("*.v"))
+ iv, vvp = self.which("iverilog"), self.which("vvp")
+ if iv and vvp:
+ (ctx.outdir / "build").mkdir(exist_ok=True)
+ r = self.sh([iv, "-g2005", "-DSIMULATION", "-s", "tb_top", "-o", "build/sim.vvp", "sim/tb_top.v"] + rtl,
+ ctx.outdir, timeout=60)
+ if not r.ok:
+ return r
+ r2 = self.sh([vvp, "-n", "build/sim.vvp"], ctx.outdir, timeout=120)
+ return RunResult(r2.ok, (r.output + "\n" + r2.output).strip(), r.command + " && " + r2.command)
+ vl = self.which("verilator", "verilator_bin")
+ if vl:
+ return self.sh([vl, "--lint-only", "-Wall", "-Wno-fatal", "-DSIMULATION", "--top-module", "top"] + rtl,
+ ctx.outdir, timeout=60)
+ return None
+
+
+BRIDGE = r'''#!/usr/bin/env python3
+"""Host bridge: FPGA UART JSON lines <-> NLCL hub (HTTP) / MQTT / UDP. Generated by NLCL.
+
+The FPGA prints one flat JSON line per message on its _tx pin and parses
+lines arriving on _rx. Wire every UART pin to one USB-UART adapter
+(or edit top.v to share one TX/RX pair), then:
+
+ pip install pyserial # paho-mqtt too if a channel uses mqtt
+ python host_bridge.py --port COM5 --baud 115200
+ python host_bridge.py --demo # no FPGA: prints what would be relayed
+"""
+import argparse
+import json
+import socket
+import sys
+import threading
+import time
+import urllib.request
+
+CHANNELS = __CHANNELS__
+
+
+def http_url(ch):
+ cfg = ch["config"]
+ return cfg.get("hub_url", "http://localhost:8765").rstrip("/") + cfg.get("path", "/channel/" + ch["id"])
+
+
+class Bridge:
+ def __init__(self, ser, demo=False):
+ self.ser, self.demo, self.lock = ser, demo, threading.Lock()
+ self.mqtt = None
+ self.seen = {}
+ if any(c["protocol"] == "mqtt" for c in CHANNELS):
+ try:
+ import paho.mqtt.client as mqtt
+ cfg = next(c["config"] for c in CHANNELS if c["protocol"] == "mqtt")
+ try: # paho-mqtt >= 2 needs an explicit callback API version
+ self.mqtt = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1)
+ except AttributeError:
+ self.mqtt = mqtt.Client()
+ self.mqtt.on_message = self.on_mqtt
+ self.mqtt.connect(cfg.get("broker", "broker.hivemq.com"), int(cfg.get("broker_port", 1883)))
+ for c in CHANNELS:
+ if c["protocol"] == "mqtt" and c["dir"] == "in":
+ self.mqtt.subscribe(c["config"].get("topic", "nlcl/" + c["id"]))
+ self.mqtt.loop_start()
+ except Exception as e: # noqa: BLE001
+ print("[bridge] mqtt unavailable:", e)
+
+ def to_fpga(self, ch, msg):
+ line = json.dumps(dict({"channel": ch["id"], "from": ch["src"]},
+ **{f: int(round(float(msg.get(f, 0)))) for f in ch["fields"]}),
+ separators=(",", ":")) + "\n"
+ with self.lock:
+ if self.ser:
+ self.ser.write(line.encode())
+ print("[bridge] -> fpga", line.strip())
+
+ def from_fpga(self, msg):
+ ch = next((c for c in CHANNELS if c["id"] == msg.get("channel") and c["dir"] == "out"), None)
+ if not ch:
+ return
+ data = json.dumps(msg).encode()
+ try:
+ if ch["protocol"] in ("http", "websocket"):
+ urllib.request.urlopen(urllib.request.Request(http_url(ch), data,
+ {"Content-Type": "application/json"}), timeout=2).read()
+ elif ch["protocol"] == "mqtt" and self.mqtt:
+ self.mqtt.publish(ch["config"].get("topic", "nlcl/" + ch["id"]), data)
+ elif ch["protocol"] == "udp":
+ socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(data, ("127.0.0.1", int(ch["config"].get("port", 9876))))
+ print("[bridge] fpga ->", ch["protocol"], msg)
+ except OSError as e:
+ print("[bridge] relay failed:", e)
+
+ def on_mqtt(self, client, userdata, m):
+ for c in CHANNELS:
+ if c["dir"] == "in" and c["protocol"] == "mqtt" and m.topic == c["config"].get("topic", "nlcl/" + c["id"]):
+ try:
+ self.to_fpga(c, json.loads(m.payload or b"{}"))
+ except ValueError:
+ pass
+
+ def poll(self):
+ udp = {}
+ for c in CHANNELS:
+ if c["dir"] == "in" and c["protocol"] == "udp":
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ s.bind(("0.0.0.0", int(c["config"].get("port", 9876))))
+ s.settimeout(0.05)
+ udp[c["id"]] = s
+ while True:
+ for c in CHANNELS:
+ if c["dir"] != "in":
+ continue
+ if c["protocol"] in ("http", "websocket"):
+ try:
+ msg = json.loads(urllib.request.urlopen(http_url(c), timeout=2).read() or b"{}")
+ except (OSError, ValueError):
+ continue
+ if msg and msg.get("_t") != self.seen.get(c["id"]):
+ self.seen[c["id"]] = msg.get("_t")
+ self.to_fpga(c, msg)
+ elif c["protocol"] == "udp":
+ try:
+ self.to_fpga(c, json.loads(udp[c["id"]].recv(4096)))
+ except (OSError, ValueError):
+ pass
+ time.sleep(0.2)
+
+ def read_serial(self):
+ buf = b""
+ while self.ser:
+ buf += self.ser.read(256)
+ while b"\n" in buf:
+ line, buf = buf.split(b"\n", 1)
+ try:
+ self.from_fpga(json.loads(line.decode("ascii", "replace")))
+ except ValueError:
+ pass
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("--port", help="serial port of the FPGA UART (COM5, /dev/ttyUSB0)")
+ ap.add_argument("--baud", type=int, default=115200)
+ ap.add_argument("--demo", action="store_true", help="no FPGA: just show the channel table")
+ a = ap.parse_args()
+ for c in CHANNELS:
+ print(f"[bridge] {c['id']}: {c['dir']} via {c['protocol']} pin {c['pin']} fields {c['fields']}")
+ if a.demo or not a.port:
+ if not a.demo:
+ print("[bridge] give --port to connect to the FPGA")
+ return 0
+ try:
+ import serial
+ except ImportError:
+ print("pip install pyserial")
+ return 1
+ ser = serial.Serial(a.port, a.baud, timeout=0.1)
+ b = Bridge(ser)
+ threading.Thread(target=b.read_serial, daemon=True).start()
+ try:
+ b.poll()
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
+'''
+
+MODULE = HardwareModule()
diff --git a/nlcl/modules/python_mod.py b/nlcl/modules/python_mod.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8f8fcbe17d91b8c0a6b744f324ca39fe00287e7
--- /dev/null
+++ b/nlcl/modules/python_mod.py
@@ -0,0 +1,339 @@
+"""Python domain: objects, services, dashboards, the HTTP hub and bridges.
+
+This is also the *glue* module of multi-module systems: whenever two other
+modules talk over HTTP (or a serial device must reach a browser), the
+composer asks this module to emit the hub/bridge even if the user never
+created a Python object.
+"""
+from __future__ import annotations
+
+import keyword
+import sys
+from pathlib import Path
+
+from ..ir import Entity, describe_action
+from .base import BuildContext, DomainModule, RunResult
+
+ASSET = Path(__file__).parent / "_assets" / "nlcl_runtime.py"
+
+# attributes/methods of nlcl_runtime.Entity: a user property with one of these names
+# is stored under "_" (the wire/state name stays the same, see Entity.aliases)
+RESERVED_ATTRS = {"name", "world", "alive", "props", "kind", "aliases", "every", "state", "log",
+ "destroy", "move", "send", "get", "on_start", "on_update", "on_change",
+ "on_message", "on_collision", "on_input", "rotation"}
+# names main.py itself defines at module level
+RESERVED_CLASSES = {"Entity", "World", "Hub", "make_channel", "main_args", "build", "_Relay"}
+
+
+def method(call: str) -> str:
+ """Python method name for a user-named action ("call shutdown")."""
+ if call in RESERVED_ATTRS or keyword.iskeyword(call) or call.startswith("_"):
+ return "do_" + call.lstrip("_")
+ return call
+
+
+def attr(prop: str) -> str:
+ """Python attribute name used for a property."""
+ if prop in RESERVED_ATTRS or keyword.iskeyword(prop) or prop.startswith("_"):
+ return prop + "_"
+ return prop
+
+
+class PythonModule(DomainModule):
+ name = "python"
+ title = "Python (software objects, services, hub, bridges)"
+ aliases = ("py", "software", "پایتون")
+ keywords = ("python", "script", "class", "service", "server", "dashboard", "api", "backend",
+ "logger", "database", "monitor", "controller", "bot", "agent", "counter", "timer",
+ "inventory", "bank", "account", "calculator", "queue", "stack")
+ kinds = {
+ "object": {},
+ "class": {},
+ "service": {},
+ "dashboard": {},
+ "server": {"port": 8000},
+ "logger": {},
+ "monitor": {},
+ "counter": {"count": 0},
+ "timer": {"elapsed": 0},
+ "account": {"balance": 0},
+ }
+ suggested_props = ("count", "balance", "threshold", "interval_ms", "label")
+ protocols = ("http", "serial", "mqtt", "udp", "websocket")
+ toolchain = """Run with free CPython 3.10+ (python.org):
+
+ python main.py # real transports (hub on :8765, serial/mqtt if available)
+ python main.py --simulate # no hardware/network needed: remote data is simulated
+ python main.py --seconds 10 # stop automatically
+
+Optional free packages: `pip install pyserial paho-mqtt`.
+Open http://localhost:8765 for the live channel dashboard."""
+
+ # ------------------------------------------------------------------ build
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
+ files = {"nlcl_runtime.py": ASSET.read_text(encoding="utf-8")}
+ files["main.py"] = self._main(ctx)
+ return files
+
+ def _name(self, ctx: BuildContext, owner: Entity):
+ def f(n: str) -> str:
+ if "." in n:
+ ent, prop = n.split(".", 1)
+ if ent in (owner.ident, owner.name):
+ return f"self.{attr(prop)}"
+ return f"self.world.get_remote({ent!r}, {prop!r})"
+ return f"self.{attr(n)}"
+ return f
+
+ def _class_names(self, ctx: BuildContext) -> dict[str, str]:
+ out, used = {}, set(RESERVED_CLASSES)
+ for e in ctx.entities:
+ cn = e.class_name
+ if not cn.isidentifier() or keyword.iskeyword(cn):
+ cn = "E" + "".join(ch for ch in cn if ch.isalnum() or ch == "_")
+ base, i = cn, 2
+ if cn in used:
+ cn = base = base + "Entity"
+ while cn in used:
+ cn, i = f"{base}{i}", i + 1
+ used.add(cn)
+ out[e.id] = cn
+ return out
+
+ def _class(self, ctx: BuildContext, e: Entity) -> list[str]:
+ cname = self._cls[e.id]
+ L = [f"class {cname}(Entity):", f" kind = {e.kind!r}"]
+ props = {k: v for k, v in e.props.items() if not k.startswith("_")}
+ for b in e.behaviors: # "rotate it by 90 degrees" needs the angle attribute to exist
+ for a in b["do"]:
+ p = str(a.get("prop", ""))
+ if p.split(".")[-1] in ("angle", "angle_x", "angle_y") and (
+ "." not in p or p.split(".", 1)[0] in (e.ident, e.name)):
+ props.setdefault(p.split(".")[-1], 0)
+ L.append(f" props = {tuple(props)!r}")
+ aliases = {k: attr(k) for k in props if attr(k) != k}
+ if aliases:
+ L.append(f" aliases = {aliases!r}")
+ L += ["", " def __init__(self, world, name=" + repr(e.ident) + "):",
+ " super().__init__(world, name)"]
+ for k, v in props.items():
+ L.append(f" self.{attr(k)} = {self.literal(v, 'python')}")
+ timers = [b for b in e.behaviors if b["on"].startswith("timer:")]
+ for i, b in enumerate(timers):
+ L.append(f" self.every({b['on'].split(':')[1]}, self._timer_{i})")
+ L.append("")
+ name = self._name(ctx, e)
+ groups: dict[str, list[dict]] = {}
+ foreign_changes = [] # "when door.open changes" on another entity: polled in on_update
+ for b in e.behaviors:
+ key = b["on"].split(":")[0]
+ if key == "change" and "." in b["on"]:
+ ent, prop = b["on"].split(":", 1)[1].split(".", 1)
+ if ent not in (e.ident, e.name):
+ foreign_changes.append((ent, prop, b))
+ continue
+ b = dict(b, on=f"change:{prop}")
+ groups.setdefault(key, []).append(b)
+
+ def body(b, indent=" ", edge=None):
+ out = []
+ ind = indent
+ if b.get("if"):
+ cond = self.expr(b['if'], 'python', name)
+ if edge is not None:
+ # "when X ..." fires once each time X becomes true, not on every tick
+ out.append(f"{indent}if self.rising({edge}, {cond}):")
+ else:
+ out.append(f"{indent}if {cond}:")
+ ind = indent + " "
+ for a in b["do"]:
+ out += [ind + line for line in self._action(a, name)]
+ return out
+
+ if "start" in groups:
+ L.append(" def on_start(self):")
+ for b in groups["start"]:
+ L += body(b)
+ L.append("")
+ auto_elapsed = (e.kind == "timer" and "elapsed" in props and not any(
+ a.get("prop") == "elapsed" for b in e.behaviors for a in b["do"]))
+ if "update" in groups or auto_elapsed or foreign_changes:
+ L.append(" def on_update(self, dt):")
+ if auto_elapsed:
+ L.append(" self.elapsed += int(round(dt * 1000)) # a timer counts milliseconds")
+ for ent, prop, b in foreign_changes:
+ L.append(f" if self.changed({ent + '.' + prop!r}, self.world.get_remote({ent!r}, {prop!r}, None)):")
+ L += body(b, " ")
+ for i, b in enumerate(groups.get("update", [])):
+ L += body(b, edge=i)
+ L.append("")
+ for i, b in enumerate(timers):
+ L.append(f" def _timer_{i}(self): # every {b['on'].split(':')[1]} ms")
+ L += body(b)
+ L.append("")
+ if "change" in groups:
+ L.append(" def on_change(self, prop):")
+ for b in groups["change"]:
+ prop = b["on"].split(":", 1)[1]
+ L.append(f" if prop == {prop!r}:")
+ L += body(b, " ")
+ L.append("")
+ if "message" in groups:
+ L.append(" def on_message(self, sender, msg):")
+ for b in groups["message"]:
+ src = b["on"].split(":", 1)[1]
+ if src != "any":
+ L.append(f" if sender == {src!r}:")
+ L += body(b, " ")
+ else:
+ L += body(b)
+ L.append("")
+ if "collision" in groups:
+ L.append(" def on_collision(self, other):")
+ for b in groups["collision"]:
+ w = b.get("with")
+ if w:
+ # "when hero touches gold": only a partner whose name or kind matches
+ L.append(f" if other.name == {w!r} or getattr(other, 'kind', None) == {w!r}:")
+ L += body(b, " ")
+ else:
+ L += body(b)
+ L.append("")
+ if "input" in groups:
+ L.append(" def on_input(self, key):")
+ for b in groups["input"]:
+ L.append(f" if key == {b['on'].split(':', 1)[1]!r}:")
+ L += body(b, " ")
+ L.append("")
+ calls = {a["name"] for b in e.behaviors for a in b["do"]
+ if a["op"] == "call" and str(a["name"]).isidentifier()}
+ for c in sorted(calls):
+ L.append(f" def {method(c)}(self, *args):")
+ impl = None
+ if ctx.llm is not None:
+ try:
+ impl = ctx.llm.write_body("Python method (self is the object)", c.replace("_", " "),
+ f"class {e.class_name} with attributes {props}")
+ except Exception:
+ impl = None
+ if impl:
+ L += [" " + ln for ln in impl.splitlines()]
+ else:
+ L.append(f' self.log("{c} called") # TODO: implement')
+ L.append("")
+ if len(L) and L[-1] != "":
+ L.append("")
+ return L
+
+ def _action(self, a: dict, name) -> list[str]:
+ op = a["op"]
+ if op in ("set", "add", "toggle"):
+ tgt = name(a["prop"])
+ if not tgt.startswith("self.world."):
+ if op == "set":
+ return [f"{tgt} = {self.expr(a['value'], 'python', name)}"]
+ if op == "add":
+ return [f"{tgt} += {self.expr(a['value'], 'python', name)}"]
+ return [f"{tgt} = not {tgt}"]
+ # property of another entity (e.g. "set door.open to true")
+ ent, prop = a["prop"].split(".", 1)
+ if op == "set":
+ val = self.expr(a["value"], "python", name)
+ elif op == "add":
+ val = f"{tgt} + ({self.expr(a['value'], 'python', name)})"
+ else:
+ val = f"not {tgt}"
+ return [f"self.world.set_remote({ent!r}, {prop!r}, {val})"]
+ if op == "destroy":
+ return ["self.destroy()", "return"]
+ if op == "log":
+ return [f"self.log({a['text']!r})"]
+ if op == "move":
+ return [f"self.move({self.expr(a['x'], 'python', name)}, {self.expr(a['y'], 'python', name)}, "
+ f"{self.expr(a['z'], 'python', name)})"]
+ if op == "send":
+ return [f"self.send({a.get('to')!r}, {a.get('fields') or None!r})"]
+ if op == "call":
+ args = ", ".join(self.expr(x, "python", name) for x in a.get("args", []))
+ m = a["name"]
+ return [f"self.{method(m)}({args})" if m.isidentifier() else f"pass # call {m}({args})"]
+ return [f"pass # {describe_action(a)}"]
+
+ def _main(self, ctx: BuildContext) -> str:
+ sysname = ctx.system.name
+ local = {e.id for e in ctx.entities}
+ self._cls = self._class_names(ctx)
+ L = ['#!/usr/bin/env python3',
+ f'"""{sysname} - python module. Generated by NLCL; edit freely."""',
+ "from nlcl_runtime import Entity, World, Hub, make_channel, main_args", "", ""]
+ for e in ctx.entities:
+ L += self._class(ctx, e)
+ L.append("")
+ L += ["def build(world):"]
+ if not ctx.entities:
+ L.append(" pass # this process only relays/bridges data between other modules")
+ for e in ctx.entities:
+ L.append(f" world.add({self._cls[e.id]}(world))")
+ hub_ports = set()
+ for c in ctx.channels:
+ kw = {"interval_ms": c.config.get("interval_ms", 1000),
+ "local_src": c.src.id in local, "local_dst": c.dst.id in local}
+ for k in ("baud", "port", "hub_url", "path", "broker", "broker_port", "topic", "types", "enums"):
+ if k in c.config:
+ kw[k] = c.config[k]
+ if c.protocol in ("http", "websocket"):
+ hub_ports.add(int(c.config.get("hub_url", "http://localhost:8765").rsplit(":", 1)[1]))
+ if c.protocol in ("spi", "i2c", "gpio", "wire"):
+ continue # electrical buses are handled by embedded/hardware modules
+ if c.src.id not in local and c.dst.id not in local and c.protocol not in ("serial",):
+ continue # other modules talk to the hub directly; nothing to do here
+ kwtxt = ", ".join(f"{k}={v!r}" for k, v in kw.items())
+ L.append(f" # {c.src.name} ({c.src.domain}) -> {c.dst.name} ({c.dst.domain}) via {c.protocol}")
+ L.append(f" world.channel(make_channel({c.protocol!r}, {c.id!r}, {c.src.ident!r}, {c.dst.ident!r}, "
+ f"{c.fields!r}, {kwtxt}))")
+ if c.protocol == "serial" and c.src.id not in local and c.dst.id not in local:
+ # bridge serial device -> hub so browsers/game engines can read it
+ hub_ports.add(8765)
+ L.append(f" world.channel(make_channel('http', {c.id!r}, {c.src.ident!r}, '__hub__', "
+ f"{c.fields!r}, interval_ms={kw['interval_ms']}, local_src=True)) # serial->hub bridge")
+ L.append(f" world.add(_Relay(world, {c.src.ident!r}, {c.fields!r}))")
+ L.append("")
+ if any(c.protocol == "serial" and c.src.id not in local and c.dst.id not in local for c in ctx.channels):
+ L = L[:5] + [
+ "class _Relay(Entity):",
+ ' """Mirror of a remote device so its data can be re-published to the hub."""',
+ " def __init__(self, world, name, fields):",
+ " super().__init__(world, name)",
+ " self.props = tuple(fields)",
+ " for f in fields:",
+ " setattr(self, f, 0)",
+ "",
+ " def on_update(self, dt):",
+ " for f in self.props:",
+ " setattr(self, f, self.world.remote.get((self.name, f), getattr(self, f)))",
+ "", ""] + L[5:]
+ L += ["", "if __name__ == '__main__':",
+ " args = main_args()",
+ " world = World(simulate=args.simulate, verbose=not args.quiet)"]
+ if hub_ports:
+ for p in sorted(hub_ports):
+ L.append(f" hub = Hub({p}) if not args.no_hub else None")
+ L.append(" if hub: hub.start()")
+ L += [" build(world)",
+ " print('[{0}] running {1} entities, {2} channels (Ctrl+C to stop)'.format("
+ f"{sysname!r}, len(world.entities), len(world.channels)), flush=True)",
+ " world.run(seconds=args.seconds, ticks=args.ticks)",
+ " for e in world.entities.values():",
+ " print(f' {e.name}: {e.state()}', flush=True)", ""]
+ return "\n".join(L)
+
+ # ------------------------------------------------------------------ run
+ def run(self, ctx: BuildContext) -> RunResult | None:
+ main = ctx.outdir / "main.py"
+ if not main.exists():
+ return RunResult(False, "build first")
+ return self.sh([sys.executable, "-u", "main.py", "--simulate", "--seconds", "3", "--no-hub"],
+ ctx.outdir, timeout=20)
+
+
+MODULE = PythonModule()
diff --git a/nlcl/modules/scene3d_mod.py b/nlcl/modules/scene3d_mod.py
new file mode 100644
index 0000000000000000000000000000000000000000..728ab968c13348174da59160719bbcb007f17041
--- /dev/null
+++ b/nlcl/modules/scene3d_mod.py
@@ -0,0 +1,1072 @@
+"""3D domain: three.js scenes / digital twins in the browser + a Blender script.
+
+Output (in /3d/):
+ index.html self-contained page (scene code inlined) - double-click to open
+ scene.js the same scene code as an ES module (edit + use dev.html)
+ dev.html loads scene.js; needs a local static server (serve.py)
+ serve.py tiny static server (python serve.py -> http://localhost:8000/dev.html)
+ blender_scene.py recreates the static scene in Blender (free) via bpy
+ README.md how to run it
+
+three.js is loaded from unpkg (three@0.160.0) through an importmap, so the page
+needs internet access the first time (the browser caches it afterwards).
+"""
+from __future__ import annotations
+
+import json
+import math
+import pprint
+import re
+import sys
+import tempfile
+from pathlib import Path
+
+from ..ir import Entity, describe_action
+from .base import BuildContext, Channel, DomainModule, RunResult
+
+ASSET_DIR = Path(__file__).parent / "_assets" / "3d"
+THREE_VERSION = "0.160.0"
+THREE_URL = f"https://unpkg.com/three@{THREE_VERSION}/build/three.module.js"
+ADDONS_URL = f"https://unpkg.com/three@{THREE_VERSION}/examples/jsm/"
+
+# entity kind -> rendering shape understood by the JS runtime / Blender script
+SHAPE_OF_KIND = {
+ "object": "box", "cube": "box", "box": "box", "crate": "box", "block": "box",
+ "sphere": "sphere", "ball": "sphere", "orb": "sphere",
+ "cylinder": "cylinder", "column": "cylinder", "pillar": "cylinder",
+ "cone": "cone", "torus": "torus", "toru": "torus", "tori": "torus", "ring": "torus", "donut": "torus",
+ "plane": "plane", "floor": "plane", "ground": "ground", "terrain": "ground",
+ "light": "light", "lamp": "light", "sun": "light",
+ "camera": "camera", "label": "label", "text": "label", "sign": "label",
+ "model": "model", "mesh": "model", "twin": "twin",
+ "building": "building", "house": "building", "tank": "tank", "silo": "tank",
+ "pipe": "pipe", "tube": "pipe", "arm": "arm",
+ "scene": "group", "group": "group", "room": "room", "assembly": "group",
+}
+SHAPES = set(SHAPE_OF_KIND.values())
+PIPEABLE = ("http", "websocket", "serial") # protocols a browser reaches through the NLCL hub
+
+# common colour names -> hex (CSS names are also understood by three.js at runtime)
+COLORS = {
+ "red": "#e53935", "green": "#43a047", "blue": "#1e88e5", "yellow": "#fdd835", "orange": "#fb8c00",
+ "purple": "#8e24aa", "violet": "#8e24aa", "pink": "#ec407a", "white": "#ffffff", "black": "#111111",
+ "gray": "#808080", "grey": "#808080", "brown": "#795548", "cyan": "#00bcd4", "magenta": "#d81b60",
+ "silver": "#c0c0c0", "gold": "#ffc107", "lime": "#cddc39", "navy": "#1a237e", "teal": "#00897b",
+ "maroon": "#800000", "olive": "#808000", "beige": "#f5f5dc", "turquoise": "#40e0d0",
+ "lightblue": "#90caf9", "darkblue": "#0d47a1", "lightgreen": "#a5d6a7", "darkgreen": "#1b5e20",
+ "lightgray": "#d3d3d3", "lightgrey": "#d3d3d3", "darkgray": "#505050", "darkgrey": "#505050",
+ "darkred": "#8b0000", "skyblue": "#87ceeb", "steel": "#71797e", "steelblue": "#4682b4",
+ "concrete": "#9e9e9e", "wood": "#a0703c", "glass": "#bfe3f2", "copper": "#b87333", "water": "#2f7fd8",
+}
+DEFAULT_HEX = {
+ "box": "#8fa3bf", "sphere": "#d9a441", "cylinder": "#6fb08f", "cone": "#c46b6b", "torus": "#a57fd1",
+ "plane": "#7d8794", "ground": "#4f5b4a", "building": "#b7bec9", "tank": "#9aa7b5", "pipe": "#7f8c99",
+ "arm": "#f0a020", "twin": "#5aa7d6", "model": "#9aa0a6", "room": "#5c6470", "light": "#ffffff",
+}
+
+
+def color_hex(v, fallback: str = "#8fa3bf") -> str:
+ """Best-effort conversion of a colour prop to #rrggbb (never raises)."""
+ try:
+ if isinstance(v, bool) or v is None or v == "":
+ return fallback
+ if isinstance(v, (int, float)):
+ return "#%06x" % (int(v) & 0xFFFFFF)
+ if isinstance(v, (list, tuple)) and len(v) >= 3:
+ vals = [float(x) for x in v[:3]]
+ if all(x <= 1 for x in vals):
+ vals = [x * 255 for x in vals]
+ return "#" + "".join("%02x" % max(0, min(255, int(x))) for x in vals)
+ s = str(v).strip().lower()
+ if s.startswith("0x"):
+ s = "#" + s[2:]
+ if re.fullmatch(r"[0-9a-f]{6}", s):
+ s = "#" + s
+ if re.fullmatch(r"#[0-9a-f]{6}", s):
+ return s
+ if re.fullmatch(r"#[0-9a-f]{3}", s):
+ return "#" + "".join(c * 2 for c in s[1:])
+ key = re.sub(r"[\s_\-]+", "", s)
+ return COLORS.get(key) or COLORS.get(s.split()[-1] if s.split() else "", fallback)
+ except Exception:
+ return fallback
+
+
+# "angle" props are rotations in degrees: angle (and angle_z) about z, angle_x / angle_y about x / y
+ROT_PROPS = {"angle": 2, "angle_z": 2, "angle_x": 0, "angle_y": 1}
+
+
+def _num(v, d: float = 0.0) -> float:
+ try:
+ if isinstance(v, bool):
+ return float(v)
+ f = float(v)
+ return f if math.isfinite(f) else d
+ except (TypeError, ValueError):
+ return d
+
+
+def _vec(v, d, fill_last: bool = False) -> list[float]:
+ if isinstance(v, (list, tuple)) and v:
+ a = [_num(x, 0.0 if not fill_last else 1.0) for x in v[:3]]
+ while len(a) < 3:
+ a.append(a[-1] if fill_last else 0.0)
+ return a
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
+ return [float(v)] * 3
+ if isinstance(v, str):
+ try:
+ f = float(v)
+ return [f] * 3
+ except ValueError:
+ pass
+ return list(d)
+
+
+def _js(v) -> str:
+ """JSON literal that is safe to inline in an HTML ' if src
+ else f'')
+ return f"""
+
+
+
+
+{title}
+
+
+
+
+
+
+
+