class_name ems extends Panel

## Предзагрузка ячеек таблиц.
@export var TableHeader: PackedScene
@export var TableLabel: PackedScene
@export var CellYemsButton: PackedScene
@export var CellLineEdit: PackedScene
@export var CellState: PackedScene
@export var CellOptBtn: PackedScene
@export var CellLEEmpty: PackedScene
@export var CellFront: PackedScene
@export var CellFrontRear: PackedScene

## Режимы работы выходов.
const OUT_MODE: Array = ['Работа', 'Контроль', '0', '1']            #
const COLUMN_OPTS_BTN: Array = [5]
const TABLE_ENTRY_COLUMNS: Array = [2,3]
var OUT_SET_ROW: Array
var IN_SET_ROW: Array

var FILES_ROWS_TYPES: Array

var g_boards: Dictionary		## Словарь плат ЭМС.
var active_board = null         ## Активная плата ЭМС
var posx: int = 125				## Позиция элементов по x.
var posy: int = 70				## Позиция элементов по y.


func _ready() -> void:
    call_deferred('init_boards')


## Инициализация основных элементов экрана ЭМС.
func init_boards():
    OUT_SET_ROW = [CellLineEdit, CellLEEmpty, CellLEEmpty, CellLEEmpty, CellLEEmpty, CellLEEmpty]
    IN_SET_ROW = [CellLineEdit, CellLEEmpty, CellLEEmpty, CellLEEmpty, CellLEEmpty]
    FILES_ROWS_TYPES = [CellLineEdit, CellLineEdit, CellLineEdit ]
    var unit_ems = network.get_unit_instance('уарэп-эмс')

    # Выставление позиций элементов ЭМС на экране
    $scrollin.set_position(Vector2(posx,posy))
    $scrollout.set_position(Vector2(posx + 650,posy))
    $scrl_in_set.set_position(Vector2(posx,posy + 700))
    $scrl_out_set.set_position(Vector2(posx + 650,posy + 700))
    $lbl_online.set_position(Vector2(posx,posy - 60))
    $btn_flash_read.set_position(Vector2(posx,posy + 900))
    $btn_flash_write.set_position(Vector2(posx,posy + 935))
    $btn_connect.set_position(Vector2(posx + 590,posy - 25))
    $btn_disconnect.set_position(Vector2(posx + 587,posy + 675))

    g_boards[yemsconsts.KEMS_BOARD_NAME] = yemsboards.EmsBoard.new(0, 0x130, yemsconsts.INPUT_KEMS, yemsconsts.OUTPUT_KEMS, unit_ems)
    g_boards[yemsconsts.EMS1_BOARD_NAME] = yemsboards.EmsBoard.new(1, 0x110, yemsconsts.INPUT_EMS1, yemsconsts.OUTPUT_EMS1, unit_ems)
    g_boards[yemsconsts.EMS2_BOARD_NAME] = yemsboards.EmsBoard.new(2, 0x120, yemsconsts.INPUT_EMS2, yemsconsts.OUTPUT_EMS2, unit_ems)

    active_board = g_boards[yemsconsts.KEMS_BOARD_NAME]

    init_tbl_in()
    $scrollin/tbl_in.pin_header($scrollin, self)
    init_tbl_out()
    $scrollout/tbl_out.pin_header($scrollout, self)
    $scrl_in_set/tbl_in_set.pin_header($scrl_in_set, self)
    $scrl_out_set/tbl_out_set.pin_header($scrl_out_set, self)
    init_tbl_files()
    $scrl_files/tbl_files.pin_header($scrl_files, self)

    unit_ems.connect('data_received', Callable(self, 'on_data_ems_received'))
    unit_ems.connect('command_done', Callable(self, 'on_command_done'))
    unit_ems.connect('line_changed', Callable(self, 'on_line_changed'))
    for board in g_boards.values():
        board.connect('upd_delay_offset', Callable(self, 'on_upd_delay_offset'))
        board.connect('upd_o_state', Callable(self, 'on_upd_o_state'))
    $btn_connect.connect('pressed', Callable(self, 'on_btn_connect'))
    $btn_disconnect.connect('pressed', Callable(self, 'on_btn_disconnect').bind(unit_ems))
    $btn_flash_read.button_connect('pressed', Callable(self, 'on_btn_flash_read').bind($btn_flash_read))
    $btn_flash_write.button_connect('pressed', Callable(self, 'on_btn_flash_write').bind($btn_flash_write))



