import json from pathlib import Path from pydantic import BaseModel from iottb.models.device_metadata_model import DeviceMetadata from iottb.definitions import DEVICE_METADATA_FILE def write_device_metadata_to_file(metadata: DeviceMetadata, device_path: Path): '''Write the device metadata to a JSON file in the specified directory.''' meta_file_path = device_path / 'meta.json' meta_file_path.write_text(metadata.json(indent=2)) def confirm_device_metadata(metadata: DeviceMetadata) -> bool: '''Display device metadata for user confirmation.''' print(metadata.json(indent=2)) return input('Confirm device metadata? (y/n): ').strip().lower() == 'y' def get_device_metadata_from_user() -> DeviceMetadata: '''Prompt the user to enter device details and return a populated DeviceMetadata object.''' device_name = input('Device name: ') device_short_name = device_name.lower().replace(' ', '-') return DeviceMetadata(device_name=device_name, device_short_name=device_short_name) def initialize_device_root_dir(device_name: str) -> Path: '''Create and return the path for the device directory.''' device_path = Path.cwd() / device_name device_path.mkdir(exist_ok=True) return device_path def write_metadata(metadata: BaseModel, device_name: str): '''Write device metadata to a JSON file.''' meta_path = Path.cwd() / device_name / DEVICE_METADATA_FILE meta_path.parent.mkdir(parents=True, exist_ok=True) with meta_path.open('w') as f: json.dump(metadata.dict(), f, indent=4) def get_device_metadata(file_path: Path) -> DeviceMetadata | None: '''Fetch device metadata from a JSON file.''' if dev_metadata_exists(file_path): with file_path.open('r') as f: device_metadata_json = json.load(f) try: device_metadata = DeviceMetadata.from_json(device_metadata_json) return device_metadata except ValueError as e: print(f'Validation error for device metadata: {e}') else: # TODO Decide what to do (e.g. search for file etc) print(f'No device metadata at {file_path}') return None def search_device_metadata(filename=DEVICE_METADATA_FILE, start_dir=Path.cwd(), max_parents=3) -> Path: pass # TODO def dev_metadata_exists(file_path: Path) -> bool: if file_path.is_file(): return True else: return False