Commit Graph

847 Commits

Author SHA1 Message Date
David Montero 6584a49a8f feat(rp2040/uart): synthesize bit-level TX waveform on GP0 / GP4
Same gap as the AVR USART: rp2040js's UART fires `onByte(value)` per
transmitted byte but never toggles the corresponding GPIO, so an
oscilloscope on GP0 (UART0 TX, default for Arduino-Pico's Serial1) sees
nothing during `Serial.print`.  Real silicon drives the pin with the
full UART frame at the configured baud rate, and Velxio should match.

`emitUartTxFrame(uartIdx, byte)` derives:
  * `txPin` via FUNCSEL inspection: walk GP0 / GP12 / GP16 / GP28 (the
    four candidates for UART0 TX per RP2040 datasheet) and pick the
    first whose `functionSelect == 2` (FUNCTION_UART).  Same for UART1.
    Fall back to GP0 / GP4 when nothing is mapped (firmware hasn't
    called `Serial1.begin()` properly).
  * `baudRate` and `bitsPerChar` directly from the UART peripheral
    (rp2040js already exposes these as live getters).
  * Time from the RP2040 IClock's `nanos` counter, matching the
    existing `setupGpioListeners` path — UART waveforms therefore stack
    consistently with PIO / SIO traces on the same scope.

Both `uart[0].onByte` and `uart[1].onByte` get hooked.  The seed-idle-
HIGH baseline is pushed once per UART per simulation run; `stop()`
clears the flag so a re-run gets a fresh seed (matching how the scope
buffer is cleared on restart).
2026-05-22 19:54:55 +02:00
David Montero b587faf1b0 feat(avr/uart): synthesize bit-level TX waveform on PD1/PE1
avr8js intercepts the transmitted byte at the UDR0 register and never
toggles the corresponding GPIO.  Real ATmega328P / ATmega2560 hardware
drives PD1 / PE1 with a start bit, 8 data bits LSB-first, and a stop bit
at the configured baud rate the moment TXEN is set.  An oscilloscope
probe on D1 therefore showed nothing in Velxio while the same probe in
the real world would resolve the UART frame.

Synthesize the frame from the inside of `onByteTransmit`:

  * Read `usart.baudRate`, `usart.bitsPerChar`, `usart.parityEnabled`,
    `usart.parityOdd`, `usart.stopBits` so unusual configurations stay
    accurate (avr8js already exposes these as public getters).
  * Build the bit list start + data(LSB first) + parity? + stopBit(s).
  * For each transition vs. previous state (initial = idle HIGH), call
    `onPinChangeWithTime(1, state, timeMs)` where
    `timeMs = (cpu.cycles + i * cyclesPerBit) / 16_000`. Same
    simulator-time clock the existing port-listener path uses, so the
    scope draws the UART waveform cycle-accurately alongside other GPIO
    activity.

Also hook `onConfigurationChange` to detect TXEN flipping 0→1 and seed
the scope baseline at idle HIGH; without that, the very first byte's
start bit transition would be invisible because the scope's pre-first-
sample default is LOW.

Both USART construction sites (initial setupSimulation around line 423,
re-init after stop around line 749) get the same hook.

Covered by `__tests__/avr-uart-tx-waveform.test.ts` (5 cases): idle seed,
byte with internal transitions, 0xFF edge case, TXEN-disabled no-op,
bit-period timing.
2026-05-22 19:49:43 +02:00
David Montero 2eb195d671 test(joystick): update fixture to direction-style xValue / yValue
The previous test fed `xValue: 0, yValue: 1023` to the analog-joystick
handler and asserted X=0V, Y=5V. That was wrong for two reasons:

  1. wokwi-analog-joystick emits direction (-1/0/+1), never 0..1023, so
     the fixture didn't match how the real component behaves.
  2. The OLD `(value/1023) * vcc` mapping happened to produce 0V for 0
     and 5V for 1023, so the broken test still passed against the
     broken handler — and now breaks against the correct one.

Switch the fixture to `xValue: -1, yValue: 1` so the expectations line up
with the corrected handler (-1 → 0V, +1 → Vcc) and exercise the same
voltage rails the real component will produce.
2026-05-22 18:59:49 +02:00
David Montero e6fdd54ba3 fix(joystick): map wokwi-analog-joystick direction (-1/0/+1) to ADC voltage
The PartSimulationRegistry handler for 'analog-joystick' was reading
`el.xValue` / `el.yValue` and computing `(value / 1023) * vcc` as if the
component were a potentiometer producing a raw 0..1023 reading.  It is
not — `@wokwi/elements/analog-joystick-element` emits xValue / yValue as
a tri-state DIRECTION signal:

  *   xValue = -1  → "left"   (mousedown on left zone)
  *   xValue =  0  → centered (mouseup snap-back)
  *   xValue = +1  → "right"  (mousedown on right zone)
  (same for yValue with up/down)

`(±1) / 1023 ≈ ±0.001`, so the ADC channel sat at ~0 V no matter which
directional zone was clicked.  Center-button clicks worked because that
path is digital (`setPinState(SEL, …)`) and bypasses the analog map.

Fix:
  * Tri-state → voltage with explicit map: -1 → 0V, 0 → Vcc/2, +1 → Vcc.
  * Vcc was hardcoded to 5V for "not RP2040" — wrong for ESP32 / S3 /
    Nano-ESP32 / etc., which all run at 3.3V like the Pi Pico.  Detect
    ESP32 via the BridgeShim's `setAdcVoltage` method and select 3.3V
    for everything that isn't pure AVR.

Reported on /example/esp32-joystick where center-button-only worked but
directional zones did nothing.  Verification via Chrome MCP after deploy.
2026-05-22 18:57:26 +02:00
David Montero dccb70aacd fix(espidf): treat C++ stdlib headers as built-in in user_libs bundler
The user_libs_all bundler in _resolve_library_components does BFS over the
sketch's external includes, copying each matching Arduino library into
one merged IDF component.  Anything not in _BUILTIN_HEADERS is treated as
an external library to resolve, and the lookup just scans
/root/Arduino/libraries/ for a directory whose `src/` (or root) holds a
matching header file.

_BUILTIN_HEADERS only listed C headers (stdint.h, stdio.h, …).  The C++
wrappers (cstdint, cstdio, cmath, …) and the STL containers (vector,
complex, string, …) were absent.  Result: any library transitively
#including <cstdint> or <vector> caused the bundler to "resolve" the
header against /root/Arduino/libraries/ArduinoSTL/ — an AVR-only
uClibc++ port that ships every C++ stdlib header as plain files. Once
ArduinoSTL was matched the bundler dragged in ALL of it, including
complex.cpp:

    template class _UCXXEXPORT complex<float>;

which fails on the ESP-IDF Xtensa toolchain because _UCXXEXPORT isn't
defined in that compile context AND the symbol already exists in the
real libstdc++ pulled in by <complex>.  Net effect: every ESP32 sketch
whose deps transitively include a C++ stdlib header (e.g. ESP32Servo
includes <cstdint>) blew up with 66+ errors before the servo example
even reached the link step.

Fix: extend _BUILTIN_HEADERS to cover the full set of C++ stdlib
wrappers and STL headers so the bundler never treats them as installable
libraries.  The Xtensa GCC + libstdc++ shipped by ESP-IDF provides them
natively; ArduinoSTL never has any business being part of an ESP32 build.

Verified end-to-end on /example/esp32-servo: compile now succeeds, sketch
boots, moving the potentiometer drives the wokwi-servo angle (Pot=2801 →
Angle=123 deg, servo arm rotates).
2026-05-22 18:48:14 +02:00
David Montero cf4af79414 fix(esp32/ledc): translate ledcWrite(pin,duty) → ledcWrite(channel,duty)
arduino-esp32 3.x ledcWrite takes a PIN and looks up the attached channel
internally. arduino-esp32 2.x (the toolchain version we pin) takes a
CHANNEL. The velxio_compat.h shim already aliased the 3.x-only
ledcAttach onto ledcSetup+ledcAttachPin so 3.x sketches would compile,
but ledcWrite still mapped 1:1 — so a call like

    #define R_PIN 16
    ledcAttach(R_PIN, 5000, 8);   // shim → channel 0 attached to pin 16
    ledcWrite(R_PIN, 128);        // ★ writes to "channel 16" (invalid)

silently wrote to LEDC channel 16, which doesn't exist (valid range
0-15). The hardware duty register never changed, qemu-lcgamboa never
emitted a `ledc_duty` event, and the RGB LED stayed dark even though
the firmware ran cleanly and the wires looked right. Verified end-to-end
with examples/esp32-pwm-led-rgb: gpio_change events fired at boot, no
ledc_duty events fired, ledRed/ledGreen/ledBlue all stayed at 0.