## Обработчик нажатия кнопки disconnect.
func on_btn_disconnect(unit_ems):
    var selected_rows_in: Array = []
    var selected_rows_out: Array = []
    $scrl_in_set/tbl_in_set.get_selected_rows(selected_rows_in)
    $scrl_out_set/tbl_out_set.get_selected_rows(selected_rows_out)
    if not active_board.read_done:
        return
    if len(selected_rows_in):
        on_disconnect($scrl_in_set/tbl_in_set, selected_rows_in, unit_ems)
    elif len(selected_rows_out):
        on_disconnect($scrl_out_set/tbl_out_set, selected_rows_out, unit_ems)


## Разрывает связь входа и выхода, [param tbl] - таблица, [param selected_rows] - выбранные строки.
## [param type_dev] - тип, 'вход' или 'выход'.
func on_disconnect(tbl, selected_rows, unit_ems):
    var o_dev: yemsdevs.OutDev
    var i_dev: yemsdevs.InDev
    var dev = tbl.get_node_user_data(0, 0)
    if dev is yemsdevs.OutDev:
        o_dev = dev
        i_dev = tbl.get_node_user_data(0, selected_rows[0])
    else:
        i_dev = dev
        o_dev = tbl.get_node_user_data(0, selected_rows[0])
    if not unit_ems.online or not g_boards[tbl.get_node_user_data(0, selected_rows[0]).board].online:
        return
    i_dev.connect_devs.erase(o_dev.dev_name)
    o_dev.connect_devs.erase(i_dev.dev_name)
    active_board = g_boards[tbl.get_node_user_data(0, selected_rows[0]).board]
    active_board.set_connection(o_dev.id, i_dev.id, false)
    set_in_dev(i_dev)
    set_out_dev(o_dev)



## Обработчик нажатия кнопки "Прочитать".
func on_btn_flash_read(btn):
    await get_tree().create_timer(0.1).timeout
    btn.pressed = false
    for board in g_boards.values():
        board.need_flash_rd = true
    log.message(log.INFO, 'Произведено чтение настроек ЭМС из flash памяти')


## Обработчик нажатия кнопки "Записать".
func on_btn_flash_write(btn):
    await get_tree().create_timer(0.1).timeout
    btn.pressed = false
    for board in g_boards.values():
        board.need_flash_wr = true
    log.message(log.INFO, 'Произведена запись настроек ЭМС в flash память')


## Инициализация таблицы с файлами настроек ЭМС.
func init_tbl_files():
    check_dir()
    $scrl_files/tbl_files.set_header([TableHeader, TableHeader, TableHeader])
    $scrl_files/tbl_files.set_header_text(['Имя файла', 'Размер', 'Дата изменения'])
    $scrl_files/tbl_files.set_columns_min_size([200, 120, 70])
    tools.fill_files_table($scrl_files/tbl_files, yemsconsts.files_folder, FILES_ROWS_TYPES)
    $scrl_files/tbl_files.set_columns_alignments(yemsconsts.FILES_ROWS_ALIGNMENT)
    $scrl_files/tbl_files.set_columns_min_size(yemsconsts.FILES_COLUMN_WIDTHS)
    $scrl_files/tbl_files.connect('row_pressed', Callable(self, 'on_pressed_file'))
    for i_row in $scrl_files/tbl_files.get_rows_count():
        disable_edit($scrl_files/tbl_files, len(FILES_ROWS_TYPES), i_row)


