-- Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
-- 
-- this file licensed under the 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.
-- qlogic和emulex卡使用此协议获取传感器信息

local class = require 'mc.class'
local bs = require 'mc.bitstring'
local log = require 'mc.logging'
local pldm_standard = require 'protocol_open.protocol.pldm_standard'

local pldm_sensor = class(pldm_standard)
local MCTP_PLDM_TYPE_2<const> = 0x02

local response_bs<const> = bs.new([[<<
    data/string
>>]])

local request_bs<const> = bs.new([[<<
    sensor_id:16,
    rearm_event_state:8
>>]])

local request_params_template<const> = {
    command_code = true,
    sensor_id = true,
    data = true
}

function pldm_sensor:construct_request_data(ctx, request)
    local data = request_bs:pack({
        sensor_id = request.sensor_id,
        rearm_event_state = 0x00;
    })
    return pldm_sensor.super.construct_request_data(self, ctx, {
        pldm_type = MCTP_PLDM_TYPE_2,
        command_code = request.command_code,
        rsp_command_code = request.command_code, -- pldm的rsp command code与req command code一致
        data = data .. (request.data or '')
    })
end

function pldm_sensor:unpack_response_data(ctx, rsp_bin)
    if ctx.completion_code and ctx.completion_code ~= 0 then
        log:debug('[protocol %s]: unsuccessful request with completion_code: %s', self.name,
            ctx.completion_code)
        return nil
    end

    local rsp = response_bs:unpack(rsp_bin, true)

    if not rsp then
        log:debug('[protocol %s]: empty data received', self.name)
        return nil
    end
    return rsp.data
end

function pldm_sensor:ctor()
    self.name = 'pldm_sensor'
    self.request_params_template = request_params_template
end

return pldm_sensor
