The Ultimate "How-to" Manual for Coupling TRNSYS, Python, and PLCs - PART 1
This article explores the integration of TRNSYS, Python, and PLCs to enhance control and simulation processes. By coupling TRNSYS for dynamic simulations, Python for communication, and PLCs for real-time control, the approach establishes a comprehensive framework for dynamic system testing.
Prerequisities
To make the most of this guide, readers should have a working knowledge of TRNSYS, Python, and PLC programming. Basic experience in these areas is expected for following the instructions and examples provided. The article also assumes that users have basic knowledge of working with code in a text editor, such as VS Code or PyCharm, and basic command line skills in Windows.
General use cases
Use cases scenarios for integrating TRNSYS with PLCs involve advanced control and testing applications where simulation and real-world systems need to work in tandem. For example, in the development of energy management systems, TRNSYS can simulate various scenarios such as load changes or energy efficiency strategies, while PLCs control the actual hardware like HVAC systems or renewable energy sources. This integration allows engineers to test and refine control strategies in a simulated environment before deploying them in real systems, ensuring improved reliability and performance.
Principle
When using TRNSYS for simulation alongside PLCs, effective data management and synchronization are key. Communication middleware must be implemented to facilitate seamless interaction between the simulation software and the PLCs. This middleware enables bidirectional data transfer and ensures that the simulation time steps are synchronized with PLC operationss.
The middleware used in this tutorial is build on top of Type 3157. Type 3157 enables event-driven Python calls from TRNSYS through CFFI, allowing you to incorporate established Python libraries like NumPy into your python modules. This approach provides enhanced flexibility compared to the conventional TRNSYS component (Type 169).
The Middleware-PLC communication operates over Ethernet by establishing a ModBus TCP/IP connection between the middleware and the PLC. The middleware acts as a bridge, translating simulation data from TRNSYS into ModBus messages that the PLC can understand. Data is exchanged in real-time, with the middleware sending control signals from TRNSYS to the PLC and retrieving feedback from the PLC to update the simulation, ensuring synchronized operation between the simulated environment and the physical system.
The design relies on the communication middleware acting as ModBus TCP/IP client and the PLC(s) acting as ModBus TCP/IP server(s). The middleware is designed to establish ModBus client connections during the initialization phase of the simulation, which occurs upon the first invocation of Python from TRNSYS.
Workflow
In this workflow, you'll start by installing Python 3.10.x and verifying its successful installation, followed by the installation of TRNSYS Type 3157. Next, you'll configure a ModBus TCP/IP server within your PLC to communicate over port 502. Finally, you'll download and set up the Python Communication Middleware to facilitate communication between TRNSYS and your PLC. You will then configure it for your specific case.
Please note that TRNSYS is exclusively compatible with Windows operating system. Therefore, the installation instructions provided here are tailored specifically for Windows. Users on macOS or Linux will need to set up a Windows environment, such as a virtual machine (see VirtualBox or VMware), to run TRNSYS effectively. Please follow the Windows-specific steps to ensure proper installation and operation.
Requirements
Physical layer
There are two options:
Installation process
1. Install Python 3.10.5
To verify that Python is correctly installed, open a Command Prompt window with administrative privileges (To do this, use the Windows search feature, type "cmd," then right-click on the Command Prompt shortcut and select "Run as administrator." ). Once the Command Prompt is open, type the first command from below and press Enter, followed by typing the second command and pressing Enter.
python --version
where python310.dll
The first command should return the python installed version, the second command should return the path to the DLL. If Windows cannot find it, you should search for that file and add its path to Windows search path. For troubleshooting, see Stack Overflow.
2. Install TRNSYS Type 3157
The following instructions assume that TRNSYS 18.04.0000 is already installed on your system. If TRNSYS is not yet installed, please complete the installation before proceeding.
The required files are distributed in a ZIP archive, see below.
The ZIP archive should be extracted in the TRNSYS installation directory, which is C:\TRNSYS18 by default. After extraction, this files should be present in your TRNSYS directory:
C:\TRNSYS18\Exe\PythonInterface.dll
C:\TRNSYS18\Studio\Proformas\TRNLib\Calling Python (CFFI)\
C:\TRNSYS18\TRNLib\CallingPython-Cffi\Documentation\
C:\TRNSYS18\TRNLib\CallingPython-Cffi\Examples\
C:\TRNSYS18\TRNLib\CallingPython-Cffi\PythonInterface\
C:\TRNSYS18\TRNLib\CallingPython-Cffi\SourceCode\
C:\TRNSYS18\UserLib\DebugDLLs\Type3157.dll
C:\TRNSYS18\UserLib\ReleaseDLLs\Type3157.dll
To verify that the Type 3157 installation was successful, try opening one of the example files located in C:\TRNSYS18\TRNLib\CallingPython-Cffi\Examples. Ensure that the type appears in the direct access tool (the list on the right), as shown below, and then click 'Run'. The simulation should open an online plotter and generate a graphical output.
For troubleshooting, see PART 2 of this article.
领英推荐
3. Define ModBus server(s) in your PLC
The principle of the setup is as follows: In the PLC programming interface, define a ModBus TCP/IP server (slave) that will communicate over port 502. Than define your registers. The exact configuration process may differ depending on the vendor and the model of the PLC you are using. Refer to the manufacturer's documentation for instructions.
4. Install Middleware
git clone https://github.com/langeeri/trnsys-plc-middleware.git
cd trnsys-plc-middleware
python -m venv venv
venv\Scripts\activate
pip install -r requirements.txt
The final directory structure should look like as follows:
trnsys-plc-middleware/
├── docs/
├── src/
├── tests/
├── .coveragerc
├── .gitignore
├── LICENSE
├── readme.md
└── requirements.txt
Inside the src directory, you will find the following files:
src/
├── main.py # Main Python script
├── main.tpf # Simulation model
├── middleware_config.py # Config for middleware
├── server_config.py # Config for the ModBus servers
└── server_manager.py # GUI for ModBus servers config
main.py
This module provides functionality to interface with Modbus servers as part of a TRNSYS simulation. It defines a ModbusServer class for handling connections, reading, and writing to Modbus servers. The module is designed to work with TRNSYS by providing custom functions for different stages of the simulation process such as initialization, time step processing, and simulation end.
The module also includes helper functions for initializing Modbus server connections based on configured settings and for handling various TRNSYS simulation stages like start time, iteration, end of time step, and last call of the simulation.
main.tpf
Sample simulation model. It corresponds with the middleware configuration and serves to better understand how the TRNSYS model configuration aligns with the middleware configuration. You can see how the indexes in Type 3157 match the indexes in the middleware configuration.
middleware_config.py
This module defines several constants that are used throughout the main.py module for ModBus server implementation and its interaction with the TRNSYS simulation environment. These constants are crucial for the proper functioning of the data exchange process and logging mechanisms.
! IMPORTANT ! You need to change the SIMULATION_MODEL constant to match your simulation model name! For example, if your TRNSYS simulation model is named MyModel.tpf, the constant should be SIMULATION_MODEL = 'MyModel'
server_manager.py
This script contains definitions for managing Modbus server settings and a GUI for easy manipulation of these configurations. It includes functions for adding, deleting, and modifying server configurations.
You should run the GUI and use it to define your ModBus servers. The GUI will automatically update the server_config.py file, which is then read by main.py. Alternatively, you can manually modify the server_config.py configuration file to define your servers.
server_config.py
This config file contains the SERVER_CONFIGS list, which consists of dictionaries. Each dictionary represents the configuration of a Modbus server, including details such as the host address, port number, and register information. Four ModBus servers are defined here as examples.
The configuration for Modbus servers should be specified inside server_configs.py in SERVER_CONFIGS list. This list includes dictionaries with details such as the host, port, registers, and input indexes for each server.
The server is specified with the following parameters:
EXAMPLE CONFIGS (You need to change it to match your situation)
SERVER_CONFIGS = [
{
'host': '127.0.0.1',
'port': 502,
'rw_registers': [1, 11, 12],
'input_indexes': [5, 2, 3],
'r_registers': [4, 5],
},
# If you dont need any read registers, keep the array blank like this:
{
'host': '127.0.0.1',
'port': 502,
'rw_registers': [1, 11, 12],
'input_indexes': [5, 2, 3],
'r_registers': [],
},
# Add additional servers as needed
]
Note: Since this is Python, the indexing is zero-based. The current middleware implementation supports only read and write operations on holding registers. The middleware does not support other types of registers, such as coils, at this time. Regarding r_registers, the current implementation of the middleware is designed to read data from multiple registers in a single PLC. In scenarios where there are multiple PLCs involved, and data from all these PLCs needs to be sent back to TRNSYS, you need to modify main.py file further. Regarding rw_registers, reading and writing to/from multiple registers at multiple PLCs is supported by the current implementation of the middleware.
Final steps and usage
Follow these steps:
The middleware is set up in such a way that ModBus clients are opened in the initialization phase of the simulation, meaning at the first call of Python from TRNSYS. At this stage, a connection to the ModBus servers, i.e., all the used PLCs, is established, but data exchange does not yet occur. It makes no sense to start data exchange before convergence is achieved in the computation of the current simulation step. The communication at this step occurs in a way that the Type 3157 component exchanges data with the communication middleware through a nested hashmap (a hashmap is a data type, it's an unordered set of key-value pairs, in Python it's often referred to as a dictionary), where the inputs from TRNSYS to Type 3157 in the current time step are sent as hashmap variables to the middleware. The data from the hashmap are sorted in the middleware and sent for writing to the registers of the respective PLCs. The data exchange in the opposite direction, i.e., from the PLCs through the middleware to TRNSYS, is resolved in a similar manner.
Specific use case
See the article published at TZB-info (in Czech): Pokro?ilé odla?ování softwaru pro ?ízení systém? s tepelnymi ?erpadly
Final words
In conclusion, integrating TRNSYS, Python, and PLCs offers a powerful combination for enhancing control and simulation processes in complex systems. This article has demonstrated how each component contributes to creating a cohesive framework that facilitates dynamic system testing. By following the outlined procedures for installation, configuration, and synchronization, users can achieve a seamless interaction between simulation models and control systems.