Fix: maintain a 40-entry pin→channel table populated by both ledcAttach
variants. Replace ledcWrite with a macro that calls a helper checking
the table first; if the value isn't a known pin we pass it through as a
channel, preserving 2.x channel-style call sites.

Macro/function name collision is sidestepped with the standard
parenthesizing trick — `(ledcWrite)(channel, duty)` doesn't expand the
function-like macro because the token isn't followed by `(`.

Verified live on velxio.dev/example/esp32-pwm-led-rgb after hot-copying
the new header into the velxio-app container: ledRed/ledGreen/ledBlue
now cycle through the full HSV wheel as expected (samples: (255,41,0),
(41,255,0), (0,41,255), (232,255,0), …).

Single-file sketch only — the table is `static` (internal linkage) and
ledcAttach + ledcWrite live in the header. Multi-file sketches that
attach in file A and write in file B would each see their own table.
Acceptable for now since arduino-esp32 sketches are nearly always
single-file; revisit when we bump the toolchain to 3.x and can drop the
shim entirely.
2026-05-22 16:14:55 +02:00
David Montero 2dbc023df4 fix(arduino-cli): pin ATTinyCore to 1.4.1 (azduino.com micronucleus host unreachable)
ATTinyCore >=1.5.0 declares ATTinyCore:micronucleus@2.5-azd1b as a tool
dependency, hosted at https://azduino.com/bin/micronucleus/. That host
has been unreachable (connection refused) for extended periods, causing
every ATtiny85 compile to fail at the core-install step with:

  Download failed: performing HEAD request: ... dial tcp ...: connection refused
  Failed to install required core: ATTinyCore:avr

micronucleus is only used for USB upload — never for compilation — but
arduino-cli refuses to install a core whose tool deps cannot fetch.

Pin to 1.4.1, the last release whose micronucleus binary is hosted on
github.com (digistump release, reachable). The FQBN clock options we
ship (clock=16pll on attinyx5, etc.) are unchanged across 1.4.x.

  - backend/app/services/arduino_cli.py: new CORE_INSTALL_VERSIONS map
    consulted by ensure_core_for_board so the runtime auto-install
    passes "ATTinyCore:avr@1.4.1" instead of unversioned latest.
  - backend/Dockerfile and docker/entrypoint.sh: same pin so a fresh
    image bakes 1.4.1 in and never hits the runtime fallback path.

Existing regression tests in test/backend/unit/test_arduino_cli_attinycore.py
still pass (they assert presence, not version).
2026-05-22 15:15:53 +02:00
davidmonterocrespo24 0dcb504c1b feat(landing): "Try Simulator Free Online" + download CTA slot below
Two coordinated copy/layout changes on the landing hero:

  - Primary CTA label gets "Online" added across the 9 supported
    locales — "Try Simulator Free Online →" / "Probar el simulador
    online gratis →" / etc. Reason: with the Velxio Desktop
    download path now live, users should immediately understand
    that the green button is the BROWSER version, and there's a
    local install option for people who want it faster offline.

  - The pro-overlay slot for the desktop download CTA was
    `landing-hero-primary-cta` and sat ABOVE the hero CTAs. Renamed
    to `landing-hero-download-cta` and moved BELOW so the funnel
    reads "try online (primary) → or install locally (secondary)"
    instead of "install locally (primary) → try online (secondary)".

OSS layout is unchanged — the slot is still empty in pure builds.

Also picks up the auto-regenerated sitemap.xml lastmod dates from a
recent deploy (every URL bumped 2026-05-19 → 2026-05-21).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:33:21 +02:00
David Montero Crespo fc1f5e3d2e Refactor code structure for improved readability and maintainability 2026-05-21 02:32:19 -03:00
davidmonterocrespo24 86879f3a34 chore(vscode-extension): .vscodeignore + 0.2.0 .vsix artefact
Adds the missing `.vscodeignore` so future `vsce package` runs don't
bundle the webview's `node_modules/` (which made the v0.1.0 release
17 MB instead of <1 MB — webview is a thin React WebView app that
ships only its compiled bundle).

With the ignore in place, 0.2.0 packages down to 100 KB (10 files:
extension.js + webview index.js + manifest + LICENSE + README +
changelog + icon + diagram schema). Matches the precedent of
committing the .vsix alongside the source for offline installation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:18:15 +02:00
davidmonterocrespo24 201d414aa7 feat(vscode-extension): 0.2.0 — Pro license gate + deep-link sign-in
Adds the Velxio Pro subscription gate to the VS Code extension. Every
compile / run validates against `https://velxio.dev/api/pro/license/validate`
before proceeding; a 60-second in-memory cache avoids hammering the
endpoint during a tight compile/run loop. No offline mode by design —
the extension throws OfflineError on network failure rather than
caching a permission grant locally. For offline workflows users get
the desktop app (separate distribution channel).

New surface:

  - `LicenseService` (src/LicenseService.ts) — secret-store-backed key
    storage, validate, nonce-backed deep-link OAuth handshake,
    OfflineError + EntitlementError taxonomy.
  - `Velxio: Sign In`              — opens velxio.dev/auth/vscode, returns
                                     via vscode://velxio.velxio-simulator/auth.
  - `Velxio: Paste License Key`    — manual fallback for headless boxes.
  - `Velxio: Sign Out`             — clears the keychain entry.
  - `Velxio: Show License Status`  — plan + trial countdown modal.
  - Status bar item: Sign in / Trial Nd / Pro / Trial ended with the
    appropriate warning/error background colour.
  - Setting `velxio.licenseApiBase` for staging overrides.

