Files
gateway_plc/gateway/main.py

109 lines
3.4 KiB
Python

import logging
import time
import threading
from config_loader import load_config
from plc_manager import PLCManager
from cache_manager import CacheManager
from api_server_html import APIServer
from config_manager import ConfigManager
class GatewayApp:
"""PLC网关应用程序主类"""
def __init__(self, config_path="../config/config.json"):
self.config_path = config_path
self.config_manager = ConfigManager(config_path)
self.plc_manager = None
self.cache_manager = None
self.api_server = None
self.reload_flag = False
self.reload_lock = threading.Lock()
self.logger = logging.getLogger("GatewayApp")
# 加载初始配置
self.load_configuration()
def load_configuration(self):
"""加载配置并初始化组件"""
# 加载配置
if not self.config_manager.load_config():
self.logger.error("Failed to load initial configuration")
return False
config = self.config_manager.get_config()
# 重新初始化PLC连接
if self.plc_manager:
self.logger.info("Reinitializing PLC connections...")
self.plc_manager = PLCManager(config["plcs"])
self.plc_manager.connect_all()
# 重新初始化缓存
if self.cache_manager:
self.logger.info("Stopping existing cache manager...")
self.cache_manager.stop()
self.logger.info("Initializing cache manager...")
self.cache_manager = CacheManager(config, self.plc_manager, app=self)
self.cache_manager.start()
# 重新初始化API服务器
if self.api_server:
self.logger.info("API server already running")
else:
self.logger.info("Starting API server...")
self.api_server = APIServer(self.cache_manager, self.config_path)
self.api_server.start()
self.logger.info("Configuration loaded successfully")
return True
def check_for_reload(self):
"""检查是否需要重载配置"""
while True:
with self.reload_lock:
if self.reload_flag:
self.reload_flag = False
self.load_configuration()
time.sleep(1)
def request_reload(self):
"""请求重载配置"""
with self.reload_lock:
self.reload_flag = True
self.logger.info("Configuration reload requested")
def run(self):
"""运行主程序"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s'
)
self.logger.info("Starting PLC Gateway...")
# 启动配置重载检查线程
reload_thread = threading.Thread(
target=self.check_for_reload,
name="ConfigReloadThread",
daemon=True
)
reload_thread.start()
try:
# 保持主程序运行
while True:
time.sleep(1)
except KeyboardInterrupt:
self.logger.info("Shutting down gracefully...")
finally:
if self.cache_manager:
self.cache_manager.stop()
self.logger.info("Shutdown complete")
def main():
app = GatewayApp()
app.run()
if __name__ == "__main__":
main()