velxio/test/test_circuit/test/e2e_pot_pwm_led.test.js

101 lines
3.5 KiB
JavaScript
Raw Normal View History

feat: electrical simulation via ngspice-WASM (eecircuit-engine) Adds full SPICE-accurate electrical simulation to Velxio, behind a lazy- loaded ⚡ toolbar toggle. Arduino / ESP32 / RP2040 sketches now co-simulate with real analog behaviour: correct voltages on wires, real I–V curves on LEDs, working potentiometers, NTC thermistors read by analogRead(), PWM driving RC filters, transistors, op-amps, diodes, MOSFETs, etc. Engine: eecircuit-engine (ngspice compiled to WebAssembly). Main bundle stays at 2.4 MB; the 20 MB SPICE chunk only loads when the user activates electrical mode. Disabled at build time via VITE_ELECTRICAL_SIM=false. Frontend additions: - simulation/spice/: SpiceEngine wrapper + lazy entry, NetlistBuilder with UnionFind over wires, componentToSpice mapping (24 metadataIds incl. real part numbers: 2N2222, 2N3055, BC547, IRF540, 2N7000, 1N4148, 1N4007, 1N4733, LEDs, NTC, op-amp ideal), CircuitScheduler with debounced coalescing, AVRSpiceBridge for quasi-static co-simulation. - store/useElectricalStore: Zustand slice, feature-flag aware. - components/analog-ui/: ⚡ toolbar toggle + SVG voltage overlay. - components/components-instruments/: Voltmeter, Ammeter probes. - 62 tests (spice-*, netlist-builder, component-to-spice, instruments). Sandbox (test/test_circuit/): 47-test validation sandbox that proved the approach (hand-rolled MNA baseline + ngspice pipeline) before porting to the app. Kept as reference. Docs: docs/wiki/circuit-emulation-*.md (13 engineering pages covering architecture, solvers, components, AVR bridge, gotchas, performance, integration plan, API reference, appendix) + electrical-simulation- user-guide.md (end-user facing). Reference plan: test/test_circuit/plan/phase_8_velxio_implementation.md Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 19:11:54 +07:00
import { describe, it, expect } from 'vitest';
import { AVRHarness } from '../src/avr/AVRHarness.js';
import { potToPwmProgram } from '../src/avr/programs.js';
import { Circuit, VoltageSource, Resistor, Potentiometer, LED } from '../src/index.js';
/**
* E2E: Potentiometer → ADC → PWM → LED brightness.
*
* +5V ─── pot_top ─┐
* │
* (10k)
* │
* ├── A0 (ADC)
* │
* (10k)
* │
* GND ─── pot_bot ─┘
*
* pin6 (PWM) ─── 220Ω ─── LED_anode, LED_cathode → GND
*/
function setupRig(wiperPos) {
const avr = new AVRHarness();
avr.loadProgram(potToPwmProgram());
const circuit = new Circuit();
// Fixed 5 V rail
circuit.addComponent(new VoltageSource('V_CC', 'vcc', 'gnd', 5));
// Potentiometer across vcc–gnd, wiper = 'a0'
const pot = new Potentiometer('POT', 'vcc', 'a0', 'gnd', 10000, wiperPos);
circuit.addComponent(pot);
// ADC input impedance (very high) so the wiper isn't loaded
circuit.addComponent(new Resistor('R_adc', 'a0', 'gnd', 100e6));
// PWM pin drives an LED through a 220 Ω resistor
const pin6 = new VoltageSource('V_PIN6', 'pin6', 'gnd', 0);
circuit.addComponent(pin6);
circuit.addComponent(new Resistor('R_led', 'pin6', 'led_a', 220));
const led = new LED('LED', 'led_a', 'gnd', 'red');
circuit.addComponent(led);
// Bridge: recompute A0 voltage, inject into ADC
circuit.solveDC();
avr.setAnalogVoltage(0, circuit.nodeVoltage('a0'));
return { avr, circuit, led, pin6, pot };
}
/**
* Run the harness until the PWM output has stabilized, then compute the
* average LED current over one PWM period by sampling OCR0A as the
* instantaneous duty.
*/
function measure(avr, circuit, led, pin6, { cyclesToSettle = 200_000 } = {}) {
avr.runCycles(cyclesToSettle);
const duty = avr.getPWMDuty(6); // 0..1
// Average voltage delivered to the LED by a PWM signal:
// V_avg_source = duty · 5 V
// Feed this into the circuit and compute brightness.
pin6.setVoltage(duty * 5);
circuit.solveDC();
return {
duty,
ledCurrent: led.currentThrough(circuit.state),
brightness: led.brightness(circuit.state),
};
}
describe('E2E — Pot → analogRead → PWM → LED brightness', () => {
it('produces monotonically increasing brightness as the wiper moves from 0 → 1', () => {
const positions = [0.0, 0.25, 0.5, 0.75, 1.0];
const results = positions.map(p => {
const rig = setupRig(p);
return {
pos: p,
a0: rig.circuit.nodeVoltage('a0'),
...measure(rig.avr, rig.circuit, rig.led, rig.pin6),
};
});
// Log table for human inspection in test output
for (const r of results) {
console.log(
`wiper=${r.pos.toFixed(2)} V_A0=${r.a0.toFixed(3)}V duty=${(r.duty*100).toFixed(1)}% I_LED=${(r.ledCurrent*1000).toFixed(2)}mA B=${r.brightness.toFixed(3)}`
);
}
// Duty should track the wiper position
expect(results[0].duty).toBeLessThan(0.05);
expect(results[results.length - 1].duty).toBeGreaterThan(0.9);
// Brightness monotonically increases
for (let i = 1; i < results.length; i++) {
expect(results[i].brightness).toBeGreaterThanOrEqual(results[i - 1].brightness - 0.01);
}
// End brightness > 0.5, start brightness < 0.05
expect(results[0].brightness).toBeLessThan(0.05);
expect(results[results.length - 1].brightness).toBeGreaterThan(0.5);
});
});