Scripts/PLACE DPMS/dpm_mapping.py
2025-09-19 10:39:48 +04:00

134 lines
4.9 KiB
Python

"""
!!! CHANGE THE INPUT_FILE VARIABLE TO THE PATH OF THE TEXT FILE! LINE 20 !!!
!!! ALSO EXAMPLES_DIR VARIABLE TO THE PATH OF THE EXAMPLES FOLDER! LINE 21 !!!
IF YOU WANT TO RUN THIS SCRIPT, YOU NEED TO HAVE A TXT FILE WITH THE FOLLOWING FORMAT:
MCM_NAME
DPM_NAME1 DPM_IP1
DPM_NAME2 DPM_IP2
...
DPM_NAMEN DPM_IPN
MCM_NAMEN
...
"""
import os
import shutil
import json
# Get the directory where this script is located
# input_file = fr"C:\Users\your_username\Desktop\SCRIPTS\PLACE DPMS\dpm_mapping.txt"
# examples_dir = fr"C:\Users\your_username\Desktop\SCRIPTS\PLACE DPMS\EXAMPLES"
# rt_folder =fr"{examples_dir}\RT"
script_dir = os.path.dirname(os.path.abspath(__file__))
input_file = os.path.join(script_dir, "dpm_mapping.txt")
examples_dir = os.path.join(script_dir, "EXAMPLES")
rt_folder = os.path.join(examples_dir, "RT")
def parse_mcm_data(file_path):
"""Parse input file and return MCMs with their DPMs."""
mcms = {}
current_mcm = None
with open(file_path, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
if line.startswith('MCM'):
current_mcm = line
mcms[current_mcm] = []
elif current_mcm and (' ' in line or '\t' in line):
dpm_name, dpm_ip = line.split('\t' if '\t' in line else ' ', 1)
mcms[current_mcm].append((dpm_name.strip(), dpm_ip.strip()))
return mcms
def create_mcm_folders(mcms, output_dir="."):
"""Create MCM folders with view.json, resource.json, and thumbnail.png."""
for mcm_name, dpms in mcms.items():
print(f"Processing {mcm_name} with {len(dpms)} DPMs...")
# Create folder
mcm_folder = os.path.join(output_dir, mcm_name)
os.makedirs(mcm_folder, exist_ok=True)
# Get template and update view.json
template_file = os.path.join(examples_dir, f"DPM{len(dpms)}", "view.json")
if not os.path.exists(template_file):
print(f"Template for DPM{len(dpms)} not found")
continue
with open(template_file, 'r') as f:
view_data = json.load(f)
# Build tagProps per rules:
# - Index 0: System/{mcm}/{mcm}
# - Index 1..N: System/{mcm}/IO_BLOCK/DPM/{dpm_name} following the provided list order
tag_props = [f"System/{mcm_name}/Rack"]
tag_props.extend([f"System/{mcm_name}/IO_BLOCK/DPM/{dpm_name}" for dpm_name, _ in dpms])
if 'params' not in view_data:
view_data['params'] = {}
view_data['params']['tagProps'] = tag_props
# Update DPM names in view data
if 'root' in view_data and 'children' in view_data['root']:
dpm_index = 0
label_index = 0
for child in view_data['root']['children']:
if child.get('type') == 'ia.display.view' and dpm_index < len(dpms):
dpm_name, _ = dpms[dpm_index]
if 'params' in child.get('props', {}) and 'view' in child['props']['params']:
view_path = child['props']['params']['view']
path_parts = view_path.split('/')
if len(path_parts) >= 2:
path_parts[-2] = mcm_name # Replace MCM name
path_parts[-1] = dpm_name # Replace DPM name
child['props']['params']['view'] = '/'.join(path_parts)
child['meta']['name'] = dpm_name
dpm_index += 1
elif child.get('type') == 'ia.display.label' and label_index < len(dpms):
dpm_name, dpm_ip = dpms[label_index]
child['props']['text'] = f"{dpm_name} {dpm_ip}"
label_index += 1
# Write view.json
with open(os.path.join(mcm_folder, "view.json"), 'w') as f:
json.dump(view_data, f, indent=2)
# Copy RT files
for file_name in ["resource.json", "thumbnail.png"]:
source = os.path.join(rt_folder, file_name)
dest = os.path.join(mcm_folder, file_name)
if os.path.exists(source):
shutil.copy2(source, dest)
def main():
"""Main function to process input file and create MCM folders."""
if not os.path.exists(input_file):
print(f"Error: File '{input_file}' not found.")
return
mcms = parse_mcm_data(input_file)
if not mcms:
print("No MCM data found.")
return
# Create OUTPUT folder
output_folder = "MCMs"
os.makedirs(output_folder, exist_ok=True)
print(f"Created output folder: {os.path.abspath(output_folder)}")
print(f"Found {len(mcms)} MCMs")
create_mcm_folders(mcms, output_folder)
print("Completed successfully, check the MCMs folder!")
if __name__ == "__main__":
main()