-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

-- Description: 调用驱动的接口封装
local log = require 'mc.logging'
local skynet = require 'skynet'
local defs = require 'unit_manager.class.logic_fw.comm_defs'

local driver = {}
local RETRY_MAX_TIMES = 10

function driver:get_cpld_device_info(chip_info, cpld_info)
    if chip_info == nil then
        log:error('chip info is nil')
        return defs.RET.ERR
    end
    for _ = 1, RETRY_MAX_TIMES do
        local ok, id_list = pcall(function()
            return chip_info:GetChipIdcode(require'mc.context'.new())
        end)
        if ok and #id_list > 0 then
            cpld_info.device_count = #id_list
            for j = 1, cpld_info.device_count do
                cpld_info[string.format('device%d_id', j)] = id_list[j]
            end
            return defs.RET.OK
        end
        skynet.sleep(100)
    end
    return defs.RET.ERR
end

function driver:set_upg_cpld_chip(chip_info, chip_index)
    for _ = 1, RETRY_MAX_TIMES do
        local ok, error = pcall(chip_info.SetTargetNumber, chip_info, require'mc.context'.new(),
            chip_index)
        if ok then
            return
        end
        log:info('set_upg_cpld_chip fail:%s', error)
        skynet.sleep(100)
    end
end

return driver
