-- 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: NMI中断(预中断)

local log = require 'mc.logging'
local class = require 'mc.class'
local enums = require 'types.enums'
local utils = require 'types.utils'
local skynet = require 'skynet'

local c_nmi = class()
local MAX_RETRY_TIMES = 3
local NMI_INTERRUPT = 1
local NMI_INTERRUPT_CLEAR = 0

function c_nmi:ctor(object, id)
    self.obj = object
    self.system_id = id
    log:notice_easy("[System:%s]set nmi object successfully, uptime: %s.", id, utils.uptime())
end

function c_nmi:retry_set_nmi_interrupt(value)
    local ok, err
    for _ = 1, MAX_RETRY_TIMES do
        ok, err = pcall(function ()
            self.obj.NmiInt = value
        end)
        if ok then
            return true
        end
        skynet.sleep(10)
        log:error('[System:%s]set nmi interrupt to %s failed, error:%s', self.system_id, value, err)
    end
end

function c_nmi:nmi_interrupt()
    local ok = self:retry_set_nmi_interrupt(NMI_INTERRUPT)
    if not ok then
        log:error_easy('[System:%s]execute nmi interrupt failed', self.system_id)
        return enums.RetValue.ERR
    end
    skynet.sleep(10)
    ok = self:retry_set_nmi_interrupt(NMI_INTERRUPT_CLEAR)
    if not ok then
        log:error_easy('[System:%s]recover nmi interrupt failed', self.system_id)
        return enums.RetValue.ERR
    end
    log:notice_easy('[System:%s]execute nmi interrupt successfully', self.system_id)
    return enums.RetValue.OK
end

return c_nmi