## Инициализация таблиц входов.
func init_tbl_in():
    # Инициализация основной таблицы входов, в ней отображается информация о параметрах и состоянии
    var header_type: Array = [TableHeader, TableHeader, CellFront, CellFrontRear, TableHeader]
    var header_text: Array = ['Входы', 'Соединитель', 'мкс', 'мкс', 'Состояние']
    var row_type: Array = [CellLineEdit, CellLineEdit, CellLineEdit, CellLineEdit, CellState]
    var yams_alligment_in: Array = [ HORIZONTAL_ALIGNMENT_LEFT,  HORIZONTAL_ALIGNMENT_CENTER, HORIZONTAL_ALIGNMENT_CENTER, HORIZONTAL_ALIGNMENT_CENTER, HORIZONTAL_ALIGNMENT_CENTER]
    var column_size: Array = [250, 100, 70, 70, 50]
    $scrollin/tbl_in.set_header(header_type)
    $scrollin/tbl_in.set_header_text(header_text)
    for board in g_boards:
        for item in g_boards[board].in_tbl:
            $scrollin/tbl_in.add_row(row_type)
            var row_index : int = $scrollin/tbl_in.get_rows_count() - 1
            var params : Array = item[1]
            var in_dev: yemsdevs.InDev = yemsdevs.InDev.new(item[0], params, row_index, g_boards[board].base_addr_isa)
            g_boards[board].in_devs[in_dev.id] = in_dev
            in_dev.board = board
            for i in len(row_type):
                if i < len(params):
                    var node = $scrollin/tbl_in.get_node2(i, row_index)
                    if i == 0:
                        node.text = board + ': ' + params[i]
                    elif i in TABLE_ENTRY_COLUMNS:
                        if board == yemsconsts.EMS1_BOARD_NAME or board == yemsconsts.EMS2_BOARD_NAME:
                            node.text = ''
                        else:
                            node.text = '%3.1f' % float(params[i])
                    else:
                        node.text = params[i]
                    node.editable = false
                $scrollin/tbl_in.set_node_user_data(i, row_index, [in_dev, board])
    $scrollin/tbl_in.set_columns_alignments(yams_alligment_in)
    $scrollin/tbl_in.set_columns_min_size(column_size)
    $scrollin/tbl_in.connect('row_pressed', Callable(self, 'on_row_pressed_in'))
    $scrollin/tbl_in.connect('selected_changed', Callable(self, 'on_selected_changed_in'))

    # Инициализация таблицы изменения параметров входа и списка выходов связанных с ним
    header_text[0] = 'Вход'
    $scrl_in_set/tbl_in_set.set_header(header_type)
    $scrl_in_set/tbl_in_set.set_header_text(header_text)
    $scrl_in_set/tbl_in_set.set_columns_alignments(yams_alligment_in)
    $scrl_in_set/tbl_in_set.set_columns_min_size(column_size)
    $scrl_in_set/tbl_in_set.connect('row_pressed', Callable(self, 'on_row_pressed_si'))
    $scrl_in_set/tbl_in_set.connect('selected_changed', Callable(self, 'on_selected_changed_si'))


## Обработчик редактирования Entry в таблице параметров входов/выходов.
func on_edit_entry(text : String, args):
    var entry = args[0]
    var tbl = args[1]
    var dev = args[2]
    var indexis = tbl.get_key_indexes(args[0].name)
    var col_i = indexis[0]
    var read = true
    var is_delay = true
    var val = float(text)
    if text.is_valid_float():
        var max_val = 0
        if col_i == yemsconsts.I_COL_DELAY:
            max_val = yemsconsts.MAX_VAL_DELAY
        else:
            max_val = yemsconsts.MAX_VAL_OFFSET
            is_delay = false
        if val > max_val:
            val = max_val
        elif val < 0:
            val = 0.0
        entry.set_text(str('%3.1f' % val))
        read = false
    else:
        if col_i == yemsconsts.I_COL_DELAY:
            entry.set_text(str('%3.1f' % dev.delay))
        else:
            entry.set_text(str('%3.1f' % dev.offset))
    if active_board.read_done and g_boards[dev.board].online:
        active_board = g_boards[dev.board]
        active_board.set_delay(dev.id, val, is_delay, read)


## Обработчик выбора строки в таблице входов.
func on_selected_changed_in(i_row: int):
    var selecter_rows: Array = []
    $scrollin/tbl_in.get_selected_rows(selecter_rows)
    var user_data = $scrollin/tbl_in.get_node_user_data(0, i_row)
    var dev = user_data[0]
    set_in_dev(dev)


## Обработчик нажатия на таблицу входов.
func on_row_pressed_in(i_row: int):
    on_row_pressed(i_row, $scrollin/tbl_in, true)
    on_selected_changed_in(i_row)