CHANGELOG.md + README.md added.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:51:07 +02:00
davidmonterocrespo24 04d93d4f46 feat(frontend): desktop overlay (welcome, grace banner, ESP32 prompt)
New `frontend/src/desktop/` module loaded only when VITE_DESKTOP=true.
Hosts the Tauri-bound UI that pure OSS doesn't need:

  - tauriBridge.ts   typed invoke / listen / openExternal / beginSignIn
                     wrappers with no-op fallbacks for `vite dev` outside
                     the Tauri webview.
  - DesktopWelcomePage.tsx   sign-in flow with browser handoff +
                              paste-key fallback; listens for
                              `velxio://auth-completed` from the shell.
  - GraceBanner.tsx          renders soft/hard grace banners driven by
                              `license_status` + `velxio://license-status`
                              emits from the background checkin loop.
                              Toggles `body.vlx-desktop-readonly` so the
                              editor's Save / Compile buttons disable
                              themselves via CSS in hard-grace.
  - Esp32QemuPrompt.tsx      one-time download modal when the user picks
                              an ESP32 board on a fresh install.
  - index.ts                 mounts welcome conditionally and the side
                              panels unconditionally.
  - desktop.css              shared styles.

All entry points are no-ops outside Tauri so the existence of the
folder has zero effect on the OSS build.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:50:51 +02:00
davidmonterocrespo24 24f84442e8 feat(frontend): runtime API base + desktop overlay extension points
Adds `lib/apiBase.ts` so the SPA can be repointed at a non-default backend
at runtime (via `window.__VELXIO_API_BASE__`) without losing the existing
`VITE_API_BASE` build-time override or the default `/api` reverse-proxy
behaviour. compilation / libraryService / projectService / metricsService
all flow through it now; axios clients use a request interceptor so the
base resolves per-request rather than at module-load time.

main.tsx grows a `VITE_DESKTOP` flag: when set, the @pro overlay is
skipped (the desktop shell handles license + auth natively) and a
small `./desktop/index` module is dynamic-imported in its place. OSS
builds tree-shake both branches.

LandingPage gets a `data-velxio-slot="landing-hero-primary-cta"` marker
above the existing hero CTAs so velxio.dev can inject an OS-detect
"Download Velxio Desktop" button as the visual primary. The slot is
empty in pure OSS.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:50:19 +02:00
David Montero be24243e4b fix(esp32): add GPIO 16/17 pin aliases on DevKit V1 (RX2/TX2)
On the ESP32 DevKit V1 the silkscreen labels GPIO 16 / 17 as RX2 / TX2,
and Esp32Element.PINS_ESP32 only exposed the silkscreen names. Examples
that wire to numeric pin "16" or "17" (e.g. ledcAttach(16, 5000, 8) on
esp32-pwm-led-rgb) couldn't resolve those names — pinPositionCalculator
failed lookups, the wire endpoint fell back to (0,0)/(50,50) and the
LED component visually floated off the board, breaking the SPICE
netlist for the example.

Add "16" and "17" as aliases pointing to the same (134,143) / (134,131)
coordinates as RX2 / TX2 so both naming conventions resolve to the same
physical pin tip.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 21:16:33 +02:00
velxio-deploy 4ee8fb59e8 chore(examples): drop stray .png files from public thumbs
ExampleThumbnail.tsx only serves /examples-thumbs/<id>.webp; the .png
copies were sharp's intermediate format committed by mistake on
2026-05-19 (commit 8693f93) when scripts/refresh-example-thumbs.sh
copied both formats to public. Removing ~18 MB of unreferenced PNGs
keeps the public folder lean. WebP is supported by ~97% of browsers
in use; the old Safari fallback path goes through CircuitPreview
(the SVG mock), not the .png.
2026-05-20 06:55:41 +02:00
velxio-deploy d1de630614 chore(examples): add 46 missing example thumbnails
Generated by velxio-prod's scripts/capture-example-thumbs.mjs after
fixing three bugs (CTA-based navigation against renamed route,
heterogeneous data-file parsing, false-positive prefix match). The
gallery now has a real canvas screenshot for every example
exampleProjects exports — 263 / 263. Previously 44 examples (mostly
digital-* and i8080-* / z80-*) had no preview and rendered the
SVG mock fallback.
2026-05-20 06:55:24 +02:00
velxio-deploy 8693f93ed9 chore(examples): refresh 219 thumb file(s) [auto] 2026-05-20 05:03:13 +02:00
David Montero Crespo 4ff71765e7
Merge pull request #202 from davidmonterocrespo24/fix/circuit-sim-service-stop
fix(circuit-sim): stop() guard + drop edges with no V-source post-reb…
2026-05-19 22:52:08 -03:00
David Montero Crespo f5ae4853eb fix(circuit-sim): stop() guard + drop edges with no V-source post-rebuild
Two related bugs that surfaced as "Vitest worker exited unexpectedly /
Timeout terminating forks worker" on the circuit-simulation-service
test file.

Bug 1 — tick() recursively re-schedules itself in its finally block.
After afterEach disposes the scheduler via __resetMixedModeScheduler(),
those re-scheduled ticks throw "call loadCircuit first", get caught by
the console.warn, and the finally schedules ANOTHER tick. Infinite
Promise loop survives until the worker OOMs.

  Fix: add CircuitSimulationService.stop() that flips a `stopped` flag
  short-circuiting tick() + handleMcuEdge(). The test harness now
  tracks each started service in _activeServices and calls stop() in
  afterEach alongside the existing unsubscribe sweep.

Bug 2 — when an MCU edge fires on a pin that's NOT wired into any net
(buildNetlist skips it because netLookup returns null), handleMcuEdge
sees hasSource=false, self-heals by queueing the edge + tick().  The
rebuild still doesn't emit the V-source (no wire), so tick.finally
replays the edge → self-heal again → tick again → infinite loop AT
RUNTIME, not just in tests. A user toggling a digital pin without a
wire freezes the whole circuit simulation.

  Fix: in tick.finally's pendingMcuEdges replay loop, check whether
  the rebuilt netlist now contains a V-source for each pending edge's
  pin. If not, drop the edge silently — a future canvas tick triggered
  by adding the wire will pick it up via the normal subscription path.

Also fix the "coalesces an edge with an in-flight full solve" test
fixture: simpleBoardWithBoard leaves pin 9 unwired, so V_uno_9 was
never emitted and the test was racing the (now-bounded) self-heal
rebuild. Replaced with an inline fixture wiring pin 9 → resistor →
GND, mirroring the wired fixture used by the alter+republish test
right above it.

Full vitest --shard 1/2 + 2/2 pass cleanly (1886 tests, 22-29s per
shard) with no worker-exit warnings.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 03:49:29 +02:00
David Montero Crespo 95a60e1d01 test: align photoresistor-sensor fixtures + snapshots with 603b791 alias
Three failures introduced by 603b791 (which added
MAPPERS['photoresistor-sensor'] = MAPPERS['photoresistor'] so the
metadata-id 'photoresistor-sensor' resolves to a SPICE mapper):

- component-to-spice.test.ts "every mapped metadataId has a test fixture"
  flagged photoresistor-sensor as missing. Added a fixture entry that
  mirrors the photoresistor one — the part is electrically identical.

