Metadata-Version: 2.5
Name: virtrig
Version: 0.3.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)
[![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 TCP devices in YAML or Python, expose them over **real local TCP sockets**, 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, 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>`, so unmodified client applications in **any language** (Python, Go, C#, Java, C++, Node.js) connect over real sockets and experience reproducible failures and recoveries.

---

## Installation

> **Pre-release note (`v0.3.0rc1`):** VirtRig is not yet published to PyPI. Install directly from GitHub or a local checkout until the first PyPI release is published.

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

```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. Start a Virtual Device from the CLI

```bash
# Validate a profile
virtrig validate examples/profiles/modbus_tcp.yaml

# Run a Generic TCP controller, Modbus TCP PLC, or MT-SICS weighing scale
virtrig run examples/profiles/generic_tcp.yaml
virtrig run examples/profiles/modbus_tcp.yaml
virtrig run examples/profiles/mt_sics_scale.yaml

# Inspect registered protocols, framers, and transports
virtrig plugins
```

### 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("examples/profiles/generic_tcp.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`):

```python
import socket


def test_sensor_profile(virtrig_sync):
    sim = virtrig_sync("examples/profiles/generic_tcp.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

| 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`, standard exceptions (`0x01`–`0x04`, `0x06`, `0x0B`), unit IDs, read-only maps, dynamic state (`pymodbus` codecs) | [`docs/protocols/MODBUS_TCP.md`](docs/protocols/MODBUS_TCP.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) |

> **Explicitly out of scope in `v0.3.0rc1`:** Serial/PTY, UDP, TLS/mTLS, USB, Bluetooth, RFID, OPC UA, Modbus RTU/ASCII, Modbus file/FIFO/MEI codes, MT-SICS Level 2/3 vendor extensions, and graphical UI.

---

## Fault Injection & Multi-Device Reference 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).

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 local TCP socket (127.0.0.1:<port>)
        ▼
  AsyncioTcpTransport ──► FrameCodec ──► FaultInjectionEngine (seeded RNG + Clock)
                                                │
                                                ▼
                                         ProtocolAdapter (generic_tcp / modbus_tcp / mt_sics / plugin)
                                                │
                                                ▼
                                         DeviceStateStore ──► EventBus & 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 |
| **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/)
- **Write your first adapter:** [`docs/TUTORIAL_FIRST_ADAPTER.md`](docs/TUTORIAL_FIRST_ADAPTER.md) & [`docs/PLUGIN_DEVELOPMENT.md`](docs/PLUGIN_DEVELOPMENT.md)
- **Contribute YAML profiles:** [`docs/CONTRIBUTING_PROFILES.md`](docs/CONTRIBUTING_PROFILES.md)
- **Open contribution ideas:** [`docs/CONTRIBUTION_OPPORTUNITIES.md`](docs/CONTRIBUTION_OPPORTUNITIES.md)
- **Contributor & release guides:** [`CONTRIBUTING.md`](CONTRIBUTING.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).