##  Выбор входного устройства, для отображения в таблице соединений входа и изменения параметров.
func set_in_dev(dev):
    var row_type: Array = [CellLineEdit, CellLineEdit, CellLineEdit, CellLineEdit, CellState]
    set_dev($scrl_in_set/tbl_in_set, dev, row_type, IN_SET_ROW, 'Список соединённых выходов :', [250, 100, 70, 70, 70])


## Обработчик выбора строки в таблице соединений входа и изменения параметров.
func on_selected_changed_si(i_row: int):
    if i_row < 2:
        return
    var out_user_data = $scrl_in_set/tbl_in_set.get_node_user_data(0, i_row)
    var dev = out_user_data
    var connector = dev.connector
    for i in $scrollout/tbl_out.get_rows_count():
        var node = $scrollout/tbl_out.get_node2(1, i)
        if connector == node.text:
            on_row_pressed_out(i)


## Обработчик нажатия на таблицу соединений входа и изменения параметров.
func on_row_pressed_si(i_row: int):
    if i_row < 2:
        return
    on_row_pressed(i_row, $scrl_in_set/tbl_in_set, true)
    on_selected_changed_si(i_row)


## Инициализация таблиц выходов.
func init_tbl_out():
    # Инициализация основной таблицы выходов, в ней отображается информация о параметрах и состоянии
    var header_text = ['Выходы', 'Соединитель', 'мкс', 'мкс', 'Состояние', 'Режим']
    var yams_alligment_out: Array = [ HORIZONTAL_ALIGNMENT_LEFT,  HORIZONTAL_ALIGNMENT_CENTER, HORIZONTAL_ALIGNMENT_CENTER, HORIZONTAL_ALIGNMENT_CENTER, HORIZONTAL_ALIGNMENT_CENTER, HORIZONTAL_ALIGNMENT_CENTER]
    $scrollout/tbl_out.set_header([TableHeader, TableHeader, CellFront, CellFrontRear, TableHeader, TableHeader])
    $scrollout/tbl_out.set_header_text(header_text)
    for board in g_boards:
        for item in g_boards[board].out_tbl:
            $scrollout/tbl_out.add_row([CellLineEdit, CellLineEdit, CellLineEdit, CellLineEdit, CellState, CellLineEdit])
            var row_index : int = $scrollout/tbl_out.get_rows_count() - 1
            var params : Array = item[1]
            var out_dev = yemsdevs.OutDev.new(item[0], params, row_index, g_boards[board].base_addr_isa)
            g_boards[board].out_devs[out_dev.id] = out_dev
            out_dev.set_default_mode()
            out_dev.board = board
            for i in len(header_text):
                var cell = $scrollout/tbl_out.get_node2(i, row_index)
                if i < len(params):
                    if i == 0:
                        cell.text = board + ': ' + params[i]
                    elif i in TABLE_ENTRY_COLUMNS:
                        if board == yemsconsts.EMS1_BOARD_NAME or board == yemsconsts.EMS2_BOARD_NAME:
                            cell.text = ''
                        else:
                            cell.text = '%3.1f' % float(params[i])
                    else:
                        cell.text = params[i]
                    cell.editable = false
                $scrollout/tbl_out.set_node_user_data(i, row_index, [out_dev, board])
                if i in COLUMN_OPTS_BTN:
                    cell.text = OUT_MODE[out_dev.mode]
                    cell.editable = false
    $scrollout/tbl_out.set_columns_min_size([250, 100, 70, 70, 70, 100])
    $scrollout/tbl_out.set_columns_alignments(yams_alligment_out)
    $scrollout/tbl_out.connect('row_pressed', Callable(self, 'on_row_pressed_out'))
    $scrollout/tbl_out.connect('selected_changed', Callable(self, 'on_selected_changed_out'))

    # Инициализация таблицы изменения параметров выхода и списка входов связанных с ним
    header_text[0] = 'Выход'
    $scrl_out_set/tbl_out_set.set_header([TableHeader, TableHeader, CellFront, CellFrontRear, TableHeader, TableHeader])
    $scrl_out_set/tbl_out_set.set_header_text(header_text)
    $scrl_out_set/tbl_out_set.set_columns_min_size([250, 100, 70, 70, 70, 100])
    $scrl_out_set/tbl_out_set.connect('row_pressed', Callable(self, 'on_row_pressed_so'))
    $scrl_out_set/tbl_out_set.connect('selected_changed', Callable(self, 'on_selected_changed_so'))