- examples-netlist-snapshot.test.ts > photoresistor-light and
  > nano-sensor-station snapshots now contain R_ldr_ldr + R_ldr_pull
  cards (correct LDR + 10k pull) instead of the previous
  R_autopull_n0 100M stub. This is the intended behaviour change:
  before the alias the LDR was unmapped and the netlist autopulled the
  net to ground with a 100M dummy; after the alias the SPICE deck
  carries the real divider topology. Regenerated only these two
  snapshot entries (vitest -u on the single file).

No production code changes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 18:29:21 -03:00
David Montero Crespo 603b791daa feat(attiny85+customchip): full ATtiny85 ADC/Timer0 + custom-chip pipeline fixes
ATtiny85 (AVRSimulator + collectPinStates + connectAnalogInputsToMcu + SimulatorCanvas + Attiny85Element + examples):
- Add attiny85AdcConfig with correct register addresses (ADMUX=0x27,
  ADCSRA=0x26, ADCSRB=0x23, ADCL=0x24, ADCH=0x25, DIDR0=0x34, adcInterrupt=0x08).
  Without this, analogRead() polled the wrong address forever and the
  firmware hung on first ADC read.
- Add attiny85Timer0Config + instantiate AVRTimer so OVF fires at the
  ATTinyCore-expected ~1.024 ms cadence. delay() advance is still blocked
  on avr8js TIFR auto-clear semantics (separate upstream issue, see
  ATTINY85_TIMER0_UPSTREAM_ISSUE.md in velxio-prod test plan).
- Map ATtiny85 ADC channels to PB-style pin names (PB5/PB2/PB4/PB3 -> 0..3)
  in connectAnalogInputsToMcu so SPICE node voltages reach the right ADC
  channel.
- Recognise /^PB\d+$/ in collectPinStates.pinNameToArduinoPin so wires
  named "PB1" emit v_attiny85_pb1 V-source and the LED responds to MCU
  writes. Previously every PB-wire returned -1 and SPICE saw no source.
- SimulatorCanvas: subscribe pin 1 (PB1) for the built-in LED on the
  attiny85 board kind (Digispark convention), instead of falling through
  to the pin-13 default.
- Attiny85Element: remove the hand-drawn "yellow LED" circle that was
  floating above the chip. The bare DIP-8 has no on-board LED; examples
  wire a real wokwi-led + resistor instead.
- examples.ts: add a real wokwi-led + 220 Ohm wokwi-resistor + wires to
  attiny85-blink, and add missing series resistors to attiny85-button-led
  and attiny85-ntc-sensor. attiny85-pwm-fade was already correct.

Custom-chip pipeline (CustomChipPart + simulatorBridges):
- Add a requestAnimationFrame loop that calls instance.tickTimers() every
  frame in CustomChipPart. Chips that register vx_timer_create (e.g. an
  i8080 stepping its core, or a sensor publishing samples) had timers
  added to the queue but nothing fired them; tickTimers was dead code.
- Gate the ESP32 backend path with detectSimulatorKind(sim)==='esp32'.
  The previous `typeof sim.registerSensor === 'function'` check matched
  AVR and RP2040 simulators too (they expose registerSensor for I2C
  sensor proxies), routing client-side chips to a non-existent ESP32
  worker on those boards.
- Replace direct simulator.usart.writeByte calls in avrUartTx with a
  JS-level FIFO + setTimeout(1ms) drainer. avr8js writeByte drops bytes
  under burst load (a chip emitting print_string lost ~99% of bytes via
  non-immediate, or kept only the last byte via immediate). The drainer
  attempts one non-immediate write per tick and retries on RXC busy /
  RXEN off. Added a guard for ATtiny85 (no USART -> would queue forever).

End-to-end verified: i8080-banner-streamer now prints the boot banner
followed by "uptime ticks: 0xNN" lines stepping every ~50 ms, executing
real Intel 8080 instructions inside the WASM chip.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 18:10:08 -03:00
David Montero Crespo a9285c6698 fix(ui): narrow pointer-passthrough whitelist; restore DHT22/HC-SR04 dialog
The previous fix (dd22bcf) used `isInteractive` to decide whether to let
the wokwi component own the pointerdown. That heuristic was too broad —
DHT22, HC-SR04, NTC, photoresistor, LED all register `attachEvents` for
the SPICE/sensor-update bridge but have NO internal pointer handlers, so
clicks on them got silently swallowed by the wokwi shadow DOM and the
property dialog never opened.

Replace with an explicit whitelist of wokwi tags that ACTUALLY own
pointerdown (rotary knobs, pushbuttons, slide switches, joysticks,
keypads, encoders, rotary dialer). Every other component, including
sensors/displays/LEDs with attachEvents, falls through to the canvas
which decides between drag-to-rearrange and click-to-open-dialog.

Documented the model in docs/wiki/component-interaction.md.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 15:16:47 -03:00
David Montero Crespo dd22bcfe50 fix(ui+spice+example): interactive wokwi components, NTC formula, photoresistor alias
Three independent fixes uncovered during a systematic example-by-example
audit (plan/full_test_plan/):

1. DynamicComponent.handleMouseDown was calling e.stopPropagation()
   unconditionally in the capture phase. That swallowed pointerdown
   BEFORE wokwi-potentiometer / pushbutton / slide-switch / joystick
   could see it, so the rotary knob would not rotate and buttons
   wouldn't press even with a real OS mouse. Now we skip the swallow
   when the click target is an inner wokwi-* element during a live
   simulation, letting the wokwi component own its own pointerdown
   while still allowing the canvas drag-to-rearrange flow on the
   wrapper / non-interactive surface.

2. examples.ts uno-ntc (and pico-ntc) sketch had the NTC divider
   formula inverted relative to both the SPICE mapper topology
   (VCC -> R_NTC -> A1 -> R_pull -> GND, the standard module wiring)
   and real wokwi-ntc-temperature-sensor modules. Moving the slider
   to 60 C made the firmware print -3.42 C. Flipped the formula to
   r = SERIES_R * (VCC - v) / v. Now slider 60 C -> Serial reports
   60.12 C and A1 voltmeter shows 4.00 V.

3. componentToSpice.ts photoresistor mapper was only registered under
   the bare key `photoresistor`, but example components use the
   metadataId `photoresistor-sensor`. Added an alias so the LDR +
   pull-down divider gets emitted for the real component instance.

All three reproduce visually in seconds; documented per-example in
plan/full_test_plan/examples/.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 15:10:42 -03:00
David Montero Crespo 2b668d882c
Merge pull request #201 from davidmonterocrespo24/fix/vitest-forks-toplevel-and-heap
fix(tests): migrate forks config to vitest-4 top-level + restore NODE…
2026-05-19 13:17:53 -03:00
davidmonterocrespo24 1f23066f47 fix(tests): migrate forks config to vitest-4 top-level + restore NODE_OPTIONS
Two issues in PR #200 became obvious from the next CI run:

1. **`poolOptions.forks.execArgv` had no effect.** Vitest 4 removed
   `test.poolOptions` entirely — every key under it moved to
   top-level `test.*`. The runner emits this banner on every run:

       DEPRECATED `test.poolOptions` was removed in Vitest 4.
       All previous poolOptions are now top-level options.

   So `test.poolOptions.forks.execArgv: ['--max-old-space-size=8192']`
   was silently ignored. Move it to `test.forks.execArgv` (and
   `test.forks.singleFork`).

