Metadata-Version: 2.5
Name: sim86
Version: 0.1.0
Summary: DEMO/FEEDBACK PREVIEW, not for production (contact t@simulator86.com). Run firmware on simulated boards in the Simulator86 cloud: CLI, pytest plugin, fault injection.
Project-URL: Homepage, https://sim86.com
Project-URL: Documentation, https://docs.sim86.com
Author: Simulator86
License: Proprietary
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Pytest
Classifier: Topic :: Software Development :: Embedded Systems
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.9
Requires-Dist: certifi
Requires-Dist: pytest>=8
Requires-Dist: websockets>=13
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Provides-Extra: test
Requires-Dist: pytest-xdist>=3; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# sim86

> **Demo and feedback preview.** sim86 is shared so you can try Simulator86
> and tell us what you think. It is **not designed for production use**: no
> stability, compatibility or availability guarantees, and commands may
> change. For more information, contact **Tariq** at
> [t@simulator86.com](mailto:t@simulator86.com).

Run your firmware on simulated boards in the Simulator86 cloud, test it with
pytest, and break the hardware on purpose to see what your firmware does.

- **One JSON file per board**: parts, wires, firmware per chip ([how to build one](docs/circuits.md)).
- **`sim86 run`**: run it and stream what every chip prints.
- **pytest plugin**: each test gets a live run of your board.
- **Fault injection**: short, open or bridge wires, or force waveforms onto a net, at an exact
  edge or nanosecond.
- **Deterministic**: the same seed and firmware give the same run, cycle for cycle.

Your tests run wherever you run pytest (your laptop, your CI). Only the
simulation runs in the cloud. Stops and faults happen inside the simulator on
the exact cycle, so network latency never changes what the firmware sees.

## Install

**One file, nothing else needed** (Linux, Windows, macOS): download
`sim86-<os>-<arch>` from the releases page, make it executable, and run it.
It includes everything, test runner too.

**Or with Python:** `pip install "sim86[test]"` (the CLI plus pytest and
pytest-xdist).

```
sim86 login            # or: export SIM86_API_KEY=sim86_live_…
```

Create an API key at **app.sim86.com → Cloud → API keys**.

## Quick start

```
sim86 init             # starter board.json + tests/test_board.py (+ editor schema)
sim86 info board.json  # what the board is: parts, firmware, nets, what tests can do
sim86 check board.json # catches wrong pins, types, settings, firmware formats
sim86 run board.json   # run it, stream serial output
```

```
▸ starting my-board on the Simulator86 cloud (3 parts, 1 chip, up to 10s simulated)…
▸ run 0193f2c4-…
▸ https://app.sim86.com/cloud/0193f2c4-…
[     0.412 ms] mcu:uart0          ESP-ROM:esp32c3-api1-20210207
[   812.035 ms] mcu:uart0          ready
```

Useful flags:

