From d925255e53eaa148330c1c8139239072a1877c78 Mon Sep 17 00:00:00 2001 From: Philip Gaber Date: Sun, 15 Dec 2024 19:46:00 +0100 Subject: [PATCH] init: working poc --- fix_entity_names.py | 100 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 fix_entity_names.py diff --git a/fix_entity_names.py b/fix_entity_names.py new file mode 100644 index 0000000..c44be36 --- /dev/null +++ b/fix_entity_names.py @@ -0,0 +1,100 @@ +import json +from argparse import ArgumentParser + +parser = ArgumentParser() +parser.add_argument( + "-s", + "--storage", + dest="storage_path", + default="/srv/homeassistant/config/.storage", + type=str, + help="Path to storage", +) +parser.add_argument( + "-y", + "--skip_confirm", + default=False, + dest="skip_confirm", + action="store_true", + help="Skip confirm", +) +try: + args = parser.parse_args() +except: + exit(1) + + +def collect_devices() -> dict[str, str]: + devices: dict[str, str] = {} + with open(f"{args.storage_path}/core.device_registry") as devices_file: + raw_devices = json.load(devices_file) + + for d in filter( + lambda x: x["name_by_user"] != None, raw_devices["data"]["devices"] + ): + devices[d["id"]] = d["name_by_user"] + + return devices + + +def collect_entities() -> list[dict]: + with open(f"{args.storage_path}/core.entity_registry") as entities_file: + entities = json.load(entities_file)["data"]["entities"] + + return entities + + +def valid_entity_id(inp: str) -> str: + return ( + inp.lower() + .replace(" ", "_") + .replace("-", "_") + .replace("/", "_") + .replace("\\", "_") + ) + + +def confirm(msg): + yon = input(f"{msg} (y/n): ") + return True if yon == "y" else False + + +def main(): + devices = collect_devices() + entities = collect_entities() + + for e in entities: + if e["device_id"] in devices: + old = e["entity_id"] + suffix = valid_entity_id(e["original_name"]) + prefix = e["entity_id"].split(".")[0] + name = valid_entity_id(devices[e["device_id"]]) + new = f"{prefix}.{name}_{suffix}" + + if old != new: + print(f"{old} -> {new}") + if not args.skip_confirm: + if confirm("Do you want to replace the name for this entity?"): + e["entity_id"] = new + else: + e["entity_id"] = new + + with open(f"{args.storage_path}/core.entity_registry") as entities_file, open( + "debug.json", "w" + ) as of: + entities_object = json.load(entities_file) + entities_object["data"]["entities"] = entities + + json.dump(entities_object, of) + + with open(f"{args.storage_path}/core.entity_registry", "w") as entities_file: + if confirm("Check 'debug.json' if the output looks reasonable then confirm"): + json.dump(entities_object, entities_file) + print("Replaced 'core.entity_registry' with the contents of debug.json") + else: + print( + "Nothing changed. You could try to fix debug.json and replace the original file with it." + ) + + +main() \ No newline at end of file