-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_config.py
244 lines (224 loc) · 8.11 KB
/
app_config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import os
import yaml
import logging
APP_PATH = os.path.dirname(os.path.abspath(__file__))
LOG_DIR_PATH = os.path.join(APP_PATH, 'logs')
APP_CONFIG_PATH = os.path.join(APP_PATH, 'config.yaml')
DEFAULT_CONFIG = {
"influxdb": {
"host": "localhost",
"port": 8086,
"username": "garden_core_user",
"password": "",
"database": "garden"
},
"sensors": [
{
"name": "soilMoistureSensor1",
"type": "SoilMoistureSensor",
"params": {
"read_frequency": 60,
"i2c_address": 0x48
}
},
{
"name": "temperatureSensor1",
"type": "TemperatureSensor",
"params": {
"read_frequency": 60,
"pin": 4
}
},
{
"name": "humiditySensor1",
"type": "HumiditySensor",
"params": {
"read_frequency": 60,
"pin": 4
}
},
{
"name": "lightSensor1",
"type": "LightSensor",
"params": {
"read_frequency": 60,
"i2c_address": 0x23
}
}
],
"actuators": [
{
"name": "pumpActuator1",
"type": "BaseActuator",
"params": {
"gpio_pin": 26,
"initial_state": False
}
},
{
"name": "ventilationActuator1",
"type": "BaseActuator",
"params": {
"gpio_pin": 13,
"initial_state": False
}
},
{
"name": "lightingActuator1",
"type": "BaseActuator",
"params": {
"gpio_pin": 19,
"initial_state": False
}
}
],
"controllers": [
{
"type": "IrrigationController",
"sensors": {
"soilMoistureSensor1": {
"threshold": 0.75,
"comparison": "LOWER"
}
},
"actuator": "pumpActuator1",
"params": {
"check_interval": 60,
"cooldown_period": 600,
"pump_flow_rate": 240,
"water_volume": 1,
}
},
{
"type": "VentilationController",
"sensors": {
"temperatureSensor1": {
"threshold": 27,
"comparison": "HIGHER"
},
"humiditySensor1": {
"threshold": 75,
"comparison": "HIGHER"
}
},
"actuator": "ventilationActuator1",
"params": {
"check_interval": 60,
"cooldown_period": 120
}
},
{
"type": "LightingController",
"sensors": {
"lightSensor1": {
"threshold": 7000,
"comparison": "LOWER"
}
},
"actuator": "lightingActuator1",
"params": {
"check_interval": 60,
"cooldown_period": 180,
"activation_time": 1800,
"start_hour": 9,
"end_hour": 21
}
}
]
}
class AppConfig:
"""
AppConfig is a singleton class responsible for handling application configuration.
It loads, updates, and saves configuration data from/to a YAML file. This class ensures that there is only one instance of the configuration across the application.
Attributes:
config_file (str): Path to the YAML configuration file.
config_data (dict): Dictionary holding the loaded configuration data.
Methods:
load_config: Loads configuration data from the YAML file, merging it with default values.
save_config: Saves the current configuration data to the YAML file.
update_config: Updates the configuration data with provided values and saves it.
get_config: Returns the current configuration data.
merge_config: Merges loaded configuration with default values and saves if necessary.
"""
_instance = None
def __new__(cls, config_file: str):
"""
Create a new instance of AppConfig or return the existing one.
This method implements the singleton pattern. If an instance of AppConfig doesn't exist, it creates a new one and initializes it. If an instance already exists, it returns the existing instance.
Args:
config_file (str): The path to the configuration file in YAML format.
Returns:
AppConfig: An instance of the AppConfig class.
"""
if cls._instance is None:
cls._instance = super(AppConfig, cls).__new__(cls)
cls._instance.config_file = config_file
cls._instance.config_data = DEFAULT_CONFIG.copy()
cls._instance.load_config()
return cls._instance
def load_config(self):
"""
Load configuration from a YAML file, merging it with default values.
This method checks if the configuration file exists. If it does, it loads the configuration and merges it with the default values defined in DEFAULT_CONFIG. If the file does not exist, it uses the default configuration.
"""
logger = logging.getLogger('app_logger')
if os.path.exists(self.config_file):
try:
with open(self.config_file, 'r', encoding='utf-8') as file:
file_config = yaml.safe_load(file) or {}
self.merge_config(file_config)
logger.info(f"Configuration loaded from {self.config_file}")
except Exception as ex:
logger.error(f"Failed to load configuration: {ex}")
logger.info("Using default configuration.")
else:
logger.warning(f"Config file {self.config_file} does not exist. Using default configuration.")
self.save_config()
def merge_config(self, file_config: dict):
"""
Merge loaded configuration with default values and save if necessary.
Args:
file_config (dict): Configuration data loaded from the YAML file.
Compares file_config with DEFAULT_CONFIG and adds any missing keys from
DEFAULT_CONFIG to file_config. Updates the config_data and saves changes if needed.
"""
missing_keys = set(DEFAULT_CONFIG) - set(file_config)
if missing_keys:
for key in missing_keys:
file_config[key] = DEFAULT_CONFIG[key]
self.config_data.update(file_config)
self.save_config()
else:
self.config_data = file_config
def save_config(self):
"""
Save the current configuration to a YAML file.
Writes the current state of config_data to the YAML file specified in config_file. If an error occurs during saving, it logs an error message.
"""
logger = logging.getLogger('app_logger')
try:
with open(self.config_file, 'w', encoding='utf-8') as file:
yaml.dump(self.config_data, file, allow_unicode=True, default_flow_style=False)
logger.info("Configuration saved successfully.")
except Exception as ex:
logger.error(f"Failed to save configuration: {ex}")
def update_config(self, new_config_data: dict):
"""
Update the configuration with new data and save it.
Args:
new_config_data (dict): A dictionary containing configuration data to be updated.
"""
logger = logging.getLogger('app_logger')
try:
self.config_data.update(new_config_data)
self.save_config()
logger.info("Configuration updated successfully.")
except Exception as ex:
logger.error(f"Failed to update configuration: {ex}")
def get_config(self):
"""
Return the current configuration data.
Returns:
dict: The current configuration data.
"""
return self.config_data