import modbus_tk.defines as cst
from modbus_tk import modbus_tcp, hooks, modbus

REGISTER_MENU_DISPLAY_PAGE             = 1000
REGISTER_MENU_ITEM_SELECT_MASK         = 1001
REGISTER_MENU_POPUP_MODIFY_ACTIVE      = 1002
REGISTER_MENU_MOVIE_ACTIVE_ID          = 1003
REGISTER_MENU_POSITION_STATUS          = 1004
REGISTER_MENU_STRING_ROW0_COL1         = 1240
REGISTER_MENU_STRING_ROW0_COL0         = 1080
REGISTER_MENU_MODIFY_CAPTION_STRING    = 1020
REGISTER_MENU_MODIFY_STRING            = 1040
REGISTER_MENU_MODIFY_SELECT_STRING     = 1060

BLOCK_REGISTER  = '3'
BLOCK_COIL      = '0'

class class_modbus_tcp_server() :
    def __init__(self, 
                slave_addr = 2,
                slave_ip= "127.0.0.1", 
                slave_port = 502):
        self.slave_addr = slave_addr
        self.slave_ip = slave_ip
        self.slave_port = slave_port

        self.slave_station = None
        self._connect()

        # 创建从站总服务器
        server = modbus_tcp.TcpServer(address=self.slave_ip, port = self.slave_port, timeout_in_sec = 0.5)  # address必须设置,port默认为502

        # 创建从站
        self.slave_station : modbus.Slave = server.add_slave(self.slave_addr)
        
        # 为从站添加存储区
        self.slave_station.add_block(BLOCK_REGISTER, cst.HOLDING_REGISTERS, starting_address = 0, size = 65536)
        self.slave_station.add_block(BLOCK_COIL, cst.COILS, starting_address = 0, size = 65536)
        
        server.start()
    def _connect(self):
        try:
            # 创建从站总服务器
            self.server = modbus_tcp.TcpServer(address=self.slave_ip, port=self.slave_port, timeout_in_sec=0.5)
            # 创建从站
            self.slave_station = self.server.add_slave(self.slave_addr)
            # 为从站添加存储区
            self.slave_station.add_block(BLOCK_REGISTER, cst.HOLDING_REGISTERS, starting_address=0, size=65536)
            self.slave_station.add_block(BLOCK_COIL, cst.COILS, starting_address=0, size=65536)

            self.server.start()
            print("Modbus TCP 服务器连接成功！")
        except Exception as e:
            print("Modbus TCP 服务器连接失败:", e)
    def is_connected(self):
        return self.server != None

    def update_server_register(self, addr, value):
        if self.slave_station:
            self.slave_station.set_values(BLOCK_REGISTER, addr, value)

    def reconnect(self):
        print("正在重启 Modbus TCP 服务器...")
        self.stop()
        self._connect()

    def stop(self):
        if self.server:
            self.server.stop()
            self.server = None
            print("Modbus TCP 服务器停止...")

    def update_server_register(self, addr, value) :
        if self.slave_station :
            self.slave_station.set_values(BLOCK_REGISTER, addr, value)
