-- 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: imu触发通知Bios触发同步及获取同步状态
local class = require 'mc.class'
local skynet = require 'skynet'
local log = require 'mc.logging'
local singleton = require 'mc.singleton'
local imu_cmd = require 'infrastructure.imu'
local prop_def = require 'macros.property_def'

local ImuSynchronizeBios = class()

function ImuSynchronizeBios:post_synchronize(system_id)
    log:notice('[bios] start post synchronize, system id: %s', system_id)
    local imu_obj = imu_cmd.get_instance()
    local msg = {
        Header = { DestNetFn = 0x30, Cmd = 0x98 },
        Data = {
            SubCmd = 0x29
        },
        SendFormat = [[<<0xDB0700:3/unit:8, SubCmd>>]],
        ReceiveFormat = [[<<ManuId:3/unit:8>>]],
        SystemId = system_id
    }

    for _ = 1, 5 do
        local ok, _ = pcall(function()
            return imu_obj:send_and_receive(msg)
        end)
        if ok then
            return
        end
        skynet.sleep(50)
    end
    log:error('[bios] post synchronize action failed, system id: %s', system_id)
    error(string.format('[bios] post synchronize action failed, system id: %s', system_id))
end

function ImuSynchronizeBios:check_post_synchronize_finished(system_id)
    log:notice('[bios] start check post synchronize state, system id: %s', system_id)
    local imu_obj = imu_cmd.get_instance()
    local msg = {
        Header = { DestNetFn = 0x30, Cmd = 0x98 },
        Data = {
            SubCmd = 0x25
        },
        SendFormat = [[<<0xDB0700:3/unit:8, SubCmd>>]],
        ReceiveFormat = [[<<ManuId:3/unit:8, Status, ErrCode>>]],
        SystemId = system_id
    }

    local ok, rsp
    for _ = 1, 10 do
        ok, rsp = pcall(function()
            return imu_obj:send_and_receive(msg)
        end)
        if ok and rsp then
            if rsp.Status == 0x00 then
                return true
            elseif rsp.Status == 0x01 then
                log:debug('[bios] bios is synchronizing. system id: %s', system_id)
                skynet.sleep(6000)  -- 等待60s
            elseif rsp.Status == 0x02 then
                log:debug('[bios] bios synchronize failed, error: %s, system id: %s',
                    prop_def.SYNCHRONIZE_ERROR_CODE[rsp.ErrCode], system_id)
            end
        end
        skynet.sleep(50)
    end
    log:error('[bios] get synchronize status failed, system id: %s', system_id)
    return false
end

return singleton(ImuSynchronizeBios)