-- 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: I2C升级CPLD所需smc命令字
local smc = require 'protocol.smc'
local log = require 'mc.logging'

local smc_interface = {}
smc_interface.__index = smc_interface

function smc_interface.new(chip)
    local obj = {}
    obj.chip = chip

    return setmetatable(obj, smc_interface)
end

function smc_interface:blkwrite(cmd, data)
    local ok = pcall(smc.chip_blkwrite, self.chip, cmd, data)
    if not ok then
        log:debug("SMC write to chip fail")
        return false
    end
    return true
end

function smc_interface:blkread(cmd, len)
    return pcall(smc.chip_blkread, self.chip, cmd, len)
end

function smc_interface:get_cpld_upgrade_info()
    -- func=0, command=0x60, ms=0, rw=1, param=0
    local cmd = 0x00002500
    local ok, rsp = self:blkread(cmd, 2)
    if not ok or not rsp then
        log:error('[Cpld]get cpld upgrade info failed, error:%s', rsp)
        return rsp
    end
    return string.sub(rsp, 1, 1):byte()
end

function smc_interface:get_cpld_manufature()
    local cmd = 0x00018500
    local ok, rsp = self:blkread(cmd, 7)
    if not ok or not rsp then
        log:error('[Cpld]get cpld manufature failed, error:%s', rsp)
        return
    end
    return string.sub(rsp, 3, 3):byte()
end

return smc_interface