Files
weather_station_MK2/software/rs485_client_to_mqtt/config_reader.py

89 lines
2.9 KiB
Python

""""
ModBus configuration file reader routines
Copyright (C) 2023-2025 M.T. Konstapel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import yaml
from yaml.loader import SafeLoader
class config_reader:
# initiate class: define name configuration files
def __init__(self, config_file):
self.config_file = config_file
def read_settings(self):
if self.read_config_file() == 0:
return 0
if self.test_global_settings() == 0:
return 0
if self.test_modbus_settings() == 0:
return 0
if self.test_modbus_servers_settings() == 0:
return 0
return 1
def read_config_file (self):
try:
with open(self.config_file) as f:
self.config_file_settings = yaml.load(f, Loader=SafeLoader)
except:
print ("Configuration file ./" + self.config_file + " not found or syntax error in file.")
return 0
else:
return 1
# Test if all settings are pressent
def test_global_settings(self):
# Test is all expected settings are present
try:
tmp = self.config_file_settings['global']['program-log']
tmp = self.config_file_settings['global']['data-log']
tmp = self.config_file_settings['global']['mqtt-server']
tmp = self.config_file_settings['global']['mqtt-port']
tmp = self.config_file_settings['global']['mqtt-root-topic']
except:
print ("Error in the global section of the configuration file.")
return 0
else:
return 1
# Test if all settings are pressent
def test_modbus_settings(self):
# Test is all expected settings are present
try:
tmp = self.config_file_settings['modbus']['port']
except:
print ("Error in the modbus section of the configuration file.")
return 0
else:
return 1
def test_modbus_servers_settings(self):
for entry in self.config_file_settings['modbus_servers']:
try:
tmp = entry['address']
tmp = entry['description']
except:
print ("Error in the modbus_servers section of the configuration file.")
return 0
else:
return 1