-- Copyright (c) 2025 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 log = require 'mc.logging'
local context = require 'mc.context'
local crc32 = require 'mc.crc32'
local _, skynet = pcall(require, 'skynet')

local i3c = {}

-- 通过i3c写命令+数据，返回完成码
function i3c.chip_blkwrite(chip, cmd, data)
    data = string.unpack('L', data)
    local buf = string.pack('I1I3I4I4', 0X20, 4, cmd, data)
    local crc = crc32(buf, 0, true)
    data = string.pack('I4I4', data, crc)
    if not chip then
        log:error('[i3c] chip blkwrite: unknown chip')
        return
    end
    local ok, res = pcall(function ()
        chip:PluginRequest(context.get_context_or_default(), 'compute',
            'plugins_mailbox_write', skynet.packstring(cmd, data))
    end)
    if not ok then
        error(string.format('[i3c] write data failed, error message: %s', res))
    end
end

-- 通过i3c发送读命令+数据长度，返回数据
function i3c.chip_blkread(chip, cmd, len)
    if not chip then
        log:error('[i3c] chip blkread: unknown chip')
        return nil
    end
    local ok, data = pcall(function ()
        return skynet.unpack(chip:PluginRequest(context.get_context_or_default(), 'compute',
            'plugins_mailbox_read', skynet.packstring(cmd, len)))
    end)
    if not ok then
        error(string.format('[i3c]read data failed, error message: %s', data))
    end
    return data
end

return i3c
