# matterlab_relays

`matterlab_relays` provides drivers for the relay boards used in the Matter Lab. It includes relay-specific implementations for several serial and Modbus-controlled boards, along with a small shared base interface for switching channels on and off.

## Supported Devices

- `Relay`: shared abstract base class
- `R421B16Relay`
- `JYdaqRelay`
- `CE221ARelay`

## Installation

Install the package:

```bash
pip install matterlab_relays
```

For development:

```bash
pip install -e .[dev]
```

The package depends on:

- `matterlab_serial_device`
- `modbus_tk`

## Quick Start

Example with an R421B16 relay:

```python
from matterlab_relays import R421B16Relay

relay = R421B16Relay(com_port="COM5", address=1, channel=1)
print("Current state:", relay.on)
relay.on = True
relay.on = False
```

## Core API

The shared `Relay` interface exposes:

- `on`

Concrete device classes add protocol-specific helpers:

- `R421B16Relay`: `_generate_query_command(...)`, `_generate_execute_command(...)`, `query_relay(...)`, `set_relay(...)`
- `JYdaqRelay`: `_add_rtu_master()`, `set_multiple_relays(...)`, `query_multiple_relays(...)`
- `CE221ARelay`: cached `on` state with `_generate_execution_command(...)`

## Testing

### Simulation Tests

Simulation tests are the default validation layer and are safe for CI.

One-click run:

```bash
python examples/test_sim.py
```

Direct pytest run:

```bash
pytest tests/test_base_relay.py tests/test_r421b16_sim.py tests/test_jydaq_sim.py tests/test_ce221a_sim.py
```

### Hardware Tests

Hardware tests are opt-in because real relay hardware may not be connected in every environment.

Available hardware test files:

- `tests/test_r421b16_real.py`
- `tests/test_jydaq_real.py`
- `tests/test_ce221a_real.py`

They are marked with `@pytest.mark.real` and are skipped unless `--run-real` is supplied.

Examples:

```bash
pytest tests/test_r421b16_real.py --run-real --com-port COM5 --address 1 --channel 1
pytest tests/test_jydaq_real.py --run-real --com-port COM5 --address 1 --channel 1
pytest tests/test_ce221a_real.py --run-real --com-port COM5 --channel 1
```

You can also provide hardware configuration through environment variables:

- `RELAY_COM_PORT`
- `RELAY_ADDRESS`
- `RELAY_CHANNEL`

## Examples

The `examples/` directory contains the recommended entry points:

- `examples/test_sim.py`: one-click simulation-only test runner
- `examples/real_devices.py`: readable examples for all supported relay drivers
- `examples/README.md`: short guide to the examples directory

## Development

Useful commands:

```bash
pytest
ruff check .
ruff format .
```

The default pytest configuration includes retries, timeouts, coverage output, and uses `src` as the import root for local development.

## Package Layout

```text
src/matterlab_relays/
  base_relay.py
  cer221a_relay.py
  jydao_relay.py
  r421b16_relay.py
tests/
examples/
```

## License

This project is distributed under the MIT License. See `LICENSE` for details.