## Обработчик выбора строки в таблице соединений выхода и изменения параметров.
func on_selected_changed_so(i_row: int):
    if i_row < 2:
        return
    var in_user_data = $scrl_out_set/tbl_out_set.get_node_user_data(0, i_row)
    var dev = in_user_data
    var connector = dev.connector
    for i in $scrollin/tbl_in.get_rows_count():
        var node = $scrollin/tbl_in.get_node2(1, i)
        if connector == node.text:
            on_row_pressed_in(i)


## Обработчик нажатия на таблицу соединений выхода и изменения параметров.
func on_row_pressed_so(i_row: int):
    if i_row < 2:
        return
    on_row_pressed(i_row, $scrl_out_set/tbl_out_set, true)
    on_selected_changed_so(i_row)


## Обработчик выбора строки в таблице выходов.
func on_selected_changed_out(i_row: int):
    var selecter_rows: Array = []
    $scrollout/tbl_out.get_selected_rows(selecter_rows)
    var user_data = $scrollout/tbl_out.get_node_user_data(0, i_row)
    var dev = user_data[0]
    set_out_dev(dev)


## Обработчик выбора строки в таблице выходов.
func on_row_pressed_out(i_row: int):
    on_row_pressed(i_row, $scrollout/tbl_out, true)
    on_selected_changed_out(i_row)


##  Выбор выходного устройства, для отображения в таблице соединений выхода и изменения параметров.
func set_out_dev(dev):
    var row_type: Array = [CellLineEdit, CellLineEdit, CellLineEdit, CellLineEdit, CellState, CellOptBtn]
    set_dev($scrl_out_set/tbl_out_set, dev, row_type, OUT_SET_ROW, 'Список соединённых входов :', [250, 100, 70, 70, 70, 100])
    var mode = $scrl_out_set/tbl_out_set.get_node2(5, 0)
    for opt in OUT_MODE:
        mode.add_item(opt)
    mode.connect('item_selected', Callable(self, 'on_switch_done').bind(dev))
    mode.select(dev.mode)


## Выбор входного или выходного устройства.[br]
## [param tbl] - таблица,[br]
## [param dev] - устройство,[br]
## [param row_type] - массив с типами колонок,[br]
## [param row_type_conn] - массив с пустыми LineEdit,[br]
## [param lbl_text] - текст отображаемый во 2 строке: пример: ('Список соединённых входов :').[br]
func set_dev(tbl, dev, row_type, row_type_conn, lbl_text, row_size):
    tbl.clear_rows()
    tbl.add_row(row_type)
    tbl.set_columns_min_size(row_size)
    var le_name: LineEdit = tbl.get_node2(0, 0)
    le_name.editable = false
    le_name.text = dev.board + ': ' + dev.dev_name
    var connector: LineEdit = tbl.get_node2(1, 0)
    connector.editable = false
    connector.text = dev.connector
    var delay: LineEdit = tbl.get_node2(2, 0)
    delay.text = '%3.1f'%dev.delay
    var offset: LineEdit = tbl.get_node2(3, 0)
    offset.text = '%3.1f'%dev.offset
    if dev.board == yemsconsts.EMS1_BOARD_NAME or dev.board == yemsconsts.EMS2_BOARD_NAME:
        delay.text = ''
        delay.editable = false
        offset.text = ''
        offset.editable = false
    else:
        delay.editable = true
        offset.editable = true
    var state = tbl.get_node2(4, 0)
    state.set_frame(dev.state)
    tbl.add_row(row_type_conn)
    var lbl: LineEdit = tbl.get_node2(0, 1)
    lbl.text = lbl_text
    for i in len(row_type_conn):
        var le: LineEdit = tbl.get_node2(i, 1)
        tbl.set_node_user_data(i, 0, dev)
        le.editable = false

    for i in dev.connect_devs:
        var dev_con = dev.connect_devs[i]
        tbl.add_row(row_type_conn)
        var node_index: Array = [0, tbl.get_rows_count() -1]
        var le_name_out: LineEdit = tbl.get_node2(node_index[0], node_index[1])
        disable_edit(tbl, len(row_type_conn), node_index[1])
        le_name_out.text = dev_con.dev_name
        tbl.set_node_user_data(node_index[0], node_index[1], dev.connect_devs[i])
    tbl.connect_columns(self, 'text_submitted', 'on_edit_entry', TABLE_ENTRY_COLUMNS, [tbl, dev])


