Metadata-Version: 2.5
Name: virtrig
Version: 0.4.0rc1
Summary: Open-source hardware simulation and integration testing platform. Test real protocols without physical devices.
Project-URL: Homepage, https://github.com/WIKKIwk/VirtRig
Project-URL: Repository, https://github.com/WIKKIwk/VirtRig
Project-URL: Documentation, https://github.com/WIKKIwk/VirtRig/tree/main/docs
Project-URL: Issues, https://github.com/WIKKIwk/VirtRig/issues
Project-URL: Changelog, https://github.com/WIKKIwk/VirtRig/blob/main/CHANGELOG.md
Author: VirtRig Contributors
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: asyncio,fault-injection,hardware-simulation,hardware-testing,industrial-automation,integration-testing,modbus,mt-sics,simulator,virtual-devices
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Framework :: Pytest
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: System :: Hardware
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic<3,>=2.7
Requires-Dist: pymodbus<4,>=3.7
Requires-Dist: pyyaml<7,>=6.0
Description-Content-Type: text/markdown

# VirtRig

**Real protocols. Virtual devices.**

[![CI](https://github.com/WIKKIwk/VirtRig/actions/workflows/ci.yml/badge.svg)](https://github.com/WIKKIwk/VirtRig/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/virtrig?include_prereleases)](https://pypi.org/project/virtrig/)
[![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%20%7C%203.12%20%7C%203.13-blue.svg)](pyproject.toml)

VirtRig is an open-source, headless hardware simulation and integration testing platform for Python. Define stateful virtual PLCs, weighing scales, and custom devices in YAML or Python, expose them over **real local TCP sockets** (all platforms) or **POSIX pseudo-terminals** (Linux/macOS), record/redact traffic as standard JSON Lines, and inject deterministic transport- and protocol-layer failures in local development and CI—without physical hardware.

---

## Why VirtRig?

Testing software that communicates with physical hardware usually breaks down in one of two ways:
- **Physical test benches** bottleneck parallel CI pipelines, require fragile cabling, and make rare failure modes (abrupt disconnects, partial frames, connection refusals, CRC corruption, unstable scale readings) nearly impossible to reproduce on demand.
- **In-process mocks or Layer-4 proxies** either hide real wire-framing bugs or cannot simulate stateful devices and protocol-specific errors.

VirtRig runs stateful virtual devices directly on `127.0.0.1:<port>` (or `/dev/pts/N` / `/dev/ttysNNN` on POSIX), so unmodified client applications in **any language** (Python, Go, C#, Java, C++, Node.js) connect over real OS endpoints and experience reproducible failures and recoveries.

---

## Installation

### From PyPI (`pip` or `uv`)

```bash
pip install --pre virtrig
# or pin the current pre-release:
pip install "virtrig==0.3.0rc1"
```

### From GitHub (latest `main`)

```bash
pip install "git+https://github.com/WIKKIwk/VirtRig.git"
```

### From a local checkout (development)

```bash
git clone https://github.com/WIKKIwk/VirtRig.git
cd VirtRig
uv sync --dev
```

### Docker

```bash
docker build -t virtrig:local .
docker run --rm -p 9100:9100 virtrig:local run examples/profiles/generic_tcp.yaml
```

*(Verified in GitHub Actions `Docker Build & Container Smoke Test` using non-root `python:3.12-slim`.)*

---

## Quick Start

### 1. Scaffold & Start a Virtual Device from the CLI

Works anywhere after `pip install` — no repository checkout required:

```bash
# Check installed version and available components
virtrig --version
virtrig plugins

# Scaffold a starter YAML device profile (generic_tcp, modbus_tcp, or mt_sics)
virtrig init generic_tcp -o my_sensor.yaml
virtrig validate my_sensor.yaml

# Run the virtual device and optionally record redacted JSONL traffic
virtrig run my_sensor.yaml --record session.jsonl --redact "TOKEN=[A-Za-z0-9]+"
```

### 2. Minimal Python SDK Example (Sync + Real TCP + Fault Recovery)

See [`examples/quickstart/minimal_sdk.py`](examples/quickstart/minimal_sdk.py):

```python
import socket
from virtrig import FaultRuleConfig, SyncSimulationHarness

with SyncSimulationHarness("my_sensor.yaml") as sim:
    host, port = sim.get_address("temp-sensor")

    with socket.create_connection((host, port), timeout=2.0) as sock:
        sock.sendall(b"READ?\r\n")
        print(sock.recv(128).decode().strip())  # TEMP=22.5 STATUS=OK READS=1

    # Close the OS listener -> client observes genuine ConnectionRefusedError
    sim.inject_fault(
        FaultRuleConfig(id="outage", device_id="temp-sensor", kind="connection_refused")
    )
    # Remove the fault -> listener rebinds the exact same port
    sim.remove_fault("outage")
```

### 3. Automatic `pytest` Integration

Installing VirtRig automatically registers its `pytest11` plugin with ready-to-use fixtures (`virtrig_sync`, `virtrig_harness`, `virtrig_modbus_plc`, `virtrig_mt_sics_scale`), working cleanly under both plain `pytest` and `pytest-asyncio` (`Mode.STRICT` and `Mode.AUTO`):

```python
import socket


def test_sensor_profile(virtrig_sync):
    sim = virtrig_sync("my_sensor.yaml")
    host, port = sim.get_address("temp-sensor")

    with socket.create_connection((host, port), timeout=2.0) as sock:
        sock.sendall(b"PING\r\n")
        assert sock.recv(64) == b"PONG\r\n"
```

---

## Supported Protocols & Transports

### Protocols

| Protocol | Adapter ID | Default Framing | Verified Capabilities | Specification & Exclusions |
| :--- | :--- | :--- | :--- | :--- |
| **Generic TCP** | `generic_tcp` | `delimiter` (`\n`) | Text & binary rules, regex state capture, greetings, `delimiter` / `length_prefix` / `fixed_length` / `raw` framers | [`docs/protocols/GENERIC_TCP.md`](docs/protocols/GENERIC_TCP.md) |
| **Modbus TCP** | `modbus_tcp` | `modbus_mbap` | Coils, Discrete Inputs, Input/Holding Registers, FC `0x01`–`0x06`, `0x0F`, `0x10`, typed registers (`INT16`–`FLOAT64`, `STRING`) with `ABCD`/`CDAB`/`BADC`/`DCBA` orders (`pymodbus` codecs), standard exceptions (`0x01`–`0x04`, `0x06`, `0x0B`), unit IDs, read-only maps | [`docs/protocols/MODBUS_TCP.md`](docs/protocols/MODBUS_TCP.md) |
| **Modbus RTU** | `modbus_rtu` | `modbus_rtu` | Verified Modbus subset (FC `0x01`–`0x06`, `0x0F`, `0x10`, typed registers, standard exceptions `0x01`–`0x04`/`0x06`/`0x0B`) over RTU framing with CRC-16 (`pymodbus.framer.FramerRTU`), silent discard on CRC mismatch; works over **TCP (all platforms)** and **POSIX PTY (Linux/macOS)** | [`docs/protocols/MODBUS_RTU_AND_SERIAL.md`](docs/protocols/MODBUS_RTU_AND_SERIAL.md) |
| **MT-SICS Scale** | `mt_sics` | `delimiter` (`\r\n`) | Level 0 & Level 1 (`I0`–`I4`, `S`, `SI`, continuous `SIR`, `Z`, `ZI`, `T`, `TI`, `TA`, `TAC`, `@`, `ES`/`ET`/`EL`), 10-char right-aligned weights, gross/net/tare/zero, overload/underload | [`docs/protocols/MT_SICS.md`](docs/protocols/MT_SICS.md) |
| **Bounded Replay** | `replay` | `raw` / `modbus_mbap` | Replays recorded `.jsonl` `(request, response)` traces (`exact_hex` / `sequential`), optional Modbus TCP Transaction ID echoing (`modbus_mbap_echo_tid`) | [`docs/TRAFFIC_RECORDING_AND_REPLAY.md`](docs/TRAFFIC_RECORDING_AND_REPLAY.md) |

### Transports & Honest Platform Boundaries

| Transport | Type ID | Platforms | Notes & Explicit Boundaries |
| :--- | :--- | :--- | :--- |
| **Local TCP** | `tcp` | Linux, macOS, Windows | Real OS loopback sockets (`127.0.0.1:<port>`), ephemeral `port: 0`, OS-level `connection_refused` |
| **POSIX PTY** | `pty` | Linux, macOS only | Stdlib `pty.openpty()` + raw mode + optional symlink; **not supported on Windows** (WHQL kernel driver signing constraint) and **does not emulate electrical RS-232/RS-485 physics** (baud timing, parity errors, `t3.5` silence). See [`docs/research/UNSOLVED_PROBLEMS.md`](docs/research/UNSOLVED_PROBLEMS.md). |

> **Explicitly out of scope:** Windows virtual COM ports (`COMx`), electrical serial/RS-485 physics, UDP, TLS/mTLS, USB, Bluetooth, RFID, OPC UA, Modbus ASCII, Modbus file/FIFO/MEI codes, MT-SICS Level 2/3 vendor extensions, and graphical UI.

---

## Fault Injection, Traffic Recording & Multi-Device Demo

VirtRig distinguishes **transport-layer**, **protocol-layer**, and **device-state** faults—all reproducible via an explicit RNG `seed` and injectable `Clock`:

- **Transport layer:** `delay` (fixed + seeded jitter), `timeout`, `drop_response`, `disconnect` (`before_response` / `after_response`), `partial_response` (chunked or truncated), `unavailable` (post-accept abort -> `ConnectionResetError`/EOF), `connection_refused` (OS listener closed -> genuine `ConnectionRefusedError` with same-port recovery).
- **Protocol layer:** `malformed_payload` (seeded byte corruption, truncation, raw replace), `protocol_error` (Modbus `ExceptionResponse`, MT-SICS `ET`/`EL`).
- **Device layer:** `state_change` (atomic state mutation on trigger).
- **Observability & Simulated-Device Recording:** Bounded JSON Lines (`.jsonl`) recording of simulated-device traffic (`TrafficRecorder` / `--record`, with `max_records` and `max_file_bytes` limits) and configurable regex/hex redaction (`RedactionRule` / `--redact`) across recorded frame payloads and event metadata. *(Not a physical-device MITM TCP proxy; see [`docs/TRAFFIC_RECORDING_AND_REPLAY.md`](docs/TRAFFIC_RECORDING_AND_REPLAY.md) for redaction and replay boundaries.)*

Run the complete multi-device factory station example (independent controller with **zero VirtRig imports** talking to a Modbus TCP PLC, MT-SICS weighing scale, and Generic TCP label printer through real failures and recovery):

```bash
uv run python examples/factory_station/run_station.py
```

---

## Architecture Overview

```text
Client App (Python / Go / C# / Java / C++ / Node.js)
        │  Real OS TCP socket (127.0.0.1:<port>) or POSIX PTY (/dev/pts/N)
        ▼
  Transport (tcp / pty) ──► FrameCodec (delimiter / length_prefix / fixed / mbap / rtu / raw)
                                    │
                                    ▼
                           FaultInjectionEngine (seeded RNG + Clock)
                                    │
                                    ▼
                           ProtocolAdapter (generic_tcp / modbus_tcp / modbus_rtu / mt_sics / replay / plugin)
                                    │
                                    ▼
                           DeviceStateStore ──► EventBus ──► TrafficRecorder (.jsonl) & ScenarioEngine
```

See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) and [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) (100 concurrent mixed devices start in `~28.6 ms` using `~2.7 MiB` Python heap on macOS arm64).

---

## Verified Compatibility Matrix

| Platform | Python 3.11 | Python 3.12 | Python 3.13 | Verification Source |
| :--- | :---: | :---: | :---: | :--- |
| **Ubuntu Linux** | Passing | Passing | Passing | GitHub Actions CI |
| **macOS** | Passing | Passing | Passing | GitHub Actions CI + Local (`3.11`, `3.12`) |
| **Windows** | Passing | Passing | Passing | GitHub Actions CI (`pty` tests cleanly skipped) |
| **Docker (`python:3.12-slim`)** | — | Passing | — | GitHub Actions CI (`docker-smoke-test`) |

---

## Documentation & Contributing

- **Getting started:** [`examples/profiles/`](examples/profiles/), [`examples/quickstart/minimal_sdk.py`](examples/quickstart/minimal_sdk.py), [`examples/factory_station/`](examples/factory_station/)
- **Protocols & Recording:** [`docs/protocols/MODBUS_TCP.md`](docs/protocols/MODBUS_TCP.md), [`docs/protocols/MODBUS_RTU_AND_SERIAL.md`](docs/protocols/MODBUS_RTU_AND_SERIAL.md), [`docs/protocols/MT_SICS.md`](docs/protocols/MT_SICS.md), [`docs/TRAFFIC_RECORDING_AND_REPLAY.md`](docs/TRAFFIC_RECORDING_AND_REPLAY.md)
- **Research & Evidence:** [`docs/audits/PYPI_ACCEPTANCE_REPORT.md`](docs/audits/PYPI_ACCEPTANCE_REPORT.md), [`docs/research/SOLUTION_EVIDENCE_MATRIX.md`](docs/research/SOLUTION_EVIDENCE_MATRIX.md), [`docs/research/UNSOLVED_PROBLEMS.md`](docs/research/UNSOLVED_PROBLEMS.md), [`docs/decisions/MILESTONE_4_DECISIONS.md`](docs/decisions/MILESTONE_4_DECISIONS.md)
- **Write your first adapter:** [`docs/TUTORIAL_FIRST_ADAPTER.md`](docs/TUTORIAL_FIRST_ADAPTER.md) & [`docs/PLUGIN_DEVELOPMENT.md`](docs/PLUGIN_DEVELOPMENT.md)
- **Contributor & release guides:** [`CONTRIBUTING.md`](CONTRIBUTING.md), [`docs/CONTRIBUTING_PROFILES.md`](docs/CONTRIBUTING_PROFILES.md), [`docs/CONTRIBUTION_OPPORTUNITIES.md`](docs/CONTRIBUTION_OPPORTUNITIES.md), [`docs/RELEASING.md`](docs/RELEASING.md), [`SECURITY.md`](SECURITY.md), [`STATUS.md`](STATUS.md)

---

## License

Licensed under the **Apache License, Version 2.0**. See [`LICENSE`](LICENSE) and [`NOTICE`](NOTICE).
