> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Hardware scripts

> Create, run, and reuse Python checks that coordinate firmware, serial ports, and lab instruments.

Use a hardware script for a repeatable check, a sequence of instrument actions, or a long measurement. Ask Inlay to create the Python script under `.inlay/hardware/` and to define what counts as success.

```text theme={"theme":"css-variables"}
Create a boot check that reads UART at 115200 baud for up to 10 seconds and
passes only if it sees READY. Do not reset or flash the target.
```

## A simple UART check

A hardware script is ordinary Python, saved under `.inlay/hardware/`. When Inlay runs it, helpers such as `serial_read` are already defined, so you don't import them. To write one yourself, save this file and replace the port with your board's port:

```python .inlay/hardware/boot_check.py theme={"theme":"css-variables"}
import asyncio
import json

async def main():
    lines = await serial_read(
        "/dev/ttyUSB0",
        timeout_seconds=10,
        baud_rate=115200,
        stop_string="READY",
    )
    ready = any("READY" in line for line in lines)
    print(json.dumps({
        "success": ready,
        "summary": "READY observed" if ready else "READY not observed",
        "data": {"lines": lines},
    }))

asyncio.run(main())
```

The serial helpers take the port and, optionally, the baud rate, which defaults to 115200:

| Helper | What it does |
| - | - |
| `await serial_read(port, timeout_seconds=5.0, baud_rate=115200, stop_string=None)` | Waits for output and returns the lines it received. It returns early when `stop_string` appears. Call it inside an `async` function, as the example does. |
| `serial_read_history(port, baud_rate=115200, only_new=False, last_n_lines=None)` | Returns output that's already captured, without waiting. |
| `serial_send(port, command, baud_rate=115200)` | Sends one command, followed by a line feed. |

Helpers for debuggers and instruments are covered on each tool's page. See [Use instrument helpers](#use-instrument-helpers).

End the script by printing one JSON result with `success` and a short `summary`. Put useful observations in `data`. Print the result on a single line, as `json.dumps` does by default. Inlay reads the last line of output that holds both `success` and `summary`.

| Script ends with | Run result |
| - | - |
| A result with `"success": true`, and a normal exit | Pass, with your summary |
| A result with `"success": false` | Fail, with your summary |
| An uncaught error, a nonzero exit, or a timeout | Fail, even if the result says `success` |
| No result line, and a normal exit | Not asserted. The run completes, but Inlay doesn't report it as a pass because the script checked nothing. |

The same rules apply to a script that runs in the background: a result with `"success": false` ends the background task as failed. When a script is meant to test something, always print the result line as its last output. Leave it out only for capture-only scripts.

Keep captures and results tied to the script and firmware revision that produced them.

## Check a pin

To read hardware state from the debugger, connect with a `gdb.*` helper and read the register. This script attaches through a J-Link and passes when PA0 on an STM32F407 reads high. Replace the device, ELF, register address, and pin with your own:

```python .inlay/hardware/check_pin.py theme={"theme":"css-variables"}
import json

GPIOA_IDR = 0x40020010  # STM32F407 GPIOA input data register
PIN = 0  # PA0

gdb.jlink_connect(
    device="STM32F407VG",
    elf="build/app.elf",
    attach=True,
)
idr = int.from_bytes(gdb.read_memory(GPIOA_IDR, 4), "little")
level = (idr >> PIN) & 1
print(json.dumps({
    "success": level == 1,
    "summary": f"PA{PIN} reads {level}",
    "data": {"GPIOA_IDR": hex(idr)},
}))
```

