-- 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 CommonI2c = {
    buffer = "",
    offset = 0,
    data = {},

    ADDR_IDX = 1,
    OFFSET_IDX = 2,
}

local log = require "log"

function CommonI2c:new(o, buffer, offset_width)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    self.buffer = buffer
    self.offset_width = offset_width
    return o
end

function CommonI2c:parse_offset()
    local offset = 0
    -- offset从第二个字节开始，然后根据位宽计算出其结束为止
    for i = self.OFFSET_IDX, self.OFFSET_IDX + self.offset_width - 1 do
        offset = offset * (2 ^ 8) -- 2 ^ 8: offset左移8位
        offset = offset + self.buffer[i]
    end
    return offset
end

function CommonI2c:parse_data()
    local data = {}
    local i = self.OFFSET_IDX + self.offset_width -- data起始位置
    local j = 1
    while i <= #self.buffer do
        data[j] = self.buffer[i]
        i = i + 1
        j = j + 1
    end
    return data
end

return CommonI2c