## Обработчик нажатия кнопки connect.
func on_btn_connect():
    var in_row_index: Array = []
    var out_row_index: Array = []
    $scrollin/tbl_in.get_selected_rows(in_row_index)
    $scrollout/tbl_out.get_selected_rows(out_row_index)
    if len(in_row_index) and len(out_row_index):
        var in_user_data = $scrollin/tbl_in.get_node_user_data(0, in_row_index[0])
        var out_user_data = $scrollout/tbl_out.get_node_user_data(0, out_row_index[0])
        if in_user_data[1] != out_user_data[1] or not active_board.read_done:
            return
        var in_dev = in_user_data[0]
        var out_dev = out_user_data[0]
        add_connection_dev($scrl_out_set/tbl_out_set, in_dev, out_dev, OUT_SET_ROW, in_user_data)
        add_connection_dev($scrl_in_set/tbl_in_set, out_dev, in_dev, IN_SET_ROW, out_user_data)


## Образует связь между выбранным входом и выходом.[br]
## [param tbl] - таблица,[br]
## [param dev1] - устройство1,[br]
## [param dev2] - устройство 2,[br]
## [param set_row] - массив с пустыми LineEdit,[br]
## [param user_data] - пользовательские данные устройства1.[br]
func add_connection_dev(tbl, dev1, dev2, set_row, user_data):
    if not dev1.dev_name in dev2.connect_devs:
        tbl.add_row(set_row)
        var node_index: Array = [0, tbl.get_rows_count() -1]
        var le_name: LineEdit = tbl.get_node2(node_index[0], node_index[1])
        le_name.text = dev1.dev_name
        disable_edit(tbl, len(set_row), node_index[1])
        tbl.set_node_user_data(node_index[0], node_index[1], user_data[0])
        dev2.connect_devs[dev1.dev_name] = dev1
        if dev1 is yemsdevs.OutDev:
            active_board = g_boards[user_data[1]]
            active_board.set_connection(dev1.id, dev2.id, true)


## Отключает возможность редактирования LineEdit в таблице.[br]
## [param tbl] - таблица,[br]
## [param num_col] - номер колонки,[br]
## [param i_row] - номер столбца.[br]
func disable_edit(tbl, num_col: int, i_row: int):
    for col in num_col:
        var node: LineEdit = tbl.get_node2(col, i_row)
        node.editable = false


## Обработчик выбора строки с таблице.
func on_row_pressed(i_row: int, tbl, set_selected: bool):
    tbl.clear_rows_selected()
    var is_row_selected = tbl.is_row_selected(i_row)
    if set_selected:
        tbl.set_row_selected(i_row, true)
    else:
        tbl.set_row_selected(i_row, not is_row_selected)


## Обработчик получения пакета от ячейки ЯУ-07Б
func on_data_ems_received(unit_ems):
    for board in g_boards.values():
        board.set_status(unit_ems.status)
        if active_board.state_board == active_board.WAIT and active_board.state_cmd == active_board.WAIT:
            if board.online and not board.read_done:
                active_board = board
                active_board.state_board = active_board.READ
                active_board.start_rw_kems(true)
            elif board.online and board.read_done and board.need_flash_rd:
                active_board = board
                active_board.state_board = active_board.READ_FLASH
                active_board.read_flash()
            elif board.online and board.read_done and board.need_flash_wr:
                active_board = board
                active_board.state_board = active_board.WRITE_FLASH
                active_board.write_flash()
            elif board.online and board.read_done and board.need_write:
                active_board = board
                active_board.state_board = active_board.WRITE
                active_board.start_rw_kems(false)
    for i_row in $scrollin/tbl_in.get_rows_count():
        var state_pic = ($scrollin/tbl_in.get_node2(4, i_row))
        var dev = $scrollin/tbl_in.get_node_user_data(4, i_row)[0]
        state_pic.set_frame(dev.state)
    for i_row in $scrollout/tbl_out.get_rows_count():
        var state_pic = ($scrollout/tbl_out.get_node2(4, i_row))
        var dev = $scrollout/tbl_out.get_node_user_data(4, i_row)[0]
        state_pic.set_frame(dev.state)
    if $scrl_in_set/tbl_in_set.get_rows_count():
        var dev = $scrl_in_set/tbl_in_set.get_node_user_data(0, 0)
        var state_pic = $scrl_in_set/tbl_in_set.get_node2(4, 0)
        state_pic.set_frame(dev.state)
    if $scrl_out_set/tbl_out_set.get_rows_count():
        var dev = $scrl_out_set/tbl_out_set.get_node_user_data(0, 0)
        var state_pic = $scrl_out_set/tbl_out_set.get_node2(4, 0)
        state_pic.set_frame(dev.state)

