Metadata-Version: 2.4
Name: juniconnlib-modbus-core
Version: 0.1.0
Summary: A modbus core library for agents with modbus sensors
Author-email: "ICE-1, Forschungszentrum Juelich GmbH" <ice-1-fiware-admin@fz-juelich.de>
Maintainer-email: Hamza Mushtaq <h.mushtaq@fz-juelich.de>
License-Expression: MIT
Project-URL: Homepage, https://jugit.fz-juelich.de/iek-10/public/ict-platform/fiware-applications/juniconnlib-modbus-core
Project-URL: Documentation, https://apps.fz-juelich.de/ice-1/ict-platform/juniconnlib-modbus-core/
Project-URL: Repository, https://jugit.fz-juelich.de/iek-10/public/ict-platform/fiware-applications/juniconnlib-modbus-core
Project-URL: Issues, https://jugit.fz-juelich.de/iek-10/public/ict-platform/fiware-applications/juniconnlib-modbus-core/-/issues
Keywords: FIWARE,ICE-1,ICT Platform,modbus
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: agentlib~=0.8.9
Requires-Dist: filip~=0.7.5
Requires-Dist: pandas~=2.3.3
Requires-Dist: pydantic~=2.8.2
Requires-Dist: pymodbus~=3.14.0
Requires-Dist: juniconnlib-core~=1.3.0
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Provides-Extra: doc
Requires-Dist: sphinx~=8.0.2; extra == "doc"
Requires-Dist: sphinx-versioned-docs~=1.4.0; extra == "doc"
Requires-Dist: sphinx_rtd_theme~=3.0.2; extra == "doc"
Requires-Dist: sphinx-autodoc-typehints~=2.5.0; extra == "doc"
Requires-Dist: sphinxcontrib-napoleon~=0.7; extra == "doc"
Requires-Dist: autodoc_pydantic~=2.2.0; extra == "doc"
Requires-Dist: myst-parser~=4.0.1; extra == "doc"
Provides-Extra: lint
Requires-Dist: isort; extra == "lint"
Requires-Dist: black; extra == "lint"
Requires-Dist: ruff; extra == "lint"
Dynamic: license-file

# Juniconnlib Modbus Core

