-- 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 ctx = require 'mc.context'
local GET_FAN_PWM_CMD<const>  = 0x18001100

local fans = device_object('Fans')

function fans:ctor()
end

function fans:set_fans_pwm(l_pwm)
    -- 批量下发转速前先下发设置一遍期望转速
    for index = 1, #l_pwm do
        local fan_object = self:get_dev_object('Fan_' .. index)
        fan_object:set_fan_expected_pwm(l_pwm[index])
    end

    local send_data = string.pack(string.rep('B', #l_pwm), table.unpack(l_pwm))
    local ok, resp = pcall(function()
        return self.PWMChip:Write(ctx.get_context_or_default(), self.SetPWMCmd, send_data)
    end)
    if not ok then
        log:info('set fans failed, resp: %s', resp)
        return 1
    end

    return 0
end

function fans:get_fans_pwm(fan_num)
    local ok, resp = pcall(function()
        return self.PWMChip:Read(ctx.get_context_or_default(), GET_FAN_PWM_CMD, fan_num)
    end)
    if not ok then
        log:debug('get fans failed, resp: %s', resp)
        return
    end

    return {string.byte(resp, 1, #resp)}
end

function fans:init()
    self:declare_method('Fans', 'bmc.dev.Fans', 'SetFansPWM', function (...)
        return self:set_fans_pwm(...)
    end)
    self:declare_method('Fans', 'bmc.dev.Fans', 'GetFansPWM', function (...)
        return self:get_fans_pwm(...)
    end)
end

return fans