import menu_utils as utils
from print_color import *
from comm_protocol_modbus import class_protocol_modbus

class class_comm_cycle_item() :
    def __init__(self, name = "", reg_addr = 0, reg_count = 0, cycle = 0, mqtt_pack = None, remap_addr = 0):
        self.reg_addr = reg_addr
        self.reg_count = reg_count
        self.cycle = cycle
        self.name = name
        self.remain_cycle = 0
        self.comm_delay = 0
        self.comm_count = 0
        self.comm_fail_count = 0
        self.comm_success_count = 0
        self.comm_success = False
        self.comm_trigger = False
        self.mqtt_pack  = mqtt_pack
        self.remap_addr = remap_addr
        self.reg_buf = []

    def in_range(self, reg_addr, reg_count) :
        reg_addr_begin = self.reg_addr
        reg_addr_end = self.reg_addr + self.reg_count 
        if reg_addr >= reg_addr_begin and reg_addr + reg_count <= reg_addr_end :
            return True
        return False
    
    def update_item_value(self, reg_addr, reg_count, new_value) :
        if self.in_range(reg_addr, reg_count) and len(self.reg_buf) :
            reg_off = reg_addr - self.reg_addr
            new_reg = list(self.reg_buf)
            for i in range(reg_count) :
                new_reg[reg_off + i] = new_value[i]
            self.reg_buf = new_reg
            self.comm_trigger = True

    def read_register_count(self, reg_addr, reg_count) :
        reg_addr_begin = self.reg_addr
        reg_addr_end = self.reg_addr + self.reg_count 
        result = None
        if reg_addr >= reg_addr_begin and reg_addr + reg_count <= reg_addr_end :
            if len(self.reg_buf) >= self.reg_count:
                result = []
                reg_off = reg_addr - self.reg_addr
                for i in range(reg_count):
                    result.append(self.reg_buf[reg_off + i])

        return result