2. **NODE_OPTIONS got dropped when the shard step was rewritten.**
   PR #199 added `env: NODE_OPTIONS: --max-old-space-size=8192` to
   the `npm test` step; PR #200 replaced the step with `npx vitest
   run --shard X/2` but did not carry the env-var across. Combined
   with #1, the workers reverted to Node's 4 GB default and shard 2
   (58 files) still OOMs at exactly 4128 MB heap.

Restore NODE_OPTIONS on the workflow step as belt-and-braces — it
gets honored by the parent vitest process, and the migrated config
covers the forked children.

With 8 GB heap × 2 shards × 58 files each, the cumulative state
from ngspice WASM + singletons fits comfortably and the suite
should exit cleanly.
2026-05-19 18:09:34 +02:00
David Montero Crespo fd6f1a43f7
Merge pull request #200 from davidmonterocrespo24/fix/frontend-tests-shard
fix(ci): shard frontend tests across two matrix legs
2026-05-19 12:54:29 -03:00
davidmonterocrespo24 a32d282b98 fix(ci): shard frontend tests across two matrix legs
The execArgv fix (PR #200) made vitest actually honor the 8 GB heap
cap — and the next CI run promptly proved that 8 GB is still not
enough. Log: every test passes but the worker hits
"Ineffective mark-compacts near heap limit" at exactly 8011 MB,
the new ceiling. Doubling again to 16 GB would be near the
GitHub-runner total RAM (16 GB) and start swapping.

The real culprit is per-file leak accumulation: 117 test files
share one vitest fork; each file lazy-loads ngspice WASM
(~24 MB), wires up MixedModeScheduler / zustand singletons, and
leaves some of that state alive in module-level closures even
after the file finishes. Sum over the suite ≈ 8 GB+ retained.

Split the run with vitest's built-in `--shard N/M`:

  - matrix.shard: [1, 2] alongside matrix.node-version: [20, 22]
    = 4 parallel runners
  - each runner executes `npx vitest run --shard ${shard}/2`
  - vitest hashes file paths into deterministic shards (same
    flaky file always lands in the same shard)
  - each runner only carries ~60 files of leak state → fits in
    the existing 8 GB cap from poolOptions.forks.execArgv

Coverage upload gated to shard 1 / node 22 to avoid the two
shards racing to overwrite the same artifact name. Coverage
itself runs once on the full suite (best-effort, may OOM, but
`continue-on-error: true` keeps it non-blocking).

The real fix is dispose hooks on the leaking singletons, but
that's a multi-PR cleanup of code paths I haven't touched in
this work item; sharding unblocks CI in the meantime.
2026-05-19 17:18:05 +02:00
David Montero Crespo 9f368fd382
Merge pull request #199 from davidmonterocrespo24/fix/vitest-forks-heap-execargv
fix(tests): bump fork heap via poolOptions.execArgv (NODE_OPTIONS ign…
2026-05-19 12:07:39 -03:00
davidmonterocrespo24 32d00ae0a7 fix(tests): bump fork heap via poolOptions.execArgv (NODE_OPTIONS ignored)
PR #198 added NODE_OPTIONS=--max-old-space-size=8192 to the
frontend-tests workflow assuming vitest's forks pool would inherit
it. It does NOT. Vitest 4's forks pool spawns workers via
child_process.fork() with an explicit execArgv list and ignores
the parent shell's NODE_OPTIONS env var — verified by reading the
post-merge GHA log: the Node OOM still fires at ~4.0 GB heap,
exactly the default v8 ceiling.

Set the heap cap at the pool level instead so the workers actually
see it. This is the canonical vitest 4 idiom for raising worker
limits — `poolOptions.forks.execArgv` is forwarded verbatim to
each forked child.

Independent of: the gpio_matrix_cb SIGSEGV fix in qemu-lcgamboa
(now landed) which addresses the Backend E2E failure mode. This
PR is exclusively the Frontend Tests heap fix.

This also serves as the trivial commit needed to re-trigger the
master CI run against the now-fixed libqemu binaries (v1.1.1
served from the license endpoint).
2026-05-19 17:05:20 +02:00
David Montero Crespo 11d08612da
Merge pull request #198 from davidmonterocrespo24/fix/esp32-worker-callback-iothread-and-fe-heap
fix(ci+esp32): unblock backend e2e + bump frontend node heap
2026-05-19 11:08:01 -03:00
davidmonterocrespo24 cfde1eb27c fix(ci+esp32): unblock backend e2e + bump frontend node heap
Two CI failures landed after PR #196 (esp32-gpio-matrix-cb-callback)
merged. Both are independent and fixed here together.

1) **Backend E2E: ESP32 hangs at bootloader handoff.**
   PR #196 added picsimlab_gpio_matrix_cb which fires on QEMU's
   iothread. The handler did `_emit({...})` for every routing
   change — and the ESP-IDF bootloader writes to gpio_out_sel
   *hundreds* of times during early boot (each peripheral init
   configures its matrix slot). Each emit acquires _stdout_lock
   and writes to the worker→manager pipe. If the manager drains
   even briefly slow, the pipe fills, write blocks, and the
   iothread stalls — symptom: ESP32 reports `entry 0x400805e4`
   then no Arduino setup() output for 75 s.

   Fix: the iothread callback now ONLY mutates the SignalRouter
   snapshot. It never emits. The 10 Hz poll thread
   (_refresh_signal_routing) stays as the sole emitter, so the
   wire-format event stream is unchanged. Benefit of having the
   callback over poll-only is reduced worst-case routing-emit
   latency (next poll tick vs up to 100 ms) and a warmer
   snapshot dict for cheaper poll diffs.

2) **Frontend Tests: Node OOM at end of suite.**
   117 test files run in one forks-pool worker. Several lazy-load
   the ngspice emscripten module (~30 MB), the MixedModeScheduler
   singleton, and other heavy modules whose dispose hooks aren't
   reached because singletons leak across files. Cumulative heap
   pressure exceeds Node's 4 GB default; the worker hits "Ineffective
   mark-compacts near heap limit" AFTER all 1881 tests pass and
   the OOM kill is reported by vitest as "Worker exited unexpectedly
   / Timeout terminating forks worker". This is not a real test
   failure — every individual test passes.

   Quick fix: pass NODE_OPTIONS=--max-old-space-size=8192 to the
   `npm test` step. Long-term, the singletons should add dispose
   hooks that test fixtures call in afterAll(), or the suite
   should shard into multiple `vitest run --shard` invocations.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:04:50 +02:00
David Montero Crespo be55c97cce
Merge pull request #197 from davidmonterocrespo24/fix/components-metadata-stale-and-vitest-worker-hang
fix: regenerate components-metadata + plug vitest worker leak
2026-05-19 10:52:28 -03:00
davidmonterocrespo24 7f0f72862c fix: regenerate components-metadata + plug vitest worker leak
Two CI failures landed together on master after PR #194 merged:

1. **components-metadata.json stale.** The `power-supply` thumbnail
   in scripts/component-overrides.json was updated (grey placeholder
   → branded PSU SVG with voltage/current labels) but the generated
   JSON wasn't regenerated. The pre-merge check
   `git diff --quiet frontend/public/components-metadata.json` now
   fails on master. Fix: `cd frontend && npm run generate:metadata`,
   commit the result.

2. **Frontend Tests > test (20/22): vitest worker hang.**
   `circuit-simulation-service.test.ts` had been calling
   `service.start()` in ~10 tests without storing the returned
   unsubscribe handle. Each call subscribes the service to the
   simStore; the listener captures the service + scheduler in
   its closure. After all tests complete, vitest's forks pool
   tries to terminate the worker but the still-active listeners
   keep the event loop pinned, producing:
       "Worker exited unexpectedly / Timeout terminating forks worker"
   All assertions actually pass — only the worker shutdown hangs.

   Fix: introduce a `startTracked(service)` helper that records
   the unsubscribe in a module-level array, plus an `afterEach`
   that drains the array. `__resetMixedModeScheduler()` still runs
   after to dispose the scheduler singleton. Replaced all 9 raw
   `service.start()` callsites.

Both are independent of any production code change. The fix is
test/scaffolding only.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 15:38:22 +02:00
David Montero Crespo 2e0e92f4f6
Merge pull request #196 from davidmonterocrespo24/feat/esp32-gpio-matrix-cb-callback
feat(esp32-worker): register picsimlab_gpio_matrix_cb callback
2026-05-19 10:30:05 -03:00
davidmonterocrespo24 437f5f83bc feat(esp32-worker): register picsimlab_gpio_matrix_cb callback
Wires the new synchronous GPIO Matrix callback exposed by
libqemu-{xtensa,riscv32} 1.1.0 (lcgamboa/qemu commit e178ff5).
Whenever the firmware writes GPIO_FUNCx_OUT_SEL_CFG_REG, the C
plugin now fires picsimlab_gpio_matrix_cb(gpio, signal_id) inline.

The handler:
- Treats signal_id == 0x100 or 0 as "matrix routing cleared" and
  emits gpio_routing_clear.
- For LEDC HS/LS range signals (the only ones the frontend
  SignalRouter currently consumes), updates the mirror and emits
  gpio_routing.
- Drops other signals — the mirror does not need to track them
  yet, and emitting them would only fatten WS frames.

Backwards compat:
- Older libqemu (<1.1.0) doesn't expose the new field; the
  picsimlab_gpio_matrix_cb placeholder runs (no-op) and the
  100 ms _refresh_signal_routing() poll thread continues to feed
  the mirror. WS event shape is identical either way.

Burn-in: keeping the poll thread active in parallel with the
callback for now. Once telemetry confirms parity (per phase 4 doc
in velxio-prod/project/esp32-gpio-matrix-cb/), the poll thread
gets retired in a follow-up commit.
2026-05-19 08:24:52 +02:00
David Montero Crespo bd23a05d23
Merge pull request #195 from davidmonterocrespo24/feat/chip-programmable-rom
Feat/chip programmable rom
2026-05-19 02:28:49 -03:00
David Montero Crespo 321997715d feat(editor): Monaco syntax highlight for 8080/Z80 assembly
When the editor opens a .s or .asm file (the chip-program files routed
to /api/compile-rom), Monaco now colorizes 8080/Z80 mnemonics, registers,
hex/binary literals, comments, and directives. Same highlighter covers
both ISAs since most mnemonics overlap.

- frontend/src/components/editor/retroAsmLanguage.ts: a Monarch tokenizer
  + LanguageConfiguration + idempotent registration helper. Recognises
  the full 8080 ISA, all the Z80 additions (LD/JR/DJNZ/EXX/EX/IM/LDIR/
  bit ops/index ops), the directives ORG/DB/DW/EQU/END, and registers
  including condition codes (NZ/Z/NC/etc.) and IX/IY.

- CodeEditor.tsx: maps `.s` and `.asm` to the new `retro-asm` language
  and calls `registerRetroAsm(monaco)` in beforeMount so the language
  exists by the time the editor first paints. Other extensions
  (.ino/.cpp/.c/.py/.json/.md) behave exactly as before.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:49:51 -03:00
David Montero Crespo 0e2f0790db feat(chips): C-to-Z80 compile via SDCC + LED chaser example
Adds a third format to /api/compile-rom: `c` (C source compiled by SDCC
to Z80 bytes). Same chip-program flow as 8080/Z80 asm — write C in a
project file, click Compile, click Run.

Backend:
- backend/app/services/c_compile.py — async SDCC wrapper. Locates the
  sdcc binary on PATH (or via SDCC env var, or common Windows install
  paths) and shells out with target=mz80 + --code-loc 0x100 --data-loc
  0x8000. Parses the resulting Intel HEX into raw ROM bytes. Pure 8080
  is rejected with a clear error (SDCC has no 8080 backend; Z80 ROMs
  also run on the i8080-cpu chip if you avoid Z80-only ops).
- rom_compile.py: compile_rom is now async; the new c branch delegates
  to c_compile. compile_rom_endpoint awaits it.

Frontend:
- romCompileService: RomFormat gains 'c'; formatForFile maps .c/.cpp to
  'c'. isChipProgramFile intentionally still excludes .c — disambiguation
  happens at the EditorToolbar level.
- EditorToolbar: the chip-program path also fires when a custom-chip
  has programFile === activeFile.name (regardless of extension). That
  lets .c files route to /api/compile-rom (SDCC) when bound to a CPU
  chip, while .c files NOT bound to any chip continue to route to
  arduino-cli as before.

Docker:
- Dockerfile.standalone adds `sdcc` to the apt-get install list, so the
  prod image ships with SDCC out of the box.

Example:
- /examples/z80-led-chaser-c — z80-cpu chip + chaser.c (a Larson
  scanner written in C with __at() MMIO definitions). Compiles cleanly
  with SDCC's --code-loc 0x100 default crt0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:31:10 -03:00
David Montero Crespo 96ef12b585 feat(chips): programmable Z80 chip + Larson scanner example
Adds the Zilog Z80 to the programmable-retro-CPU lineup. Same compile-rom
flow that landed for the 8080 in PR #189: write Z80 asm in a project
file, click Compile (backend assembles via in-tree two-pass asm-z80),
click Run, the chip emulator boots from the resulting ROM bytes.

Backend:
- backend/app/services/asmz80.py — two-pass Z80 assembler covering the
  practical demo subset: LD r,n / r,r' / rp,nn / (nn),A / A,(nn) +
  ALU r/n + INC/DEC + JP/JR/DJNZ/CALL/RET + PUSH/POP + IN/OUT +
  EX/EXX + LDIR/LDDR/IM/NEG + RLCA/RRCA/RLA/RRA + the simple
  ED-prefix variants. Not yet: CB-prefix bit ops, DD/FD index ops.
- rom_compile.py routes target=z80 through the new assembler.

Chip:
- frontend/src/components/customChips/examples/intel/z80-cpu.{c,chip.json}
  Generated by scripts/make-z80-cpu.py from the existing z80.c emulator
  (same clean-room implementation that passes ZEXDOC end-to-end). The
  external pin/bus protocol is replaced with internal RAM + ROM + MMIO
  for LED/BTN/UART. 35 KB WASM.

Example:
- /examples/z80-larson-scanner — Knight-Rider-style walking LED.
  Demonstrates JR/DJNZ/RLCA which the 8080 can't run.

Plus a small Z80 smoke-test asm under scripts/.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:21:08 -03:00
David Montero Crespo b4358786d6
Merge pull request #194 from davidmonterocrespo24/fix/pinmanager-test-mocks
fix(tests): update mocks + assertions for PinManager API changes
2026-05-19 00:16:21 -03:00
davidmonterocrespo24 666f9c4008 fix(tests): update mocks + assertions for PinManager API changes
PR #192 (spice-led-pipeline) added two PinManager changes that were
not reflected in the test mocks / assertions:

- `setPinState(pin, state)` gained an optional `source: 'mcu' |
  'external'` third arg. Production ESP32-C3 / RISC-V simulators
  now pass `'mcu'` to mark the call as an MCU output (so the SPICE
  collector emits a V-source). The esp32c3-blink and esp32c3-simulation
  tests asserted on the old 2-arg shape.
- `resetPinStates()` is a new public method on PinManager called by
  `stopBoard` / `resetBoard` to clear cached pin states. The mocks in
  esp32-integration.test.ts and multi-board-integration.test.ts did
  not add it, so any test that ran stopBoard hit
  `TypeError: getBoardPinManager(...)?.resetPinStates is not a function`.

This commit:
- Adds `'mcu'` to the two ESP32-C3 setPinState assertions.
- Adds `this.resetPinStates = vi.fn()` to both integration mocks.

These are pure test fixups — no production code touched. The
`circuit-simulation-service.test.ts > handleMcuEdge` failure
(`expected 1 to be 2`) is a separate regression in production code
introduced by PR #192 and is NOT fixed here.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 04:52:30 +02:00
David Montero Crespo bbf8cd0303 feat(chips): programmable retro CPU chips with external ROM
Adds a new way to use the retro CPU chips: write your program in a
project file (.s / .asm / .hex / .bin), click Compile, click Run, and
the same chip emulates whatever you wrote. Same chip + different ROMs =
mini PC, calculator, LED demo, Kill-the-Bit game, etc.

SDK:
- velxio-chip.h gets two new host imports:
    uint32_t vx_rom_size(void);
    void     vx_rom_read(uint32_t off, uint8_t* dst, uint32_t len);
  CPU-emulator chips call these in chip_setup to pull their program out
  of the host's romBytes property.

Frontend runtime:
- ChipRuntime accepts opts.romBytes (Uint8Array) and exposes the new
  imports, copying bytes into chip memory on vx_rom_read.
- CustomChipPart pulls component.properties.romBytes (base64) and passes
  it through.
- Component registry declares three new custom-chip properties:
  romBytes (base64), programFile (matching project filename), and
  programTarget (cpu name).

New programmable bundled chip:
- frontend/src/components/customChips/examples/intel/i8080-cpu.{c,chip.json}
  Same clean-room 8080 emulator as i8080-repl/i8080-counter, but ROM is
  loaded externally via vx_rom_*. Has 8 LEDs, 8 buttons, UART, 16 KB RAM,
  32 KB of external ROM.

Backend:
- New /api/compile-rom endpoint and rom_compile service that turns
  chip-program source into ROM bytes. 8080 ASM is assembled by the
  in-tree two-pass assembler (moved to backend/app/services/asm8080.py).
  Intel HEX records are parsed; raw .bin is passed through. Future targets
  (z80, 8086, 4004) are scaffolded but not wired yet.

EditorToolbar:
- Compile button detects when the active file is .s/.asm/.hex/.bin and
  routes to compile-rom instead of arduino-cli. The compiled bytes are
  injected into every custom-chip on the canvas whose programFile property
  matches the active filename (or is empty).

Example:
- /examples/i8080-killbits loads Dean McDaniel's 1975 Kill-the-Bit on
  the programmable i8080-cpu chip. killbits.s is shipped as a project
  file alongside sketch.ino; the user clicks Compile then Run and the
  LED walks across 8 outputs, buttons kill it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 23:38:18 -03:00
David Montero Crespo ca1bf00597
Merge pull request #193 from davidmonterocrespo24/esp32-cleanup-broadcast-pwm
refactor(esp32): retire ledc_update + broadcastPwm + channelGpioMemo
2026-05-18 23:23:05 -03:00
davidmonterocrespo24 ba59fd4b4a refactor(esp32): retire ledc_update + broadcastPwm + channelGpioMemo
The SignalRouter path has been in prod through Phase 2.5 / Phase 3.3
deploys without regressions, so the temporary fallback shipped in
commit 77bf897 can come out. Closes #101.

Backend (esp32_worker.py + esp32_lib_manager.py):
- Stop emitting `ledc_update` from the 0x5000 LEDC callback and from
  the polling thread. Only `ledc_duty` (channel + duty_pct) and the
  GPIO matrix routing events ship now.
- Drop the channel→gpio reverse-lookup that fed the legacy event.

Frontend:
- Delete `PinManager.broadcastPwm` and `PinManager.pwmListenerPinCount`.
- Delete `makeLedcUpdateHandler` + its `channelGpioMemo`.
- Delete `Esp32Bridge.onLedcUpdate` field + the `case 'ledc_update':`
  message handler + the `LedcUpdate` type.
- Strip `this.onLedcUpdate = null` from 14 test mocks.
- Rewrite the `does not call broadcastPwm` guard in
  esp32-multi-servo-gpio-matrix.test.ts to assert the method itself
  no longer exists on PinManager (stronger regression guard than the
  spy version, and doesn't need vi).
- Remove the `PinManager.broadcastPwm fallback` describe block from
  esp32-servo-pot.test.ts — every test in it exercised the deleted
  fallback path.

Docs (ESP32_EMULATION.md):
- Replace `ledc_update` rows in the events / implementation tables
  with the SignalRouter trio (`ledc_duty`, `gpio_routing`,
  `gpio_routing_clear`).
- Update the visual flow diagram + the "why this matters" paragraph
  to past-tense the broadcastPwm bug.

Tests: 1886 frontend tests pass (the previously-failing
board-kinds-coverage test that needed the new Pi Zero/1/2 kinds is
also green). Backend unit suite: 279 pass, the 11 espidf_real_paths
prereq failures are environment-dependent (need arduino-cli libs in
the local shell) and unrelated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 04:05:34 +02:00
David Montero Crespo b98b1bf1df
Merge pull request #192 from davidmonterocrespo24/fix/spice-led-pipeline
Fix/spice led pipeline
2026-05-18 22:48:21 -03:00
David Montero Crespo d898f122ec test(visual-led): add RGB + 7-segment leafCheck assertions
Two new harness modes that would have caught the PinTracer signature
bug fixed in 55b3dd2:

- `leafCheck: 'rgbLed'` — samples wokwi-rgb-led.ledRed/Green/Blue 16
  times across a fade cycle and asserts each channel takes ≥2 distinct
  values. The buggy version stayed at {0} for every channel because the
  resolver locked itself to FLOATING and onChange never fired.

- `leafCheck: 'sevenSegment'` — samples wokwi-7segment.values 12 times
  and asserts ≥4 distinct segment patterns. Counter sketches naturally
  hit 10+ patterns when working; ≤1 means the segment subscribers never
  saw an edge.

Both checks are now in the default suite alongside Blink, Button,
Traffic-Light, Fade. Result with current main: 6/6 pass.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 22:39:01 -03:00
David Montero Crespo 55b3dd29e5 fix(DynamicComponent): pass componentId through to PinTracer
`PinTracer` signature is `(componentId, componentPinName) => number | null`
but the local `getArduinoPin` lambda only accepted one arg and used the
closure-captured `id`. When `createDefaultPinResolver` passed both args
(per the typed signature), JS bound the FIRST arg (the componentId) into
the lambda's single `componentPinName` parameter. `traceDetailed` then
looked up a pin literally named "rgb-led-1" on component "rgb-led-1",
returned null, and the resolver locked itself into 'FLOATING' state —
its onChange path never subscribed and the wokwi-rgb-led element's
ledRed/ledGreen/ledBlue stayed at 0 forever even as the SPICE side
correctly cycled through R, G, B, Y, C, M, W via analogWrite().

Same bug latent for any multi-pin component that goes through the
PinResolver path (multi-pin LEDs, RGB strips, 7-seg drivers, anything
that calls `getPinResolver(<pinName>)` for several pin names).

Fix: lambda now accepts both shapes — `getArduinoPin(pinName)` (legacy
single-arg used by every PartSimulationRegistry handler) AND
`getArduinoPin(componentId, pinName)` (PinTracer 2-arg form used by
createDefaultPinResolver / createSpiceResolvedPinResolver). Picks the
right componentId in either case.

Verified via the rgb-led example: ledRed/ledGreen/ledBlue now cycle
0→255→0 in sync with the SPICE node voltages on pins 9/10/11.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 22:08:06 -03:00
David Montero Crespo 677d3a673a
Merge pull request #191 from davidmonterocrespo24/fix/spice-led-pipeline
Fix/spice led pipeline
2026-05-18 21:55:26 -03:00
David Montero Crespo 81837eedb9 fix(spice+pipeline): LED visualization, INPUT_PULLUP, ESP32-C3, PWM fade, examples
End-to-end pipeline fixes uncovered while auditing the /examples gallery.
Each bug shipped past green unit + snapshot tests because none of those run
firmware + render LEDs. Added scripts/visual-led-test.mjs as a CDP-driven
visual harness that loads each example, runs the simulator, samples
`wokwi-led.brightness`, and asserts toggle / gradient / initial-off
invariants — exits non-zero on any regression.

Frontend simulator
- PinManager.updatePort: new optional ddrMask param. A pin is added to
  `outputPins` only if the DDR bit is set, so the PORTx write that
  enables INPUT_PULLUP (DDR=0, PORT=1) no longer falsely marks the pin
  as MCU output. AVRSimulator now reads DDRB/C/D (0x24/0x27/0x2A on
  Uno/Nano, 0x37 on ATtiny85, per-port table on Mega) and forwards it.
- AVRSimulator: pass DDR mask alongside every port-listener fire.
- BasicParts pushbutton{,-6mm}: seed pin HIGH in attachEvents so
  `digitalRead()` returns HIGH while idle. avr8js doesn't auto-simulate
  INPUT_PULLUP — without this the firmware reads LOW from boot and
  thinks the button is permanently pressed (the "LED is always on,
  pressing does nothing" UX bug).
- connectMcuEdgesToService: suppress synthetic digital edges on pins
  with active PWM, AND subscribe to onPwmChange to re-tick the netlist
  on duty changes. Fade-LED now produces a true gradient (6 distinct
  brightness levels across a fade cycle) instead of a binary 0/full
  toggle.
- CircuitSimulationService.handleMcuEdge: replace single-slot
  pendingMcuEdge with a per-pin Map. Multiple pins toggling during the
  same in-flight tick used to overwrite each other; now every pin's
  most-recent edge replays after the tick. Fixes Traffic-Light RED→
  YELLOW→GREEN sequencing.
- NetlistBuilder: new sanitizeSpiceId() helper replaces hyphens with
  underscores in V-source names. ngspice's interactive `alter` command
  treats `-` as an operator and silently no-ops on hyphenated source
  names, so mid-simulation MCU pin transitions stopped propagating
  after the first solve. MixedModeScheduler.onMcuPinChange and
  CircuitSimulationService self-heal use the same sanitizer so names
  stay consistent across emit/alter/lookup. Also added a regex-based
  fallback in step 2 so any board pin matching `GND.\d+` canonicalises
  to net "0" — ESP32-C3 dev kits expose up to 10 GND pins and the
  per-board `groundPinNames` list missed several, leaving wires
  floating instead of grounded.
- collectPinStates: emit V-sources only for pins in `outputPins`, not
  every wired board pin. Leaves INPUT pins (analog sensors on A0,
  pull-down dividers, etc.) free for the SPICE solver instead of being
  shorted to 0 V by an ideal MCU V-source.
- start.ts: extended __spiceDebug to also expose outputPinsByBoard +
  nodeVoltages + pinNetMapEntries for the visual harness.
- ESP32 / RP2040 / RISC-V / C3 simulators: pass `'mcu'` source flag to
  triggerPinChange / setPinState so the new outputPins tracking fires
  on those boards too (was AVR-only before).
- useSimulatorStore: stopBoard/resetBoard call pm.resetPinStates() so
  outputPins clears between runs; Esp32Bridge.onPinChange passes the
  `'mcu'` flag in all three places it's wired.
- types/board.ts: ATtiny85 FQBN `clock=internal16mhz` →
  `clock=16pll` (ATTinyCore 1.5.2 renamed the option).

Backend
- esp-idf-template/main/CMakeLists.txt: skip the
  `-DLED_BUILTIN=2` fallback for esp32c3 and esp32s3 targets. Both
  variants already define LED_BUILTIN in pins_arduino.h via a
  self-define macro (`#define LED_BUILTIN LED_BUILTIN` + `static const
  uint8_t LED_BUILTIN = ...;`). Pre-defining the symbol from the
  command line expanded the static-const declaration to
  `static const uint8_t 2 = ...;` — a syntax error that broke every
  ESP32-C3 / S3 build (`expected unqualified-id before numeric
  constant`).

Examples
- examples.ts: bulk-fix 72 wire endpoints that referenced
  `componentId: 'nano-rp2040'` / `'esp32-c3'` etc. (boards that don't
  exist on the canvas). Replaced with `'arduino-uno'` (the canvas
  board-id convention) and converted `D<n>` pin names to `GP<n>` for
  Pico-style boards. Affects pico-blink, pico-i2c-scanner,
  pico-i2c-rtc-read, pico-spi-loopback, c3-blink and others.

Tests
- scripts/visual-led-test.mjs: CDP-driven harness. Default suite covers
  Blink (single-pin), Button (idle-OFF invariant — catches the
  INPUT_PULLUP regression), Traffic-Light (multi-pin sequencing),
  Fade-LED (PWM gradient — ≥3 distinct levels), RGB-LED (≥3 PWM pins
  driven). Run via `npm --prefix frontend run test:visual` against a
  Chrome on `:9222` + vite on `:5174` + backend on `:8001`.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 21:52:07 -03:00
David Montero Crespo a179f8492e Refactor code structure for improved readability and maintainability 2026-05-18 21:50:45 -03:00