Skip to content

Commit

Permalink
Added docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
langeeri committed Jan 29, 2024
1 parent 83aba34 commit cd21dc3
Show file tree
Hide file tree
Showing 4 changed files with 191 additions and 38 deletions.
93 changes: 60 additions & 33 deletions src/main.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,86 @@
# -*- coding: utf-8 -*-

# Copyright 2023 Regulus

# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
"""main.py
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
Communication Middleware for TRNSYS Simulation
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
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, a transient system simulation program, 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.
Classes
-------
ModbusServer
A class representing a Modbus server, providing methods for connecting, reading, and writing data.
Functions
---------
define_servers(server_configs)
Initializes Modbus servers based on provided configuration.
Initialization(TRNData)
Initializes the global variable 'servers' and connects to servers for the TRNSYS simulation.
StartTime(TRNData)
Handles actions to be performed at the start time of TRNSYS simulation.
Iteration(TRNData)
Handles actions for each TRNSYS iteration within a time step.
EndOfTimeStep(TRNData)
Handles end-of-time-step actions for the connected servers based on TRNData.
__author__ = "Erika Langerová, Michal Broum"
__copyright__ = "<2023> <Regulus>"
LastCallOfSimulation(TRNData)
Closes connections and performs cleanup at the end of the TRNSYS simulation.
Notes
-----
- The module uses global variables and relies on specific configuration files (`server_config`
and `middleware_config`).
- It is tailored to work with the TRNSYS simulation environment, specifically with its data handling.
See Also
--------
server_config : Module providing server configurations.
middleware_config : Module providing middleware configurations for the simulation.
"""

__author__ = "Erika Langerová"
__copyright__ = "<2023> <UCEEB CVUT>"
__credits__ = [" ", " "]

__license__ = "MIT (X11)"
__version__ = "1.2.1"
__maintainer__ = ["Erika Langerová"]
__email__ = ["erika.langerova@regulus.cz"]
__status__ = "Alfa"
__email__ = ["erika.langerova@cvut.cz"]
__status__ = "Released"

__python__ = "3.10.5"
__TRNSYS__ = "18.04.0000"

# --------------------------------------------------------------------------

import logging
# Standard library imports
import time as osTime
from typing import Dict, List, Union, Optional

# Third party imports
import logging
from pymodbus.client import ModbusTcpClient
from pymodbus.payload import BinaryPayloadBuilder, Endian

# Local imports
from server_config import SERVER_CONFIGS
from middleware_config import SIM_SLEEP, SIMULATION_MODEL, LOGGING_FILENAME


# --------------------------------------------------------------------------

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



# --------------------------------------------------------------------------------
# START
# --------------------------------------------------------------------------------
# ...


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


# --------------------------------------------------------------------------------

