-- Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. 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.

local skynet = require 'skynet'
local log = require 'mc.logging'
local class = require 'mc.class'
local Singleton = require 'mc.singleton'
local cooling_device_base = require 'basic_cooling.cooling_device.base'
local cooling_fans = class(cooling_device_base)

local FAN_OBJ_ADD_TIMEOUT_TIMES <const> = 30 -- 风扇对象添加超时次数，累计时间为600s
function cooling_fans:init()
    self.super.init(self)
    self.syn_id = 'FanId'
    self.interface = 'bmc.kepler.Systems.CoolingFan'
    self.class_name = 'CoolingFan'
    self.pwm_name = 'HardwarePWM'

    skynet.fork_once(function()
        for i = 1, FAN_OBJ_ADD_TIMEOUT_TIMES, 1 do
            -- 如果风扇对象添加完成直接退出
            if self.obj_add_complete_flag then
                log:notice('Fan object timeout detection exit')
                break
            end
            skynet.sleep(2000)
        end
        local fan_id_string = ''
        for _, fan_obj in pairs(self.obj_table) do
            fan_id_string = fan_id_string .. ' ' .. fan_obj[self.syn_id]
        end
        if self.obj_add_complete_flag == false then
            -- 达到超时时间且风扇板分发缺失时，强制进行一次检测以启动cooling调速服务
            log:notice('Fan object timeout detection starting, expect fan board num: %s, cur fan board num: %s',
                self.board_add_complete_num, self.board_num
            )
            log:notice('%s object id identify result: %s', self.class_name, fan_id_string)
            if self.board_add_complete_num < self.board_num and self.board_add_complete_num ~= 0 then
                self:update_cooling_device_obj_identify_result()
            end
        end
    end)
end

return Singleton(cooling_fans)