## Обработчик выполнения команды
func on_command_done(unit_ems):
    active_board.on_command_done(unit_ems)


## Вызывается по изменению статуса ячейки ЯУ-07Б
func on_line_changed(unit_ems):
    if unit_ems.online:
        $lbl_online.text = 'Ячейка ЯУ-07 на связи'
        $lbl_online.modulate = Color.GREEN
    else:
        $lbl_online.text = 'Ячейка ЯУ-07 не на связи'
        $lbl_online.modulate = Color.RED
        for board in g_boards.values():
            board.state_board = board.WAIT
            board.read_done = false


## Вызывается по обновлению информации от ячейки времянках входов/выходов
func on_upd_delay_offset(_board, dev):
    if dev.board == yemsconsts.EMS1_BOARD_NAME or dev.board == yemsconsts.EMS2_BOARD_NAME:
        return
    var tbl = $scrollin/tbl_in
    if dev is yemsdevs.OutDev:
        tbl = $scrollout/tbl_out
    var le_delay = tbl.get_node2(TABLE_ENTRY_COLUMNS[0], dev.tbl_row_id)
    var le_offset = tbl.get_node2(TABLE_ENTRY_COLUMNS[1], dev.tbl_row_id)
    le_delay.set_text(str('%3.1f' % dev.delay))
    le_offset.set_text(str('%3.1f' % dev.offset))
    if $scrl_in_set/tbl_in_set.get_rows_count():
        var sel_dev = $scrl_in_set/tbl_in_set.get_node_user_data(0, 0)
        var l_delay = $scrl_in_set/tbl_in_set.get_node2(2, 0)
        var l_offset = $scrl_in_set/tbl_in_set.get_node2(3, 0)
        l_delay.set_text(str('%3.1f' % sel_dev.delay))
        l_offset.set_text(str('%3.1f' % sel_dev.offset))
    if $scrl_out_set/tbl_out_set.get_rows_count():
        var sel_dev = $scrl_out_set/tbl_out_set.get_node_user_data(0, 0)
        var l_delay = $scrl_out_set/tbl_out_set.get_node2(2, 0)
        var l_offset = $scrl_out_set/tbl_out_set.get_node2(3, 0)
        l_delay.set_text(str('%3.1f' % sel_dev.delay))
        l_offset.set_text(str('%3.1f' % sel_dev.offset))


## Вызывается по обновлению информации о режиме выходов
func on_upd_o_state(board, dev):
    var le_mode = $scrollout/tbl_out.get_node2(COLUMN_OPTS_BTN[0], dev.tbl_row_id)
    le_mode.set_text(OUT_MODE[dev.mode])
    dev.connect_devs.clear()
    for in_d in board.in_devs.values():
        if in_d.connect_devs.has(dev.dev_name):
            in_d.connect_devs.erase(dev.dev_name)
    for in_id in dev.btns_state:
        if dev.btns_state[in_id] and board.in_devs.has(in_id):
            var in_dev = board.in_devs[in_id]
            in_dev.connect_devs[dev.dev_name] = dev
            dev.connect_devs[in_dev.dev_name] = in_dev
    if $scrl_out_set/tbl_out_set.get_rows_count():
        var sel_dev = $scrl_out_set/tbl_out_set.get_node_user_data(0, 0)
        var mode = $scrl_out_set/tbl_out_set.get_node2(5, 0)
        mode.set_text(OUT_MODE[sel_dev.mode])



