-- 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 bs = require 'mc.bitstring'
local enums = require 'ipmi.enums'
local context = require 'mc.context'
local json = require 'cjson'

local tool = {}
tool.__index = tool

local channel_type = enums.ChannelType
local PKG_IPMI = bs.new('<<_,_:2,DestNetFn:6,_:3/unit:8,Cmd,Payload/string>>')

function tool.new(bus)
    return setmetatable({
        bus = bus
    }, tool)
end

function tool:cmd_test(case)
    local payload = case.payload or '\xdb\x07\x00'
    for word in string.gmatch(case.cmd, "[^%s]+") do
        local w =  string.pack('B', word)
        payload = payload .. w
    end
    local ipmi_req = {
        DestNetFn = 0x30,   -- 填写网络字节码
        Cmd = case.cmd_type or 0x92,  -- 填写命令字, 默为0x92
        Payload = payload .. '\x00'   -- 填写命令参数，默认最后有一位校验位，必须添加
    }
    local req = PKG_IPMI:pack(ipmi_req)
    local ctx = json.encode({ChanType = channel_type.CT_ME:value(), Instance = 0})

    local ok, rsp = pcall(self.bus.call, self.bus, 'bmc.kepler.ipmi_core', '/bmc/kepler/IpmiCore',
        'bmc.kepler.IpmiCore', 'Route', 'a{ss}ayay', context.new(), req, ctx)
    assert(ok, string.format('call cases %s ipmi msg fail', case.info))
    return rsp
end

return tool