-- 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 ipmi = require 'ipmi'
local comp_code = ipmi.types.Cc
local class = require 'mc.class'
local singleton = require 'mc.singleton'
local msg = require 'thermal_mgmt.ipmi.ipmi_message'
local fan_service = require 'fan_service'
local c_fans_object = require 'fans_object'
local log = require 'mc.logging'

local cpu_ipmi = class()

function cpu_ipmi:ctor()
end

function cpu_ipmi:get_fan_speed(req, ctx, ...)
    local device_number = req['DeviceNumber']
    local device_id = (device_number - 1) // 2 + 1;
    local isRearFan = (device_number - 1) % 2;

    local fan_speed, cc = fan_service.get_instance():get_fan_speed(device_id, isRearFan)

    return msg.GetFanSpeedRsp.new(cc, req.ManufactureId, fan_speed, 7) -- 7代表的单位为转速(RPM)
end

function cpu_ipmi:get_total_fan_power(req, ctx, ...)
    local fan_power_total = 0
    local unit = 106 -- 106代表的单位为0.1瓦特(W)
    if not c_fans_object.collection or not next (c_fans_object.collection) then
        log:error('No fans object found! Get fan power failed!')
        return msg.GetTotalFanPowerRsp.new(comp_code.Success, req.ManufactureId, fan_power_total, unit) -- 失败则返回0
    end
    fan_power_total = math.floor(c_fans_object:get_fans_power() / 10 + 0.5)
    return msg.GetTotalFanPowerRsp.new(comp_code.Success, req.ManufactureId, fan_power_total, unit)
end

return singleton(cpu_ipmi)