【intelhex】python從hex文件獲取版本號(hào)

from intelhex import IntelHex
import logging
import argparse


def handle_argument():
    """獲取腳本輸入?yún)?shù)

    Returns:
        _type_: Namespace(參數(shù))
    """
    parser = argparse.ArgumentParser(
        description="獲取MCU底軟版本號(hào)", usage="%(prog)s [options]"
    )
    parser.add_argument("--hex_file_path", type=str, required=True, help="hex文件路徑")
    return parser.parse_args()


# 日志初始化
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    encoding="utf-8",
)
logger = logging.getLogger(name="GetMcuVersion")


def hex2dec(hex_number):
    """16進(jìn)制轉(zhuǎn)10進(jìn)制

    Args:
        hex_number (_type_): _description_

    Returns:
        _type_: _description_
    """
    return int(hex_number, 16)


def get_hexversion_from_hexfile(hexFilePath):
    """從hex文件中讀取十六進(jìn)制版本號(hào)

    Args:
        hexFilePath (_type_): _description_

    Returns:
        _type_: _description_
    """
    # 創(chuàng)建一個(gè)IntelHex對(duì)象
    hex_file = IntelHex()

    # 加載HEX文件
    try:
        hex_file.loadhex(hexFilePath)
        logger.info("HEX文件加載成功。")
    except FileNotFoundError:
        logger.info("未找到指定的HEX文件。")
    except Exception as e:
        logger.info(f"加載HEX文件時(shí)出錯(cuò):{e}")

    # 讀取指定地址的字節(jié)
    address = 0x0077FC10
    if address in hex_file.addresses():
        data = hex_file.getsz(address)
        # print(f"addr的類型是:{type(data)}")
        logger.info(f"地址 0x{address:08X} 的數(shù)據(jù)是:{data.hex()}")
        logger.info(f"MCU底軟版本號(hào)對(duì)應(yīng)的十六進(jìn)制數(shù)據(jù)是:{data.hex()[0:4]}")
        return data.hex()[0:4]
    else:
        logger.info(f"地址 0x{address:08X} 未在HEX文件中定義。")


def get_decversion_from_hexversion(version_hex):
    """十六進(jìn)制版本號(hào)轉(zhuǎn)換成最終需要的版本號(hào)格式

    Args:
        version_hex (_type_): _description_

    Returns:
        _type_: _description_
    """
    version_dec = hex2dec(version_hex)
    mcu_version = (
        str(version_dec)[0:1]
        + "."
        + str(version_dec)[1:3]
        + "."
        + str(version_dec)[3:5]
    )
    logger.info(f"MCU底軟版本號(hào)是:{mcu_version}")
    return mcu_version


if __name__ == "__main__":
    # 獲取入?yún)?    args = handle_argument()
    version_hex = get_hexversion_from_hexfile(args.hex_file_path)
    mcu_version = get_decversion_from_hexversion(version_hex)
    print(mcu_version)
python intelhexDemo.py --hex_file_path="D:\hello.hex"
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容