from pathlib import Path import toml from logger import get_log _log = get_log() class Config: config_path = Path("config.toml") def __init__(self): if not Config.config_path.exists(): self.create_config_file() config_content = self.load_config() broker_settings = config_content.get("broker", {}) self.broker_address = broker_settings.get("address", "pythagodzilla.pw") self.broker_port = broker_settings.get("port", 1883) self.broker_username = broker_settings.get("username", "") self.broker_password = broker_settings.get("password", "") def create_config_file(self): """ """ default_config = { "broker": { "address": "pythagodzilla.pw", "port": 1883, "username": "", "password": "" } } try: with open(self.config_path, "w", encoding="utf-8") as config_file: toml.dump(default_config, config_file) _log.info(f"已创建默认配置文件{Config.config_path}") except Exception as e: _log.exception(f"创建配置文件失败: {e}") def load_config(self): """ Load the configuration from the config file. """ try: with open(self.config_path, "r") as config_file: config = toml.load(config_file) return config except FileNotFoundError: _log.exception(f"配置文件 {self.config_path} 不存在。") return None except toml.TomlDecodeError as e: _log.exception(f"配置文件解析错误: {e}") return None except Exception as e: _log.exception(f"加载配置文件失败: {e}") return None