from openpyxl import load_workbook

def read_cell(sheet, row, col):
    val = str(sheet.cell(row, col).value)
    if val == "None":
        val = ""
    return val.strip()

def read_sheet(wb, topic, sht_name):
    sheet = wb[sht_name]
    
    text = ""
    for i in range(2, sheet.max_row+1):
        # print(str(sheet.cell(i, 1).value))
        addr = read_cell(sheet, i, 8)
        name = read_cell(sheet,i, 2)
        datatype = read_cell(sheet,i, 4)
        unit = read_cell(sheet, i, 5)
        is_alert = (read_cell(sheet, i, 7) == "告警")
        remark = read_cell(sheet, i, 6)
        
        if (len(addr) <= 6 and len(addr) >=2 and addr != "寄存器地址"):
            if (len(unit)>0):
                remark += '(' + unit + ')'
            if (len(text)>0):
                text += ',\n'
            text += '\t\t\t{"key": "%s", "datatype": "%s", "alert": %d, "name":"%s", "remark": "%s"}' % (addr, datatype, is_alert, name, remark.replace("\n", ""))
    

    if (len(text)>0):
        text = "\n" + text + "\n\t\t"
    text =  '\t"%s":{\n\t\t"addr":[%s]\n\t}' % (topic, text)
    return text    
            

wb = load_workbook('EMU对外通信点表最终修改1版_v9.xlsx', data_only=True)

text = ""
text = read_sheet(wb, "EMS_YT", "EMS遥调")
text += ',\n' + read_sheet(wb, "EMS_YX", "EMS遥信")
text += ',\n' + read_sheet(wb, "EMS_YC", "EMS遥测")
text += ',\n' + read_sheet(wb, "PCU_YC", "PCU遥测")
text += ',\n' + read_sheet(wb, "PCU_YX", "PCU遥信")
text += ',\n' + read_sheet(wb, "PCS_YC", "PCS遥测")
text += ',\n' + read_sheet(wb, "PCS_YX", "PCS遥信")
text += ',\n' + read_sheet(wb, "BMS_YC", "BMS电池堆遥测")
text += ',\n' + read_sheet(wb, "BCU_YC", "BCU电池簇遥测")
text += ',\n' + read_sheet(wb, "BCU_YX", "BCU电池簇遥信")
# text += ',\n' + read_sheet(wb, "AirC_YC", "空调遥测")
# text += ',\n' + read_sheet(wb, "AirC_YX", "空调遥信")
text += ',\n' + read_sheet(wb, "MEM_YC", "多功能电表遥测")
text += ',\n' + read_sheet(wb, "TH_YC", "温湿度状态遥测")
text += ',\n' + read_sheet(wb, "Fire40_YX", "消防4.0遥信")
text += ',\n' + read_sheet(wb, "Cooling_YC", "冷机遥测")
text += ',\n' + read_sheet(wb, "Cooling_YX", "冷机遥信")
text += ',\n' + read_sheet(wb, "Gateway_YC", "网关遥测")
text += ',\n' + read_sheet(wb, "Gateway_YX", "网关遥信")
text += ',\n' + read_sheet(wb, "Charger_YC", "充电桩遥测")

with open('regaddrs-new.json', 'w', encoding='utf-8') as f:
    f.write("{\n" + text + "\n}")