| Flag | |
|---|---|
| `--expect "ready"` | exit 0 as soon as the text is printed, 1 if it never is (good for shell CI) |
| `--duration 20s` | simulated time to run |
| `--firmware motor=out/m.elf` | swap one chip's image |
| `--scenario faults.json` | run with a fault plan ([below](#planned-faults-scenarios)) |
| `--seed 42` | reproduce a run exactly |
| `--no-open` | don't open the live page (it opens by default at a terminal) |
| `--json` | one JSON object per output line, for scripts and agents |

## Drive a running board from the shell

For agents and quick experiments: start a board, then act on it one command
at a time. Every command prints one JSON object and exits non-zero on
failure. `last` is the run you started most recently.

```
sim86 start board.json                        {"run": "01a1…", "url": "…/live/01a1…"}
sim86 events last &                           everything that happens, one JSON line each
sim86 wait last "thermostat ready" --since-start
sim86 input last temp temperature=72          set what a sensor senses
sim86 wait last "ALARM" --ms 3000             run until printed (simulated ms)
sim86 state last alarm                        {"state": {"intensity": 100}}
sim86 press last mute --hold 300ms            buttons
sim86 until last --edge temp.SCL --falling --nth 3     pause on the exact edge
sim86 fault last short temp.SDA gnd           {"fault": 0}
sim86 wait last "sensor error" --ms 500
sim86 fault last clear                        clears what you applied
sim86 read last mcu GPIO.IN                   chip registers
sim86 measure last temp.SCL --over 200ms      edges and volts on a net
sim86 stop last
```

`wait` reads output in order: it looks at what was printed after your last
action (or the last line it matched), so nothing printed between two
commands is missed. `--since-start` searches everything.

**Step mode (`sim86 start board.json --step`)**: the board only moves inside
`wait`, `advance` and `until`, and stays paused between commands. Timing is
then exact however slow you (or your agent) are: a short applied for
`advance last 20ms` lasts exactly 20 ms. Without `--step` the board runs in
real time between commands, like real hardware on a bench. In step mode,
`wait` moves in 50 ms slices and stops within one slice of the match.

A session runs up to 10 minutes of simulated time by default (`--duration`);
the board file's `limits` only apply to `sim86 run` and tests.

Sensors behave like real parts: a temperature set with `input` reaches the
firmware gradually (thermal lag), and a sensor's first reading after
power-up can be 0 until its first conversion finishes.

`sim86 events` prints history first, then live events until the run ends:
`serial` (firmware output), `action` (what a program did to the run),
`note`, `plan` (scheduled faults), `paused`/`running`, `state` (with
`--state`: LEDs, sensors, displays), `ended`. Filter with `--type`, `--part`,
`--grep`; stop with `--until-text` or `--wall SECONDS`.

Also: `status`, `pause`, `resume`, `advance last 5ms`, `until last --at 2s`,
`event last PART ACTION`, `write last mcu REG VALUE`, `inside last PART`,
`note last "…"`.

## Test it with pytest

```
sim86 test -v              # runs your tests/ — works with the single-file download
sim86 test -n 4 -k sda     # any pytest option: parallel, select, --junitxml=results.xml
```

`sim86 test` is pytest with the sim86 plugin loaded; the downloadable
executable carries pytest and pytest-xdist inside, so no Python is needed.
With a pip install, plain `pytest` works too (the plugin registers itself).
Your test files can import `pytest` and `sim86`, plus anything else when you
run them from your own Python environment.

Point it at your board in `pytest.ini`:

```ini
[pytest]
sim86_board = board.json
```

Each test that takes `board` gets its own fresh run of that file. The run
stops when the test ends.

```python
def test_boots(board):
    board["mcu"].serial.wait_for("ready", ms=2000)
```

`wait_for` runs the board until the text appears, for at most that much
**simulated** time. If it times out, the board is left paused exactly at the
deadline and the test fails, showing the last lines printed.

When a test fails, the report includes the run link, the faults still
applied and the last 40 lines every chip printed:

```
---------------------------- sim86 ----------------------------
run: https://app.sim86.com/cloud/0193f2c4-…
faults still applied: short sensor.SDA to gnd
last output:
  [  1203.551 ms] mcu:uart0          i2c timeout, retrying
```

### What a test can do

```python
board["mcu"].serial.wait_for("text", ms=500)   # run until printed (simulated time)
board["mcu"].serial.lines                      # everything it printed: .t (ms) .source .line
board.serial.text                              # the whole board's output

board.until(edge="sensor.SCL", kind="falling", nth=3)  # pause on the exact edge (counted from now)
board.until(at="250ms")                        # pause at a simulated time
board.advance("5ms")                           # run exactly 5 ms more, then pause
board.resume()                                 # keep running
board.time_ms                                  # current simulated time

board["mcu"].read("I2C0.SR")                   # chip register, exact while paused
board["mcu"].read("I2C0.SR")["BUS_BUSY"]       # one bit field
board["mcu"].read("cpu.pc", "mem[0x3fc80000:16]")
board["mcu"].write("GPIO.OUT", 0)

board["btn"].press(hold="200ms")               # buttons
board["sensor"].set_input("temperature", 85)   # what a sensor senses
board["imu"].set_input("acceleration", [0, 0, 9.8])
board["sensor"].internals()                    # a part's registers, state, recent writes
```

Register names are the vendor's own (from its SVD). Search them with
`sim86 registers XiaoESP32C3 "i2c0 sr"`.

### Volts, edges and part state

```python
board["alarm"].state                          # what a part shows: {"intensity": 100}, currents, …
m = board.measure("temp.SDA", over="5ms")     # a net over the last 5 ms of simulated time
m.min, m.max, m.mean, m.last                  # volts (analog nets: the solver's exact values)
len(m.rising), m.rising[0].rise_ns            # edges; 10–90 % rise time and delay on analog nets
board.volts("r1.2")                           # a net's voltage right now
board.watch("temp.SDA", "temp.SCL")           # start recording nets before something happens
```

A net is named by any pin on it. Volts and rise times come from the analog
layer: nets with resistors, capacitors, supplies and so on. A purely digital
net reports its edges and the rail volts each edge drove to.

In the board file, part values can be written like on a schematic:
`"ohms": "4k7"`, `"farads": "100n"`, `"volts": "3V3"`.

### Radio (Wi-Fi, BLE)

```python
board.radio.loss("mcu", "ap", 120)            # out of range (40 ≈ same desk, 90 far)
board.radio.jam(channel=6, dbm=20)            # interferer on Wi-Fi channel 6 (22 MHz wide)
board.radio.jam(channel=6, dbm=30, mhz=90)    # the whole 2.4 GHz band
board.radio.restore()                         # as the board file set it up
```

See `examples/wifi` and `examples/ble`.

### Choosing the board per test

```python
import pytest

@pytest.mark.board("boards/two-node.json", duration="20s", seed=7)
def test_two_nodes(board): ...

@pytest.mark.board(firmware={"motor": "out/motor-debug.elf"})
def test_debug_build(board): ...
```

### Watch tests live

```
sim86 test --open -k sda
```

Each test's run opens in the browser: the board live, a banner with the
test's name and result, and an **Activity** feed of every step the test takes
(paused on an edge, shorted a wire, set an input), stamped with simulated
time. Any program driving a run shows up the same way. Label your own steps
with `board.note("heating to 80 °C")`. `--sim86-linger 10` keeps each run
going for 10 s after its test.

`sim86 run` opens the same live page by default when you run it in a
terminal. Pass `--no-open` to skip it; it never opens under CI or `--json`.

## Fault injection

Pause on the exact moment, break something, then watch how the firmware
recovers:

```python
def test_sensor_survives_a_shorted_sda(board):
    mcu = board["mcu"]
    mcu.serial.wait_for("ready", ms=2000)

    board.until(edge="sensor.SCL", kind="falling", nth=3)  # mid-transaction
    fault = board.short("sensor.SDA", "gnd")               # SDA stuck low
    board.advance("5ms")
    board.clear(fault)

    mcu.serial.wait_for("sensor ok", ms=1000)              # it must recover
```

| Fault | |
|---|---|
| `board.short(pin, "gnd" \| "vcc")` | tie a net to a rail (stuck line) |
| `board.open(a, b)` | break the wire between two pins |
| `board.bridge(a, b)` | join two nets, like a solder bridge |
| `board.drive(pin, [[0, 0], [2000, 1]], repeat="4us")` | force a waveform onto a net: `[time_ns, level]` steps |
| `board.clear(fault)` / `board.clear()` | remove one fault / all of them |

Faults apply at the board's current simulated time. While it is paused,
that's the exact instant it paused at.

### Sweeps

A sweep is plain pytest. Each case is its own cloud run, so they
parallelise (`pip install pytest-xdist`, then `pytest -n 8`):

```python
import pytest

@pytest.mark.parametrize("pin", ["sensor.SDA", "sensor.SCL"])
@pytest.mark.parametrize("to", ["gnd", "vcc"])
@pytest.mark.parametrize("nth", [1, 9, 40])
def test_stuck_bus(board, pin, to, nth):
    board["mcu"].serial.wait_for("ready", ms=2000)
    board.until(edge="sensor.SCL", kind="falling", nth=nth)
    fault = board.short(pin, to)
    board.advance("20ms")
    board.clear(fault)
    board["mcu"].serial.wait_for("sensor ok", ms=2000)
```

### Planned faults (scenarios)

For long runs, describe the faults up front. The simulator then runs the
whole plan by itself, at full speed:

```json
{
  "name": "flaky bus, then overheat",
  "events": [
    { "on": { "wire": "sensor.SCL", "edge": "falling", "count": 30 },
      "bridge": { "wires": ["sensor.SDA", "mcu.GND"], "duration": "5ms" } },
    { "at": "2s", "env": { "part": "sensor", "input": "temperature", "from": 25, "to": 85, "over": "5s" } },
    { "at": "8s", "env": { "part": "btn", "action": "pressed", "hold": "200ms", "release": "released" } }
  ]
}
```

```
sim86 run board.json --scenario scenarios/flaky.json
```
```python
@pytest.mark.board(scenario="scenarios/flaky.json", duration="15s")
def test_overheat_alarm(board):
    board["mcu"].serial.wait_for("ALARM", ms=10_000)
```

`on` edges count from the start of the run. Times are `"250us"`, `"5ms"`,
`"2s"`.

## CI

```yaml
# .github/workflows/firmware.yml
jobs:
  sim:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: ./build.sh                     # your firmware build
      - uses: actions/setup-python@v5
        with: { python-version: "3.12" }
      - run: pip install "sim86[test]"
      - run: sim86 test -n 8 --junitxml=results.xml
        env:
          SIM86_API_KEY: ${{ secrets.SIM86_API_KEY }}
```

Every test result carries its run link (`sim86_run` in the JUnit
properties).

## Other commands

```
sim86 parts [word] [--kind sensor]     search the part catalog
sim86 parts --show MCP9808             pins, I2C address, settings, sensor inputs
sim86 registers <chip> [words]         search a chip's registers and fields
sim86 runs                             your recent runs
sim86 logs <run>                       a run's output
sim86 open <run>                       the run's page in the browser
sim86 stop <run>                       stop a run
```

## Feedback (people and agents)

Found something the simulator gets wrong, or something missing? Send it
straight to the team:

```
sim86 feedback --kind wrong_simulation \
  --summary "BMP280 returns 0x00 for chip id after a soft reset" \
  --steps "write 0xB6 to 0xE0, read 0xD0" --expected "0x58" --actual "0x00" \
  --board board.json --run 0193f2c4-…
```

Agents can pipe a JSON report:

```
echo '{"kind":"bug","summary":"…","goal":"…","steps":"…","expected":"…","actual":"…",
       "reproducible":"always","impact":"blocked","target":{"chip":"ESP32-C3","part":"BMP280"}}' \
  | sim86 feedback --json -
```

`kind` is one of `bug`, `wrong_simulation`, `missing`, `confusing`, `idea`. It's for problems with
Simulator86 itself, not with your firmware.

## Python API

The fixture is a thin layer over the API, which also works outside pytest:

```python
from sim86 import load_board, Run

board = load_board("board.json")
with Run.start(board, duration="10s") as run:      # stops the run on exit
    run["mcu"].serial.wait_for("ready", ms=2000)
    print(run.url)
```

The only setting is your key: `SIM86_API_KEY`, or `sim86 login`, which saves
it to `~/.config/sim86/config.json`.
