-- 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.

-- Description: I2cLed类，用于控制不需要用户管理的I2C控制的Led灯
local class = require 'mc.class'
local log = require 'mc.logging'
local skynet = require 'skynet'

local c_led_i2c = class()

local LED_OFF <const> = 0
local LED_ON <const> = 0xff

-- 闪烁
function c_led_i2c:blink_scan()
    if self.state == LED_OFF or self.state == LED_ON or self.on_time == 0 or self.off_time == 0 then
        self.ticks = 0
        return true
    end

    self.ticks = self.ticks + 1
    local period = self.on_time + self.off_time
    if self.ticks >= period then
        self.ticks = self.ticks % period
    end

    if self.ticks < self.off_time then
        self:set_state(LED_OFF)
    else
        self:set_state(LED_ON)
    end
end


function c_led_i2c:set_state(state, on_time, off_time)
    local on_value = self.mds_obj.LedOnValue
    for i = 1, 3 do
        local ok, err = pcall(function()
            if state == LED_OFF then
                self.mds_obj.CtrlValue = LED_OFF
            elseif state == LED_ON then
                self.mds_obj.CtrlValue = on_value
            end
        end)
        if ok then
            break
        else
            log:notice('ok is %s, error:%s', ok, err)
            skynet.sleep(10)
        end
    end

    self.state = state
    self.on_time = on_time or 0
    self.off_time = off_time or 0
end

function c_led_i2c:init()
    self.ticks = 0
    self.state = LED_OFF
    self.on_time = 0
    self.off_time = 0
end

function c_led_i2c:ctor(mds_obj, position)
    self.mds_obj = mds_obj
    self.position = position
end

return c_led_i2c