import re
import json

def parse_datatype(text):
    datatypes = ["int16", "uint16", "int32", "uint32", "int64", "uint64"]
    for index, datatype in enumerate(datatypes):
        left, separator, right = text.partition(datatype)
        if len(separator) != 0:
            return datatype, left + right
    return "",  text


def parse_from_file(filename):
    data = ""
    with open(filename, "r", encoding='utf-8') as f:  # 打开文件
        linedata = ""
        for line in f:  # 行遍历
            line = line.strip()
            #linedata = f.readline()  # 读取文件的一行
            flag = bool(re.search(r'0x[0-9A-Fa-f]{4}', line))
            linedata += line.strip()
            if flag:
                # print(linedata)
                # left, separator, right = linedata.partition("0x")
                parts = re.split(r'(0x[0-9A-Fa-f]{4})', linedata)
                linedata = ""

                key = parts[1]
                datatype, remark = parse_datatype(parts[0].strip())
                remark = remark.replace("\t", " ").replace("\"", "")

                item = {}
                item["key"] = key
                item["datatype"] = datatype
                item["remark"] = remark

                if len(data) > 0:
                    data += ",\n"    
                data += ("\t\t\t" + json.dumps(item, ensure_ascii=False))
    return data


addritems = {} 
addritems["EMS_YT"] = ["EMS遥调.txt", 1]
addritems["BCU_YX"] = ["BCU电池簇遥信.txt", 1]
addritems["BCU_YC"] = ["BCU电池簇遥测.txt", 1]
addritems["BMS_YC"] = ["BMS电池堆遥测.txt", 1]
addritems["EMS_YX"] = ["EMS遥信.txt", 1]
addritems["EMS_YC"] = ["EMS遥测.txt", 1]
addritems["EMS_YT"] = ["EMS遥调.txt", 1]
addritems["PCS_YX"] = ["PCS遥信.txt", 1]
addritems["PCS_YC"] = ["PCS遥测.txt", 1]
addritems["PCU_YX"] = ["PCU遥信.txt", 1]
addritems["PCU_YC"] = ["PCU遥测.txt", 1]
addritems["MEM_YC"] = ["多功能电表遥测.txt", 1]
addritems["TH_YC"] = ["温湿度状态遥测.txt", 1]
addritems["Fire40_YX"] = ["消防4.0遥信.txt", 1]
addritems["Cooling_YX"] = ["冷机遥信.txt", 1]
addritems["Cooling_YC"] = ["冷机遥测.txt", 1]


with open('registeraddr.json', 'w', encoding='utf-8') as f:
    f.write("{")
    index = 0
    for key in addritems:
        filename = addritems[key][0]
        count = addritems[key][1]
        print("parse: ", key, filename)
        data = parse_from_file(filename)
        if len(data) > 0:
            data = "\n" + data + "\n\t"
        if index != 0:
            f.write(",")
        f.write("\n\t\"" + key + "\": {\n\t\t\"count\":" + str(count) + ",\n\t\t\"addr\":[" + data + "\t]\n\t}")
        index+=1
    f.write("\n}")

