-- 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 device_object = require 'mc.mdb.device_tree.device_object'
local log = require 'mc.logging'

local pwm_channel = device_object('PWMChannel')

function pwm_channel:ctor()
    self.fans = {}
end

function pwm_channel:register_fan()
    for _, fan_id in pairs(self.ManageFans) do
        self.fans[fan_id] = self:get_dev_object('Fan_' .. fan_id)
        self.fans[fan_id]:set_pwm_channel(self)
    end
end

function pwm_channel:configurable()
    for _, fan_obj in pairs(self.fans) do
        if fan_obj:is_present() and not fan_obj:is_identified() then
            -- 有未识别的风扇不支持设置
            return false
        end
    end
    return true
end

function pwm_channel:set_fan_expected_pwm(pwm_value)
    for _, obj in pairs(self.fans) do
        obj:set_expected_pwm(pwm_value)
    end
end

function pwm_channel:set_fan_hardware_pwm(pwm_percent)
    for _, obj in pairs(self.fans) do
        obj:set_pwm(pwm_percent)
    end
end

function pwm_channel:set_fan_pwm(pwm_percent)
    if not self:configurable() then
        -- 当前风扇识别失败情况下不允许设置
        log:debug('invalid fan%s/%s identify status', table.unpack(self.ManageFans))
        return 1
    end
    self:set_fan_hardware_pwm(pwm_percent)
    return 0
end

function pwm_channel:start()
    log:notice('[thermal_mgmt_app] pwm_channel manage_fans:' ..
        string.rep(' %d', #self.ManageFans), table.unpack(self.ManageFans))
    self:next_tick(self.register_fan, self)
end

return pwm_channel