def StartTime(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:
"""
Function called at TRNSYS starting time (not an actual time step,
Expand All @@ -313,8 +344,6 @@ def StartTime(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:

return


# --------------------------------------------------------------------------------

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

return

# --------------------------------------------------------------------------------

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

osTime.sleep(SIM_SLEEP)

# --------------------------------------------------------------------------------

def LastCallOfSimulation(TRNData: Dict[str, Dict[str, List[Union[int, float]]]]) -> None:
"""
Expand Down
30 changes: 29 additions & 1 deletion src/middleware_config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,34 @@

# constants
"""middleware_config.py
Configuration settings for the main.py module.
This module defines several constants that are used throughout the 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.
Constants
---------
SIM_SLEEP : int
The sleep duration in seconds between successive end-of-time-step actions during the simulation.
This is used to prevent overloading the system with rapid consecutive requests.
LOGGING_FILENAME : str
The filename for the log file where all log messages related to the data exchange process are stored.
This log file is useful for debugging and monitoring the flow of data between the TRNSYS simulation
and the Modbus servers.
SIMULATION_MODEL : str
The identifier for the simulation model. The name of the .tpf file with the simulation model in-use
must be provided.
Notes
-----
- These constants are used in the main.py module.
- Changing these values can significantly impact the performance and behavior of the data exchange
process. Ensure that any modifications are well-tested and compatible with the overall system requirements.
"""
SIM_SLEEP = 60
LOGGING_FILENAME = 'DataExchange.log'
SIMULATION_MODEL = 'main'
Expand Down
13 changes: 12 additions & 1 deletion src/server_config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
# indexování je od nula

"""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 indexing starts at zero.
"""

SERVER_CONFIGS = [
{
"host": "10.208.8.11",
Expand Down
93 changes: 90 additions & 3 deletions src/server_manager.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,80 @@

"""server_manager.py
Manage Modbus server configurations with a graphical user interface.
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.
The output of the GUI is directed to the server_config.py, from which
the main.py module reads the ModBus servers definitions.
The `SERVER_CONFIGS` list consists of dictionaries, each representing
the configuration of a Modbus server, including details such as host
address, port number, and register information.
Attributes
----------
SERVER_CONFIGS : list of dict
A list containing the configurations for each Modbus server. Each
dictionary includes the host, port, and register information.
Functions
---------
add_server()
Adds a new server configuration to `SERVER_CONFIGS` and updates
the configuration file.
delete_selected_server()
Removes the selected server configuration from `SERVER_CONFIGS`.
clear_entries()
Clears all input fields in the GUI.
update_server_listbox()
Updates the listbox to display the current server configurations.
See Also
--------
tkinter : The standard Python interface to the Tk GUI toolkit.
Notes
-----
- The script should be directly run to launch the GUI for managing server
configurations.
- Direct modifications to the `SERVER_CONFIGS` affect Modbus server
connections.
- Ensure accurate and valid data entry for stable Modbus server
communication.
Examples
--------
To launch the GUI, run the script:
$ python server_manager.py
In the GUI, add, delete, or view Modbus server configurations as needed.
"""

if __name__ == "__main__":

# Standard library imports
from typing import NoReturn

# Third party imports
import tkinter as tk

# Local imports
from server_config import SERVER_CONFIGS

def add_server():

def add_server() -> NoReturn:
"""
Add a new server configuration to the SERVER_CONFIGS list and update the configuration file.
Retrieves server details from the GUI entries, creates a dictionary for the new server,
appends it to SERVER_CONFIGS, and writes the updated list to the server_config.py file.
"""
host = host_entry.get()
port = port_entry.get()
rw_registers = rw_registers_entry.get()
Expand All @@ -23,15 +95,26 @@ def add_server():
update_server_listbox()
clear_entries()

def delete_selected_server():
def delete_selected_server() -> NoReturn:
"""
Delete the selected server configuration from the SERVER_CONFIGS list and update the configuration file.
Identifies the selected server in the GUI listbox, removes it from SERVER_CONFIGS,
and writes the updated list to the server_config.py file.
"""
selected_index = servers_listbox.curselection()
if selected_index:
SERVER_CONFIGS.pop(selected_index[0])
with open("server_config.py", "w") as config_file:
config_file.write(f"SERVER_CONFIGS = {str(SERVER_CONFIGS)}")
update_server_listbox()

def clear_entries():
def clear_entries() -> NoReturn:
"""
Clear all input fields in the GUI.
"""
host_entry.delete(0, tk.END)
port_entry.delete(0, tk.END)
rw_registers_entry.delete(0, tk.END)
Expand All @@ -40,6 +123,10 @@ def clear_entries():
update_server_listbox()

def update_server_listbox():
"""
Update the listbox in the GUI to display the current server configurations.
"""
servers_listbox.delete(0, tk.END)
for server in SERVER_CONFIGS:
servers_listbox.insert(tk.END, f"{server['host']}:{server['port']}")
Expand Down

0 comments on commit cd21dc3

Please sign in to comment.