-- 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.


local class = require 'mc.class'
local c_ieu = require 'unit_manager.class.unit.ieu.ieu'
local log = require 'mc.logging'
local cmn = require 'common'

---@class RiserCard: IEU @Riser卡
local c_riser_card = class(c_ieu)

local UNAVAILABLE <const> = 'N/A'
local UPGRADING <const> = 1

local function update_mcu_status(obj)
    if not obj.mcu_obj then
        return
    end

    -- mcu写flash时中断无法响应，升级时不查询升级状态
    if obj.mds_obj and obj.mds_obj.CurrentUpgradeStatus == UPGRADING then
        return
    end

    local state = obj.mcu_obj.interface:query_upgrade_status()
    if state then
        obj:set_prop('Count', 0)        -- 通信成功次数重置成0
        obj:set_prop('CpldStatus', 0)   -- 默认配置成0, 表示没有告警
        return
    end

    local count = obj:get_prop('Count')
    if count < 2 then   -- 三次防抖, 前两次失败后只计数
        obj:set_prop('Count', count + 1)
        return
    end

    -- 连续三次失败后则表示通信失败，更新CpldStatus状态触发告警
    log:info('[Riser] Mcu communication test failed.')
    obj:set_prop('CpldStatus', 1)
end

function c_riser_card:task_update_mcu_status()
    if self:get_prop('MCUVersion') == UNAVAILABLE then
        return
    end
    cmn.skynet.fork(function()
        cmn.skynet.sleep(12000) -- 启动阶段等待2分钟后更新MCU状态
        while true do
            cmn.skynet.sleep(500)
            update_mcu_status(self)
        end
    end)
end

function c_riser_card:task_update()
    self:task_update_mcu_version()
    self:task_update_mcu_status()
end

return c_riser_card