Files
ThingsBoard/Code Snippets/compareMistawayTBDevices.py
2025-09-18 16:58:46 -05:00

81 lines
2.7 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
compare_names.py
Compares the `deviceName` values from File1 with the `name` values from File2.
If a `deviceName` does not appear in File2, it is written to *missing.txt*.
"""
import json
import argparse
import sys
from pathlib import Path
def load_json(path: Path):
"""Return the parsed JSON data from *path*."""
try:
with path.open("r", encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
print(f"❌ File not found: {path}", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError as exc:
print(f"❌ Invalid JSON in {path}:\n{exc}", file=sys.stderr)
sys.exit(1)
def extract_device_names_from_file1(data):
"""Return a list of deviceName values from the File1 structure."""
names = []
for mac, obj in data.items():
# Some devices may not have a name; skip them quietly.
name = obj.get("deviceName")
if isinstance(name, str):
names.append(name)
return names
def extract_names_from_file2(data):
"""Return a set of name values from the File2 list."""
names = set()
for entry in data:
name = entry.get("name")
if isinstance(name, str):
names.add(name)
return names
def main(file1_path: Path, file2_path: Path, output_path: Path):
# Load data
data1 = load_json(file1_path)
data2 = load_json(file2_path)
# Pull out the two collections we care about
names_in_file1 = extract_device_names_from_file1(data1)
names_in_file2 = extract_names_from_file2(data2)
# Find names that are missing from File2
missing = [name for name in names_in_file1 if name not in names_in_file2]
# Output
if missing:
print(f"⚠️ Found {len(missing)} device(s) whose name is missing in File2.")
# Write to a text file one name per line
with output_path.open("w", encoding="utf-8") as out:
out.write("\n".join(missing))
print(f"✔️ Missing names written to {output_path}")
else:
print("✅ All deviceNames from File1 are present in File2.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Find deviceName values in File1 that are not present in File2."
)
parser.add_argument("file1", type=Path, help="Path to File1 (JSON dict).")
parser.add_argument("file2", type=Path, help="Path to File2 (JSON list).")
parser.add_argument(
"-o",
"--output",
type=Path,
default=Path("missing.txt"),
help="Where to write the list of missing names (default: missing.txt)",
)
args = parser.parse_args()
main(args.file1, args.file2, args.output)