-- 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 Pca9545 = {}

ADDR_IDX = 1
ADDR_MASK = 0xFE
CONTROL_IDX = 2
CHANNEL_MASK = 0x0F

local function parse_addr(tx_buffer)
    return tx_buffer[ADDR_IDX] & ADDR_MASK
end

local function parse_channel(tx_buffer)
    local channel_state = {}
    if #tx_buffer ~= 2 then -- 2: 9545接收接收命令的长度
        print("command len fail, len=", #tx_buffer)
        return channel_state
    end
    local control = tx_buffer[CONTROL_IDX]
    local channel = control & CHANNEL_MASK
    while channel ~= 0 do
        local b_set = channel & 0x01
        table.insert(channel_state, b_set)
        channel = channel >> 1
    end
    return channel_state
end

function Pca9545.write(tx_buffer)
    local addr = parse_addr(tx_buffer)
    local channel_state = parse_channel(tx_buffer)
    local channel_path = ""
    for i = 1, #channel_state do
        if channel_state[i] == 1 then
            channel_path = string.format("/0x%02x/%d", addr, i - 1)
            break
        end
    end
    local t = {}
    t["hub"] = channel_path
    return t
end

return Pca9545
