-- 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 class = require 'mc.class'
local client = require 'thermal_mgmt.client'
local log = require 'mc.logging'
local Singleton = require 'mc.singleton'

local power_supplies = class()

local POWER_SUPPLIES_PATH<const> = '/bmc/kepler/Chassis/1/PowerSubsystem/PowerSupplies'
function power_supplies:ctor()
    self.power_supplies_obj = nil
end

local function get_power_supplies_obj(self)
    if self.power_supplies_obj then
        return
    end
    local obj = client:GetPowerSuppliesObjects()[POWER_SUPPLIES_PATH]
    if obj and obj.SetPsusFanMinPWM_PACKED then
        self.power_supplies_obj = obj
    end
end

function power_supplies:set_psu_fan_pwm(ctx, value)
    get_power_supplies_obj(self)
    if not self.power_supplies_obj then
        log:debug('Get power supplies obj failed')
        return
    end

    value = math.ceil(value)
    local ok, rsp = pcall(self.power_supplies_obj.SetPsusFanMinPWM_PACKED, self.power_supplies_obj, ctx, value)
    if not ok then
        log:debug('Set all psu fan pwm failed, err_msg: %s', rsp)
    end
end

return Singleton(power_supplies)