> [!WARNING]
>
> Without `attach=True`, `gdb.jlink_connect()` and `gdb.openocd_connect()` program the target with the ELF and run to `main`. With it, they load symbols only, and the debugger still halts the target when it connects. See [Choose programming or attachment](/docs/debug-mode/gdb.md#choose-programming-or-attachment) before you connect to a board whose state matters.

Look up the register address for your MCU with [register lookup](/docs/debug-mode/registers.md). The other `gdb.*` helpers are listed in [Script helpers](/docs/debug-mode/gdb.md#script-helpers).

## Run a script

| From | How | Notes |
| - | - | - |
| Chat | Ask Inlay to run the script in Act or Debug mode. | Each run asks for approval, according to your [approval settings](/docs/core-concepts/approvals.md). |
| VS Code | Open the file and select **Run Hardware Script** (▷) in the editor title bar. | See [Run a script from the editor](#run-a-script-from-the-editor). |
| Chat input | Run `/run-script .inlay/hardware/boot_check.py`. The path is relative to the project folder. | See [Run a script from the chat input](#run-a-script-from-the-chat-input). |
| A shell | Run `inlay script boot_check.py` from the project directory. | Asks in the terminal before installing packages. |

The `inlay script` command takes a path relative to `.inlay/hardware/`, such as `boot_check.py` or `cases/i2c-nack/capture_bus.py`.

| Option | Use |
| - | - |
| `--json` | Print the script's JSON result on stdout. Script output moves to stderr. |
| `--profile <json>` | Pass a JSON object to the script as `capture_profile`. Use `@path` to read it from a file. |
| `--timeout <ms>` | Stop the script after this many milliseconds. The default is `60000`. |
| `--any-path` | Run a script stored outside `.inlay/hardware/`. Inlay doesn't check helper usage in those scripts. |

The command prints the script's output as it runs, then the result's `summary`. A script with no result line ends with `Hardware script completed without asserting a result.` The command exits with `0` when the script passes or doesn't assert a result, `1` when it fails, and `2` for a usage error. Press `Ctrl+C` to stop the command. To stop a run that Inlay started from chat, stop the chat response. See [CLI reference](/docs/headless/cli-reference.md#hardware-scripts) for all options.

Run scripts through Inlay when they use its instrument helpers. Running the same file with plain `python` doesn't provide the helpers or their setup.

## Run a script from the editor

1. Open any Python file in the workspace.
2. Select **Run Hardware Script** (▷) in the editor title bar, right-click in the editor and choose it, or run **Inlay: Run Hardware Script** from the Command Palette.
3. In the row that appears at the bottom of the chat, choose:
   * **Run** to execute the script without sending the result to Inlay. When it finishes, **Hand to agent** sends the result if you change your mind.
   * **Run and hand to agent** to execute the script and send the result to Inlay when it finishes.
   * **Cancel** to remove the row without touching hardware.

To repeat a script Inlay ran earlier in the chat, select **↻ Run** on that run's row. It runs the current contents of the file with the same profile and shows the same three choices.

While the script runs, output streams to the row and to the Monitor's **Debug Output** tab. Select **Show output** to bring up the Monitor. To stop the run, select **Stop** on the row or the stop button that replaces ▷ in the title bar.

Limits for editor-started runs:

* Only one editor-started script runs at a time. A second run shows **Another hardware script is already running. Stop it first.**
* If an agent task or another session is using the hardware, the run fails with **Hardware is busy in another workflow.**
* Editor-started runs never install Python packages. If a package is missing, the run fails and tells you to run the script from chat or with `inlay script` in a terminal, where you can approve the install.

## Run a script from the chat input

`/run-script [file]` starts a script yourself from the chat input, without asking Inlay to run it. Its alias is `/run-hardware-script`.

| Client | With a file | Without a file |
| - | - | - |
| VS Code | Shows the same run row as the editor button, with **Run**, **Run and hand to agent**, and **Cancel**. | Uses the Python file in the active editor. If the active editor isn't a Python file, a file picker opens. |
| Terminal UI | Opens the **Hardware Script** panel. Choose **Run** to watch the output there, or **Run and analyze** to hand the result to Inlay when the script finishes. | Opens the **Run hardware script** file picker in `.inlay/hardware/`, or reopens the panel of a script that's already running. |

In the terminal UI panel, press `s` to stop a running script, `a` to hand a finished result to Inlay, `r` to run it again, and `Esc` to hide or close the panel. Only one script started this way runs at a time.

## Supply a capture profile

For settings that change between runs, read them from `capture_profile` in the script and keep the values in a companion file named after the script, such as `boot_check.profile.json`.

| Started from | Profile used |
| - | - |
| `inlay script` | The `--profile` value, otherwise the companion file. A `@path` value is read relative to the current directory. |
| VS Code editor | The companion file. The run row shows **Uses boot\_check.profile.json for capture\_profile.** |
| **↻ Run** on an earlier chat run | The profile from the run it repeats. |
| Chat | The profile Inlay passes with that run. Chat runs don't read the companion file, so name the values in your request or ask Inlay to use the file. |
| No profile | An empty dict. Use defaults for optional settings. |

Override the profile and timeout at launch:

```bash theme={"theme":"css-variables"}
inlay script boot_check.py --profile @profiles/bench.json --timeout 120000
```

The profile must contain a JSON object, and the script must read the fields you supply. If the script needs Python packages that aren't installed yet, run it once from chat or an interactive terminal so you can approve the install.

## Use instrument helpers

Choose the tool first, then use its guide for dependencies, channel numbering, and supported operations:

| For | Helpers | Documented in |
| - | - | - |
| Debuggers | `gdb.*` | [Script helpers](/docs/debug-mode/gdb.md#script-helpers) lists the shared helpers. For connection options, see [J-Link](/docs/debug-mode/jlink.md#script-a-j-link-connection), [OpenOCD](/docs/debug-mode/openocd.md#script-the-connection), [TI CCS](/docs/debug-mode/ccs.md#script-the-connection), and [XMOS xgdb](/docs/debug-mode/xmos-debugging.md#use-a-hardware-script). |
| AURIX TriCore | `aurix.*` | [Debug TriCore over TCF](/docs/debug-mode/aurix.md#debug-tricore-over-tcf) |
| UART | `serial_read()`, `serial_read_history()`, `serial_send()` | [A simple UART check](#a-simple-uart-check) |
| RTT | `rtt_read()`, `rtt_read_history()`, `rtt_send()` | They take the same arguments as the serial helpers, without the port and baud rate, and use RTT channel 0. See [RTT](/docs/debug-mode/rtt.md) for the connection. |
| Logic analyzers | `la_*` | [Saleae](/docs/debug-mode/saleae.md#in-a-hardware-script), [Digilent](/docs/debug-mode/digilent.md), [DSLogic](/docs/debug-mode/dslogic.md#use-dslogic-in-a-hardware-script), and [PicoScope MSO inputs](/docs/debug-mode/picoscope.md#use-mso-inputs) |
| Oscilloscopes | `scope_*` | [SCPI oscilloscopes](/docs/debug-mode/scpi-oscilloscopes.md#connect-from-a-hardware-script), [Siglent](/docs/debug-mode/siglent.md), and [PicoScope](/docs/debug-mode/picoscope.md) |
| Spectrum analyzer | `spectrum_*` | [Script a sweep](/docs/debug-mode/spectrum-analyzer.md#script-a-sweep) |
| Power | `ppk2_*`, `joulescope_*` | [PPK2](/docs/debug-mode/ppk2.md#use-the-ppk2-in-a-hardware-script) and [Joulescope](/docs/debug-mode/joulescope.md#use-the-joulescope-in-a-hardware-script) |
| Trace and coverage | The `jtrace` package | [Script a custom capture](/docs/debug-mode/jtrace.md#script-a-custom-capture) |
| XMOS simulator | `xsim.*` | [XMOS xsim](/docs/debug-mode/xsim.md) |
| Bluetooth LE | `ble_*` | [Bluetooth](/docs/debug-mode/bluetooth.md#repeat-a-test) |
| Network captures | | [Analyze captures in a script](/docs/debug-mode/packets.md#analyze-captures-in-a-script) |

ITM/SWO, xSCOPE, and CAN have no script helpers of their own. Ask Inlay to read them, as their guides describe: [ITM/SWO](/docs/debug-mode/itm-swo.md), [xSCOPE](/docs/debug-mode/xscope.md), and [CAN](/docs/debug-mode/can.md).

Several instruments share `la_*` or `scope_*` helper names, but triggers, decoders, capture modes, and output controls still depend on the tool. A script written for one instrument may need changes for another.

Use `run_tool(["probe-rs", "list"])` in a script when a command must run on the computer the hardware is attached to, including a [bench](/docs/integrations/benches.md). Name the target explicitly before any programming or control action.

To show script measurements live, ask Inlay to publish them to a [dashboard](/docs/core-concepts/dashboards.md). This needs no firmware change.

For generated waveforms, supplies, BLE connections, and similar resources, include cleanup that runs even when a test fails.

## Watch a live capture preview

While a script captures from an instrument, the Monitor's **Power**, **Logic**, or **Oscilloscope** tab shows a live preview. If no tab of that kind is open, the Monitor opens one. A chip with the capture's name and a **Live** or **Ended** pill replace the tab's usual setup controls.

| Capture | Preview |
| - | - |
| `joulescope_measure` and PPK2 captures | Current, and voltage from a Joulescope, updated five times per second. The view keeps the latest 4,000 points. |
| Logic captures started with `la_*` helpers | Capture progress. DSLogic also shows waveforms while acquiring; other analyzers show them once the capture is exported. |

The preview doesn't open a second connection to the instrument, and closing it doesn't stop the script. Use the script's stop control to end acquisition. A finished preview stays visible until you select **New capture**.

Scripts for other instruments can publish their own preview points:

```python theme={"theme":"css-variables"}
inlay_publish_capture_preview(
    capture_id="spi-test-1",  # Use a new ID for every acquisition.
    name="SPI capture",
    kind="logic",  # power, logic, or oscilloscope
    points=[
        {"channel": "CLK", "timestamp": 0, "value": 0},
        {"channel": "CLK", "timestamp": 1, "value": 1},
    ],
    sample_count=2,
    elapsed_sec=0.001,
)
```

Timestamps are milliseconds from the start of acquisition. Send bounded batches, and pass `state="stopped"` with the final update. A preview never saves a capture; use the instrument's normal capture helper for that.

## Keep a hardware case

For an investigation that needs several scripts, keep related files together in a case folder under `.inlay/hardware/cases/`. Name the folder with lowercase letters, digits, and hyphens, such as `i2c-nack`:

```text theme={"theme":"css-variables"}
.inlay/hardware/cases/i2c-nack/
  CASE.md
  capture_bus.py
  inspect_pins.py
```

`CASE.md` is the record of one bug. Ask Inlay to keep its status (`open`, `resolved`, or `abandoned`), the symptom, hypotheses with verdicts, findings, the next check, and paths to evidence up to date. Inlay reuses an existing case for the same bug instead of starting a new one.

Update existing scripts when the test changes, so it stays clear which version produced a result. Run a case script from a shell with its path, such as `inlay script cases/i2c-nack/capture_bus.py`.

## Run longer checks

Ask for a background run when you need a soak test or a long capture. Inlay starts the script and returns to the chat while it runs, and reports the result when the script exits. The board stays reserved for that chat until then.

A background run isn't limited by the script timeout, but it stops after 24 hours. To check on it or stop it, ask Inlay, or use the chat's background tasks: in VS Code they appear above the chat input, and in the terminal UI, `/background` lists them.

An active hardware task can make another session wait. Check `/hardware-queue` before starting a conflicting operation, and release the equipment when the run finishes. If a session that no longer needs the board still holds it, `/hardware-force-release` frees it after you confirm; that session's hardware work is interrupted.

## Troubleshoot

| Symptom | Check |
| - | - |
| `"tools/probe.py" is not inside .inlay/hardware` | `inlay script` takes a path relative to `.inlay/hardware/`. Run it from the project folder, or add `--any-path` for a script stored elsewhere. |
| The run ends with `Script not found` | The file isn't under `.inlay/hardware/` in the project you ran from. Check the name and the folder. |
| `NameError` for a helper such as `serial_read` | The script ran with plain `python`. Run it through Inlay, which defines the helpers. |
| The run completes, but it isn't reported as a pass | The script printed no result line. Print one JSON line with `success` and `summary` as its last output. |
| The run fails after 60 seconds | The script hit the default timeout of 60,000 ms. Pass `--timeout` to `inlay script`, ask Inlay to run it with a longer timeout, or ask for a [background run](#run-longer-checks). |
| The run stops at a missing Python package | Editor-started runs and runs without an interactive terminal can't install packages. Run the script once from chat or with `inlay script` in a terminal, and approve the install. |
| **Another hardware script is already running. Stop it first.** | Only one editor-started script runs at a time. Stop it from its row, or wait for it to finish. |
| **Hardware is busy in another workflow.** | Inlay or another session is using the hardware. Run `/hardware-queue` to see which session holds it. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.