87 lines
3.3 KiB
Python
87 lines
3.3 KiB
Python
import json
|
|
import os
|
|
import logging
|
|
from config_validator import ConfigValidator
|
|
|
|
class ConfigManager:
|
|
"""配置文件管理器"""
|
|
|
|
def __init__(self, config_path="../config/config.json"):
|
|
self.config_path = config_path
|
|
self.config = None
|
|
self.load_config()
|
|
|
|
def load_config(self):
|
|
"""加载配置文件"""
|
|
try:
|
|
if not os.path.exists(self.config_path):
|
|
# 尝试从备份恢复
|
|
backup_path = self.config_path + ".bak"
|
|
if os.path.exists(backup_path):
|
|
logging.warning(f"Main config not found, using backup: {backup_path}")
|
|
with open(backup_path, 'r') as src, open(self.config_path, 'w') as dst:
|
|
config_data = src.read()
|
|
dst.write(config_data)
|
|
else:
|
|
raise FileNotFoundError(f"Configuration file not found: {self.config_path}")
|
|
|
|
with open(self.config_path, 'r') as f:
|
|
self.config = json.load(f)
|
|
|
|
# 验证配置
|
|
is_valid, error = ConfigValidator.validate_config(self.config)
|
|
if not is_valid:
|
|
logging.error(f"Invalid configuration: {error}")
|
|
# 尝试从备份恢复
|
|
backup_path = self.config_path + ".bak"
|
|
if os.path.exists(backup_path):
|
|
logging.warning("Attempting to load from backup configuration")
|
|
with open(backup_path, 'r') as f:
|
|
self.config = json.load(f)
|
|
is_valid, error = ConfigValidator.validate_config(self.config)
|
|
if not is_valid:
|
|
raise ValueError(f"Backup config also invalid: {error}")
|
|
else:
|
|
raise ValueError(f"Invalid configuration: {error}")
|
|
|
|
return True, None
|
|
except Exception as e:
|
|
logging.error(f"Failed to load config: {e}")
|
|
self.config = {"plcs": []}
|
|
return False, str(e)
|
|
|
|
def get_config(self):
|
|
"""获取当前配置"""
|
|
return self.config
|
|
|
|
def validate_config(self, config):
|
|
"""验证配置是否有效"""
|
|
return ConfigValidator.validate_config(config)
|
|
|
|
def save_config(self, new_config):
|
|
"""保存配置文件"""
|
|
try:
|
|
# 验证配置
|
|
is_valid, error = self.validate_config(new_config)
|
|
if not is_valid:
|
|
return False, f"Invalid configuration: {error}"
|
|
|
|
# 备份旧配置
|
|
backup_path = self.config_path + ".bak"
|
|
if os.path.exists(self.config_path):
|
|
with open(self.config_path, 'r') as src, open(backup_path, 'w') as dst:
|
|
dst.write(src.read())
|
|
|
|
# 保存新配置
|
|
with open(self.config_path, 'w') as f:
|
|
json.dump(new_config, f, indent=2)
|
|
|
|
self.config = new_config
|
|
return True, None
|
|
except Exception as e:
|
|
logging.error(f"Failed to save config: {e}")
|
|
return False, str(e)
|
|
|
|
def reload_config(self):
|
|
"""重新加载配置"""
|
|
return self.load_config() |