-- 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 skynet = require 'skynet'
local utils = require 'mc.utils'
local log = require 'mc.logging'
local gpio = require "libsoc_adapter.gpio"
local log_def = require 'macros.log_def'
local get_interrupt = gpio.get_interrupt
local GPIO_AC_LOST_INT_NUM <const> = log_def.GPIO_AC_LOST_INT_NUM
local ACLOST_TASK_DELAY <const> = log_def.ACLOST_TASK_DELAY
local SLEEP_STEP <const> = 500

local TEST_MODE <const> = {
    NONE = 0,
    UT = 1,
    IT = 2
}

local g_test_mode = TEST_MODE.NONE

skynet.register_protocol {
    name = "gpio",
    id = 98,
    pack = skynet.pack,
    unpack = skynet.unpack
}

local function sleep(work, timeout)
    while timeout > 0 and work:is_running() do
        utils.msleep(SLEEP_STEP)
        timeout = timeout - SLEEP_STEP
    end
end

return function(work)
    local drv = gpio.new()
    drv:init(log_def.GPIO_AC_LOST_ACT_NUM, 0)
    drv:set_interrupt(GPIO_AC_LOST_INT_NUM, 1)

    log:notice("Gpio drive start")
    while work:is_running() do
        local ok, _ = pcall(get_interrupt, drv, GPIO_AC_LOST_INT_NUM, 0xffffffff, 0)
        if ok then
            log:notice("Send gpio ac lost signal")
            skynet.send('.power_mgmt', 'gpio', 1)
        end

        sleep(work, ACLOST_TASK_DELAY)
    end

    log:notice("gpio drive end")
end