Skip to content

Commit cd21dc3

Browse files
committed
Added docstrings
1 parent 83aba34 commit cd21dc3

4 files changed

Lines changed: 191 additions & 38 deletions

File tree

src/main.py

Lines changed: 60 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,86 @@
1-
# -*- coding: utf-8 -*-
21

3-
# Copyright 2023 Regulus
42

5-
# Permission is hereby granted, free of charge, to any person obtaining a
6-
# copy of this software and associated documentation files (the "Software"),
7-
# to deal in the Software without restriction, including without limitation
8-
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
9-
# and/or sell copies of the Software, and to permit persons to whom the
10-
# Software is furnished to do so, subject to the following conditions:
3+
"""main.py
114
12-
# The above copyright notice and this permission notice shall be included in
13-
# all copies or substantial portions of the Software.
5+
Communication Middleware for TRNSYS Simulation
146
15-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21-
# THE SOFTWARE.
7+
This module provides functionality to interface with Modbus servers as part of a TRNSYS simulation.
8+
It defines a `ModbusServer` class for handling connections, reading, and writing to Modbus servers.
9+
The module is designed to work with TRNSYS, a transient system simulation program, by providing
10+
custom functions for different stages of the simulation process such as initialization, time step
11+
processing, and simulation end.
2212
23-
# --------------------------------------------------------------------------
13+
The module also includes helper functions for initializing Modbus server connections based on
14+
configured settings and for handling various TRNSYS simulation stages like start time, iteration,
15+
end of time step, and last call of the simulation.
16+
17+
Classes
18+
-------
19+
ModbusServer
20+
A class representing a Modbus server, providing methods for connecting, reading, and writing data.
21+
22+
Functions
23+
---------
24+
define_servers(server_configs)
25+
Initializes Modbus servers based on provided configuration.
26+
27+
Initialization(TRNData)
28+
Initializes the global variable 'servers' and connects to servers for the TRNSYS simulation.
29+
30+
StartTime(TRNData)
31+
Handles actions to be performed at the start time of TRNSYS simulation.
32+
33+
Iteration(TRNData)
34+
Handles actions for each TRNSYS iteration within a time step.
35+
36+
EndOfTimeStep(TRNData)
37+
Handles end-of-time-step actions for the connected servers based on TRNData.
2438
25-
__author__ = "Erika Langerová, Michal Broum"
26-
__copyright__ = "<2023> <Regulus>"
39+
LastCallOfSimulation(TRNData)
40+
Closes connections and performs cleanup at the end of the TRNSYS simulation.
41+
42+
Notes
43+
-----
44+
- The module uses global variables and relies on specific configuration files (`server_config`
45+
and `middleware_config`).
46+
- It is tailored to work with the TRNSYS simulation environment, specifically with its data handling.
47+
48+
49+
See Also
50+
--------
51+
server_config : Module providing server configurations.
52+
middleware_config : Module providing middleware configurations for the simulation.
53+
54+
"""
55+
56+
__author__ = "Erika Langerová"
57+
__copyright__ = "<2023> <UCEEB CVUT>"
2758
__credits__ = [" ", " "]
2859

2960
__license__ = "MIT (X11)"
3061
__version__ = "1.2.1"
3162
__maintainer__ = ["Erika Langerová"]
32-
__email__ = ["erika.langerova@regulus.cz"]
33-
__status__ = "Alfa"
63+
__email__ = ["erika.langerova@cvut.cz"]
64+
__status__ = "Released"
3465

3566
__python__ = "3.10.5"
3667
__TRNSYS__ = "18.04.0000"
3768

3869
# --------------------------------------------------------------------------
3970

40-
import logging
71+
# Standard library imports
4172
import time as osTime
4273
from typing import Dict, List, Union, Optional
74+
75+
# Third party imports
76+
import logging
4377
from pymodbus.client import ModbusTcpClient
4478
from pymodbus.payload import BinaryPayloadBuilder, Endian
79+
80+
# Local imports
4581
from server_config import SERVER_CONFIGS
4682
from middleware_config import SIM_SLEEP, SIMULATION_MODEL, LOGGING_FILENAME
4783

