import threading
from threading import Thread
import time
import menu_utils as utils
from comm_device import class_comm_device
from print_color import *

class class_comm_master_thread(Thread):
    thread_object_id = 0
    CHECK_INTERVAL = 0.05  # 检查间隔（秒）
    MAX_FAIL_TIME = 5  # 最大失败时间（秒）

    def __init__(self, 
                 device_comm_object_list=None,  
                 thread_name="device"):
        super().__init__()
        self.stop_request = False
        self.device_comm_object_list = device_comm_object_list if device_comm_object_list is not None else []
        
        if thread_name is None:
            thread_name = "device" + str(class_comm_master_thread.thread_object_id)
        class_comm_master_thread.thread_object_id += 1

        self.thread_name = thread_name

    def close(self):
        self.stop_request = True

    def run(self):
        print_inform_msg(f"{self.thread_name} modbus 主线程启动")
        
        total_fail_time = 0
        base_time = time.time()
        
        while not self.stop_request:
            comm_success_count = 0
            total_comm_count = 0

            for device in self.device_comm_object_list:
                try:
                    if device.comm_active:
                        success_count, comm_count = device.device_comm_cycle()
                        comm_success_count += success_count
                        total_comm_count += comm_count
                except Exception as err:
                    print_error_msg(err)

            cur_time = time.time()
            
            if comm_success_count > 0:
                total_fail_time = 0
            elif total_comm_count > 0:
                total_fail_time += cur_time - base_time
            base_time = cur_time

            if total_fail_time >= self.MAX_FAIL_TIME:
                self.reconnect_devices()
                total_fail_time = 0  

            time.sleep(self.CHECK_INTERVAL)
            
        print_error_msg(f"{self.thread_name} modbus 主线程停止")

    def reconnect_devices(self):
        """重新连接所有设备的协议"""
        for device in self.device_comm_object_list:
            try:
                device.protocol.close()
            except Exception as err:
                print_error_msg(f"关闭协议时出错: {err}")

        for device in self.device_comm_object_list:
            try:
                device.protocol.open(device.protocol.mode)
            except Exception as err:
                print_error_msg(f"重新打开协议时出错: {err}")
        
        print_warning_msg("与保护器连接超时, 重新进行连接")
