@tool

extends 'res://scenes/контроль/элемент-я.gd'


func on_line_changed(unit_instance):
    if not unit_instance.online:
        disable_all()


func on_settings_changed():
    var external_ctl = ProjectSettings.get_setting('application/config/Внешнее управление', false)
    if external_ctl:
        disable_all()


func disable_all():
    state = STATE_VAL.NONE
    $block_output.state0 = STATE_VAL.NONE
    $block_output.state1 = STATE_VAL.NONE
    $block_output.state2 = STATE_VAL.NONE
    $block_input1.state  = STATE_VAL.NONE
    $block_input1.state0 = STATE_VAL.NONE
    $block_input1.state1 = STATE_VAL.NONE
    $block_input1.state2 = STATE_VAL.NONE
    $block_input2.state  = STATE_VAL.NONE
    $block_input2.state0 = STATE_VAL.NONE
    $block_input2.state1 = STATE_VAL.NONE
    $block_input2.state2 = STATE_VAL.NONE


func on_data_received(data: PackedByteArray):

    # Сеть 1. Использование
    $block_input1.state = STATE_VAL.GOOD if data[4] & (1 << 5) else STATE_VAL.ERROR
    # Сеть 1. Вход
    $block_input1.state0 = STATE_VAL.GOOD if ((data[4] & (1 << 1)) == 0) and ((data[4] & (1 << 3)) == 0) else STATE_VAL.ERROR
    # Сеть 1. Неисправность блока инвертора 1 канала
    $block_input1.state1 = STATE_VAL.GOOD if (data[6] & (1 << 2)) == 0 else STATE_VAL.ERROR
    # Сеть 1. Перегрев 1 канала
    $block_input1.state2 = STATE_VAL.GOOD if (data[5] & (1 << 3)) == 0 else STATE_VAL.ERROR

    # Сеть 2. Использование
    $block_input2.state = STATE_VAL.GOOD if data[4] & (1 << 6) else STATE_VAL.ERROR
    # Сеть 2. Вход
    $block_input2.state0 = STATE_VAL.GOOD if ((data[4] & (1 << 2)) == 0) and ((data[4] & (1 << 4)) == 0) else STATE_VAL.ERROR
    # Сеть 2. Неисправность блока инвертора 2 канала
    $block_input2.state1 = STATE_VAL.GOOD if (data[6] & (1 << 3)) == 0 else STATE_VAL.ERROR
    # Сеть 2. Перегрев 2 канала
    $block_input2.state2 = STATE_VAL.GOOD if (data[5] & (1 << 4)) == 0 else STATE_VAL.ERROR

    # Неисправность, напряжение меньше номинального, напряжение выше номинального
    $block_output.state0 = STATE_VAL.GOOD if ((data[4] & (1 << 0)) == 0) and ((data[4] & (1 << 7)) == 0) and ((data[5] & (1 << 2)) == 0) else STATE_VAL.ERROR
    # Перегрузка и короткое замыкание по выходу
    $block_output.state1 = STATE_VAL.GOOD if ((data[5] & (1 << 0)) == 0) and ((data[5] & (1 << 1)) == 0) else STATE_VAL.ERROR
    # Критическая температура
    $block_output.state2 = STATE_VAL.GOOD if ((data[5] & (1 << 5)) == 0) else STATE_VAL.ERROR

    # Обобщённое состояние
    state = STATE_VAL.GOOD \
    if     $block_input1.state1 == STATE_VAL.GOOD \
       and $block_input1.state2 == STATE_VAL.GOOD \
       and $block_input2.state0 == STATE_VAL.GOOD \
       and $block_input2.state1 == STATE_VAL.GOOD \
       and $block_input2.state2 == STATE_VAL.GOOD \
       and $block_output.state0 == STATE_VAL.GOOD \
       and $block_output.state1 == STATE_VAL.GOOD \
       and $block_output.state2 == STATE_VAL.GOOD \
    else STATE_VAL.ERROR