## Вызывается при выборе режима работы выхода
func on_switch_done(mode, dev):
    var board = g_boards[dev.board]
    if active_board.state_board == active_board.WAIT and board.online:
        active_board = board
        active_board.change_mode(dev.id, mode)


## Проверяет ниличие директории, если их нет, создаёт
func check_dir():
    var dir = DirAccess.open(yemsconsts.files_folder)
    if dir:
        check_files()
    else:
        DirAccess.make_dir_absolute(yemsconsts.files_folder)
        check_files()


## Проверяет наличие файлов, если их нет, создаёт
func check_files():
    for file in yemsconsts.FILES_NAME:
        var fd = FileAccess.open(yemsconsts.files_folder + file, FileAccess.READ)
        if fd:
            fd.close()
        else:
            fd = FileAccess.open(yemsconsts.files_folder + file, FileAccess.WRITE)
            fd.close()


## Обработчик выбора строки с таблице
func on_pressed_file(i_row: int):
    $scrl_files/tbl_files.clear_rows_selected()
    var is_row_selected = $scrl_files/tbl_files.is_row_selected(i_row)
    $scrl_files/tbl_files.set_row_selected(i_row, not is_row_selected)


## Вызываеттся по нажатию кнопки сохранить настройки в файл
func _on_btn_save_pressed() -> void:
    var sel_row: Array = []
    $scrl_files/tbl_files.get_selected_rows(sel_row)
    if sel_row:
        var fl_node = $scrl_files/tbl_files.get_node2(0, sel_row[0])
        var fl_name = fl_node.text
        var file = FileAccess.open(yemsconsts.files_folder + fl_name, FileAccess.WRITE)
        var json_data: Dictionary = {}
        fill_json_data(json_data)
        var json = JSON.stringify(json_data)
        file.store_string(json)
        file.close()
        for i_row in $scrl_files/tbl_files.get_rows_count():
            $scrl_files/tbl_files.remove_row(0)
        tools.fill_files_table($scrl_files/tbl_files, yemsconsts.files_folder, FILES_ROWS_TYPES)
        $scrl_files/tbl_files.set_columns_alignments(yemsconsts.FILES_ROWS_ALIGNMENT)
        $scrl_files/tbl_files.set_columns_min_size(yemsconsts.FILES_COLUMN_WIDTHS)
        for i_row in $scrl_files/tbl_files.get_rows_count():
            disable_edit($scrl_files/tbl_files, len(FILES_ROWS_TYPES), i_row)
        log.message(log.INFO, 'Произведено сохранение настроек ЭМС в файл: %s' %fl_name)


## Заполняет данными словарь устройств для упаковки в JSON
func fill_json_data(json_data: Dictionary):
    for board in g_boards.values():
        var devs: Dictionary = {}
        json_data[board.id_board] = devs
        for in_dev in board.in_devs.values():
            json_data[board.id_board][in_dev.id] = in_dev.ports_data
        for out_dev in board.out_devs.values():
            json_data[board.id_board][out_dev.id] = out_dev.ports_data


## Вызываеттся по нажатию кнопки загрузить настройки из файла
func _on_btn_load_pressed() -> void:
    var sel_row: Array = []
    $scrl_files/tbl_files.get_selected_rows(sel_row)
    if sel_row:
        var fl_node = $scrl_files/tbl_files.get_node2(0, sel_row[0])
        var fl_name = fl_node.text
        var file = FileAccess.open(yemsconsts.files_folder + fl_name, FileAccess.READ)
        if file == null:
            return
        var read = file.get_as_text()
        file.close()
        var json_conv: = JSON.new()
        if Error.OK == json_conv.parse(read):
            var json_data = json_conv.get_data()
            for board in g_boards.values():
                if not json_data.has(str(board.id_board)):
                    return
                var data = json_data[str(board.id_board)]
                var read_ok = board.btn_load(data)
                if read_ok:
                    board.need_write = true
                    log.message(log.INFO, 'Произведено чтение настроек ЭМС из файла: %s, для платы %s' %[fl_name, board.id_board])
                else:
                    log.message(log.ERROR, 'Ошибка чтение настроек ЭМС из файла: %s' %fl_name)