Modbus Core is a Python library for reading and decoding Modbus registers from devices and forwarding the resulting values as FIWARE-compatible payloads. It is designed to work in agent-based ecosystems using [`agentlib`](https://github.com/RWTH-EBC/AgentLib) and [`juniconnlib-core`](https://jugit.fz-juelich.de/iek-10/public/ict-platform/fiware-applications/juniconnlib-core), while also providing a local simulator and regression tests for device-level behavior. Including the functions for reading, writing, handling exceptions, and managing the Modbus connection, it is designed to be used with various Modbus devices and is designed to forward the read and write registers to another juniconnlib module.

The project focuses on:

- discovering devices from a JSON device registry
- loading per-device register mappings from JSON
- connecting to Modbus TCP endpoints with retry logic
- decoding register values into typed Python values
- generating FIWARE payloads for downstream publishing
- supporting a local simulated Modbus server for testing


Key implementation modules:

- [`src/juniconnlib_modbus_core/modules/modbus_device.py`](src/juniconnlib_modbus_core/modules/modbus_device.py): device abstraction, register reading, decoding, and write support
- [`src/juniconnlib_modbus_core/modules/modbus_core_communicator.py`](src/juniconnlib_modbus_core/modules/modbus_core_communicator.py): multi-device orchestration, coordinator, reconnection logic, and FIWARE payload dispatch
- [`tests/test_module/test_module.py`](tests/test_module/test_module.py): lightweight utility for polling FIWARE provisioned entities
- [`simulator/run_simulator.py`](simulator/run_simulator.py): local Modbus simulator runner

---

## Features

### Device registry support

The communicator reads a device list from a JSON file and creates one `ModbusDevice` per entry.

### Register mapping support

Each device type can specify its attribute map and register blocks in a JSON configuration. The library supports multiple register ranges and multiple data types.

### Typed decoding

Supported data types in `ModbusAttributeConfig` include:

- `uint16`
- `int16`
- `uint32`
- `int32`
- `float32`
- `float16`
- `timeStamp`
- `bitmask16`

### FIWARE-ready payloads

Each read cycle creates one or more `AttributeUpdate` payloads, with `entity_id`, `entity_type`, and a decoded attribute dictionary suitable for FIWARE or downstream agent publishing.

### Reconnect handling

The core communicator tracks disconnected devices, retries according to configured limits, and continues polling only for valid connected/provisioned devices.

### Local simulator

A Modbus simulator is included so you can validate register reads/writes without a live device.

---

## Installation

This project is packaged with setuptools and requires Python 3.12 or newer.

### Install from PyPI

To install the latest published release into your active Python environment:

```bash
pip install juniconnlib-modbus-core
```

### Install from source

Use an editable installation when developing the project or working with the repository checkout:

```bash
git clone git@jugit.fz-juelich.de:iek-10/public/ict-platform/fiware-applications/juniconnlib-modbus-core.git
cd juniconnlib-modbus-core
python -m venv .venv
```

Activate the virtual environment, then install the package:

```bash
# Linux/macOS
source .venv/bin/activate

# Windows PowerShell
.venv\Scripts\Activate.ps1

# Windows Command Prompt
.venv\Scripts\activate.bat
```

```bash
pip install -U pip
pip install -e .
```

To include the test dependencies in the editable installation:

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

---

## Runtime dependencies

The project depends on:

- `agentlib`
- `filip`
- `openpyxl`
- `pandas`
- `pydantic`
- `pymodbus`
- `juniconnlib-core`

These are declared in `pyproject.toml`.

---

## Configuration

### 1. Device registry JSON file

The communicator expects a JSON file with either a single object or a list of objects, each containing at least these keys:

- `device_id`
- `device_type`
- `modbus_host`
- `modbus_port`

Example:

```json
[
  {
    "device_id": 1,
    "device_type": "SensorType",
    "modbus_host": "192.0.2.10",
    "modbus_port": 502
  },
  {
    "device_id": 2,
    "device_type": "SensorType",
    "modbus_host": "192.0.2.11",
    "modbus_port": 502
  }
]
```

Entries without a `device_id` or `modbus_host` are dropped. Duplicate `device_id` values raise a `ValueError`.

### 2. Register configuration JSON file

Each device type is described in a JSON object keyed by the device type string.

Example:

```json
{
  "device_config": {
    "SensorType": {
      "modbus_attributes": {
        "voltage_u1_l1_n": {
          "address": 0,
          "data_type": "float32",
          "ref_scale_factor": 1.0
        },
        "frequency": {
          "address": 2,
          "data_type": "float32",
          "ref_scale_factor": 0.1
        },
        "status_bits": {
          "address": 4,
          "data_type": "bitmask16",
          "enum_bitfield_mapping": {
            "0": "ok",
            "1": "warning",
            "2": "alarm"
          }
        }
      },
      "modbus_registers": [[0, 5]],
      "create_timestamp": true,
      "byteorder": "BIG",
      "wordorder": "BIG"
    }
  }
}
```

Field explanations:

- `address`: starting register address for the attribute
- `data_type`: Modbus register type to decode
- `ref_scale_factor`: optional multiplier applied after decoding
- `is_static`: marks static attributes if needed
- `enum_bitfield_mapping`: used with `bitmask16` to map bit positions to labels
- `modbus_registers`: range list of register intervals to read per cycle
- `create_timestamp`: adds a timestamp near the read time
- `byteorder`: endian handling within each 16-bit register
- `wordorder`: endian ordering for 32-bit values

### 3. Agentlib module configuration

The communicator is intended to be used as an `agentlib` module. A typical configuration looks like this:

```json
{
  "id": "sensor_agent",
  "modules": [
    {
      "module_id": "modbus_core_communicator",
      "type": "juniconnlib_modbus_core.modbus_core_communicator",
      "device_file": "/path/to/devices.json",
      "register_file": "/path/to/registers.json",
      "device_fiware_header": {
        "service": "my_service",
        "service_path": "/"
      },
      "read_interval": 1,
      "max_reconnect_attempts": 3,
      "reconnect_interval": 60,
      "resource": "/iot/json",
      "protocol": "json"
    }
  ]
}
```

This is consistent with [`ModbusCoreConfig`](src/juniconnlib_modbus_core/modules/modbus_core_communicator.py).

---

## Architecture

### `ModbusDevice`

`ModbusDevice` is the core unit representing a single physical Modbus endpoint.

Responsibilities:

- connect/disconnect a `pymodbus` TCP client
- read holding registers from configured ranges
- decode values according to configured attribute types
- create FIWARE-style payloads from decoded data
- optionally write individual or multiple registers

### `ModbusCoreCommunicator`

`ModbusCoreCommunicator` acts as the coordinator for many devices.

Responsibilities:

- load device entries from the JSON registry
- Create a `ModbusDevice` for each device entry
- connect each device
- detect disconnected devices
- attempt reconnection with bounded retry logic
- publish each device payload to the agent broker
- keep track of provisioned FIWARE entities

This logic is implemented in `ModbusCoreCommunicator.process()` and related helpers.

---

## Data decoding behavior

The library reads contiguous ranges of registers and then slices them by attribute address offsets. For example, if a range is `[10, 15]` and an attribute is configured at address `12`, it will read the correct subset from the raw registers.

`ModbusDevice.decode_modbus_registers()` applies:

1. register-range filtering
2. register count validation
3. decode-by-type mapping
4. byte/endian normalization
5. optional scale factor multiplication
6. payload assembly

### `ref_scale_factor`

If `ref_scale_factor` is set on an attribute, the decoded value is multiplied by that factor before publication.

Example:

```json
{"address": 1, "data_type": "int16", "ref_scale_factor": 0.1}
```

This is useful for engineering values represented as scaled integers in the device.

---

## Simulator

The repo contains a simple local simulator for testing Modbus register reads and writes.

### Start the simulator

```bash
python simulator/run_simulator.py
```

The simulator configuration is located [`here`](simulator/config/simulator_setup.json).

It defines a test server and some example registers, including a few writeable and invalid addresses. This is useful for validating the Modbus protocol layer without connecting to real hardware.

---

## Example quick start

### 1. Prepare a device registry

Create `devices.json`:

```json
[
  {
    "device_id": 1,
    "device_type": "SensorType",
    "modbus_host": "192.0.2.10",
    "modbus_port": 502
  },
  {
    "device_id": 2,
    "device_type": "SensorType",
    "modbus_host": "192.0.2.11",
    "modbus_port": 502
  }
]
```

### 2. Prepare a register definition

```json
{
  "device_config": {
    "SensorType": {
      "modbus_attributes": {
        "frequency": {
          "address": 0,
          "data_type": "float32"
        },
        "voltage": {
          "address": 2,
          "data_type": "float32"
        }
      },
      "modbus_registers": [[0, 3]],
      "create_timestamp": true,
      "byteorder": "BIG",
      "wordorder": "BIG"
    }
  }
}
```

### 3. Run the module in an agent context

Use the agent configuration shown earlier and start your agent process. The communicator will read the device list, connect to each device, and publish decoded payloads.

---

## Local test harness

The repo includes a simple FIWARE test module in [`tests/test_module/test_module.py`](tests/test_module/test_module.py).

It reads entities from an Orion context broker and prints common values like voltage, current, frequency, and power. You can run it with a config file such as `tests/configs/config_test_module.json` via:

```bash
MODBUS_CONFIG=tests/configs/config_test_module.json python -m tests.test_module.main
```

This is primarily a validation utility; the main functional code is the Modbus communicator and device modules.

---

## Testing

The project ships with pytest-based unit tests under `tests/`.

Run the suite with:

```bash
pytest -q
```

Examples of coverage include:

- device connection and reconnection behavior
- register read errors and warnings
- payload creation
- endianness and scale handling
- utility validation for IP/url handling

`tests/manual_sim.py` and `tests/manual_sim_modbus.py` are manual scripts and require a running simulator.

---

## Notes and caveats

- The code expects a valid Modbus TCP server at the configured host/port.
- `modbus_registers` should be sized carefully to avoid oversized frames.
- `byteorder` and `wordorder` must currently be given in upper case (`"BIG"` / `"LITTLE"`) in the register configuration.
- `max_reconnect_attempts` and `reconnect_interval` are enforced by the coordinator.
- Some legacy examples in the repo are simplified and serve as reference patterns rather than the only supported configuration style.

---

If you are integrating this into an agent environment, start from the device registry and register JSON examples, then validate against the simulator before connecting to physical hardware.