48-
4984
# --------------------------------------------------------------------------
5085

5186
class ModbusServer:
@@ -238,12 +273,10 @@ def define_servers(server_configs: List[Dict[str, Union[str, int, List[int], int
238273
servers.append(server)
239274
return servers
240275

241-
242-
243276
# --------------------------------------------------------------------------------
244277
# START
245278
# --------------------------------------------------------------------------------
246-
# ...
279+
247280

248281
def Initialization(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:
249282
"""
@@ -292,8 +325,6 @@ def Initialization(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> No
292325
server.close_connection()
293326

294327

295-
# --------------------------------------------------------------------------------
296-
297328
def StartTime(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:
298329
"""
299330
Function called at TRNSYS starting time (not an actual time step,
@@ -313,8 +344,6 @@ def StartTime(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:
313344

314345
return
315346

316-
317-
# --------------------------------------------------------------------------------
318347

319348
def Iteration(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:
320349
"""
@@ -334,7 +363,6 @@ def Iteration(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:
334363

335364
return
336365

337-
# --------------------------------------------------------------------------------
338366

339367
def EndOfTimeStep(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:
340368
"""
@@ -391,7 +419,6 @@ def EndOfTimeStep(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> Non
391419

392420
osTime.sleep(SIM_SLEEP)
393421

394-
# --------------------------------------------------------------------------------
395422

396423
def LastCallOfSimulation(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:
397424
"""

src/middleware_config.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,34 @@
11

2-
# constants
2+
"""middleware_config.py
33
4+
Configuration settings for the main.py module.
5+
6+
This module defines several constants that are used throughout the Modbus server implementation
7+
and its interaction with the TRNSYS simulation environment. These constants are crucial for
8+
the proper functioning of the data exchange process and logging mechanisms.
9+
10+
Constants
11+
---------
12+
SIM_SLEEP : int
13+
The sleep duration in seconds between successive end-of-time-step actions during the simulation.
14+
This is used to prevent overloading the system with rapid consecutive requests.
15+
16+
LOGGING_FILENAME : str
17+
The filename for the log file where all log messages related to the data exchange process are stored.
18+
This log file is useful for debugging and monitoring the flow of data between the TRNSYS simulation
19+
and the Modbus servers.
20+
21+
SIMULATION_MODEL : str
22+
The identifier for the simulation model. The name of the .tpf file with the simulation model in-use
23+
must be provided.
24+
25+
Notes
26+
-----
27+
- These constants are used in the main.py module.
28+
- Changing these values can significantly impact the performance and behavior of the data exchange
29+
process. Ensure that any modifications are well-tested and compatible with the overall system requirements.
30+
31+
"""
432
SIM_SLEEP = 60
533
LOGGING_FILENAME = 'DataExchange.log'
634
SIMULATION_MODEL = 'main'

src/server_config.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,15 @@
1-
# indexování je od nula
1+
2+
"""server_config.py
3+
4+
This config file contains the `SERVER_CONFIGS` list, which consists of dictionaries.
5+
Each dictionary represents the configuration of a Modbus server, including details
6+
such as the host address, port number, and register information.
7+
Four ModBus servers are defined here as examples.
8+
9+
The indexing starts at zero.
10+
11+
"""
12+
213
SERVER_CONFIGS = [
314
{
415
"host": "10.208.8.11",

src/server_manager.py

Lines changed: 90 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,80 @@
1+
2+
"""server_manager.py
3+
4+
Manage Modbus server configurations with a graphical user interface.
5+
6+
This script contains definitions for managing Modbus server settings
7+
and a GUI for easy manipulation of these configurations. It includes
8+
functions for adding, deleting, and modifying server configurations.
9+
10+
The output of the GUI is directed to the server_config.py, from which
11+
the main.py module reads the ModBus servers definitions.
12+
13+
The `SERVER_CONFIGS` list consists of dictionaries, each representing
14+
the configuration of a Modbus server, including details such as host
15+
address, port number, and register information.
16+
17+
Attributes
18+
----------
19+
SERVER_CONFIGS : list of dict
20+
A list containing the configurations for each Modbus server. Each
21+
dictionary includes the host, port, and register information.
22+
23+
Functions
24+
---------
25+
add_server()
26+
Adds a new server configuration to `SERVER_CONFIGS` and updates
27+
the configuration file.
28+
delete_selected_server()
29+
Removes the selected server configuration from `SERVER_CONFIGS`.
30+
clear_entries()
31+
Clears all input fields in the GUI.
32+
update_server_listbox()
33+
Updates the listbox to display the current server configurations.
34+
35+
See Also
36+
--------
37+
tkinter : The standard Python interface to the Tk GUI toolkit.
38+
39+
Notes
40+
-----
41+
- The script should be directly run to launch the GUI for managing server
42+
configurations.
43+
- Direct modifications to the `SERVER_CONFIGS` affect Modbus server
44+
connections.
45+
- Ensure accurate and valid data entry for stable Modbus server
46+
communication.
47+
48+
Examples
49+
--------
50+
To launch the GUI, run the script:
51+
52+
$ python server_manager.py
53+
54+
In the GUI, add, delete, or view Modbus server configurations as needed.
55+
56+
"""
57+
158
if __name__ == "__main__":
59+
60+
# Standard library imports
61+
from typing import NoReturn
62+
63+
# Third party imports
264
import tkinter as tk
65+
66+
# Local imports
367
from server_config import SERVER_CONFIGS
468

5-
def add_server():
69+
70+
def add_server() -> NoReturn:
71+
"""
72+
Add a new server configuration to the SERVER_CONFIGS list and update the configuration file.
73+
74+
Retrieves server details from the GUI entries, creates a dictionary for the new server,
75+
appends it to SERVER_CONFIGS, and writes the updated list to the server_config.py file.
76+
77+
"""
678
host = host_entry.get()
779
port = port_entry.get()
880
rw_registers = rw_registers_entry.get()
@@ -23,15 +95,26 @@ def add_server():
2395
update_server_listbox()
2496
clear_entries()
2597

26-
def delete_selected_server():
98+
def delete_selected_server() -> NoReturn:
99+
"""
100+
Delete the selected server configuration from the SERVER_CONFIGS list and update the configuration file.
101+
102+
Identifies the selected server in the GUI listbox, removes it from SERVER_CONFIGS,
103+
and writes the updated list to the server_config.py file.
104+
105+
"""
27106
selected_index = servers_listbox.curselection()
28107
if selected_index:
29108
SERVER_CONFIGS.pop(selected_index[0])
30109
with open("server_config.py", "w") as config_file:
31110
config_file.write(f"SERVER_CONFIGS = {str(SERVER_CONFIGS)}")
32111
update_server_listbox()
33112

34-
def clear_entries():
113+
def clear_entries() -> NoReturn:
114+
"""
115+
Clear all input fields in the GUI.
116+
117+
"""
35118
host_entry.delete(0, tk.END)
36119
port_entry.delete(0, tk.END)
37120
rw_registers_entry.delete(0, tk.END)
@@ -40,6 +123,10 @@ def clear_entries():
40123
update_server_listbox()
41124

42125
def update_server_listbox():
126+
"""
127+
Update the listbox in the GUI to display the current server configurations.
128+
129+
"""
43130
servers_listbox.delete(0, tk.END)
44131
for server in SERVER_CONFIGS:
45132
servers_listbox.insert(tk.END, f"{server['host']}:{server['port']}")

0 commit comments

Comments
 (0)