# micropython 中使用
import time
import uhashlib
import uos
import ubinascii  # 导入用于转换二进制到十六进制字符串的模块


def calculate_sha256(filename):
    h = uhashlib.sha256()
    with open(filename, 'rb') as f:
        while True:
            chunk = f.read(1024)
            if not chunk:
                break
            h.update(chunk)

    # 获取摘要并转换为十六进制字符串
    hash_bytes = h.digest()  # 获取摘要的二进制形式
    return ubinascii.hexlify(hash_bytes).decode()  # 将二进制摘要转换为十六进制字符串


# 遍历目录
all_file_data = {}


def list_directory(path='.', list_all=False):
    try:
        for entry in uos.ilistdir(path):
            name = entry[0]
            if name == "__pycache__" or name == "temp":
                continue
            type_code = entry[1]
            if type_code == 0x4000:  # 目录标志位，可能根据实现不同
                _type = "dir"
            else:
                _type = "file"
            file_path = "{}/{}".format(path, name)
            # print("_type:{},  {}/{}".format(_type, path, name))
            all_file_data[file_path] = {"_type": _type,
                                        "file": name,
                                        }
            if _type == "dir":
                list_directory(file_path, list_all=True)
    except OSError as e:
        # print("path", path)
        # print(f"{path} Error listing directory: {e}")
        pass


# 示例使用
list_directory('', list_all=True)
# 执行你想要测量的部分代码
for k, v in all_file_data.items():
    if v["_type"] == "file":
        md5_checksum = calculate_sha256(k)
        print("{}@{}".format(k, md5_checksum))
