From ee97971f2bd9be57856158e8f40353fc7ac74aef Mon Sep 17 00:00:00 2001 From: Mika Date: Sun, 10 May 2026 02:07:42 +0000 Subject: [PATCH] Add ir_gain_test/src/ir_gain_test/cli.py --- ir_gain_test/src/ir_gain_test/cli.py | 71 ++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 ir_gain_test/src/ir_gain_test/cli.py diff --git a/ir_gain_test/src/ir_gain_test/cli.py b/ir_gain_test/src/ir_gain_test/cli.py new file mode 100644 index 0000000..927b1d7 --- /dev/null +++ b/ir_gain_test/src/ir_gain_test/cli.py @@ -0,0 +1,71 @@ +import argparse +import json +from pathlib import Path +from typing import Any +import sys +from ir_gain_test import core + + +def main() -> None: + """Entry point for IR Gain Analysis CLI.""" + parser = argparse.ArgumentParser( + description=( + "Analyze IR gain values and intensity data from a nighttime line-following robot test." + ) + ) + parser.add_argument( + "--input", + required=True, + help="Path to JSON file containing recorded intensity data.", + ) + parser.add_argument( + "--output", + required=False, + help="Path where analysis report will be saved (JSON).", + ) + + args = parser.parse_args() + + input_path = Path(args.input) + if not input_path.exists() or not input_path.is_file(): + sys.stderr.write(f"Error: Input file '{input_path}' does not exist or is not a file.\n") + sys.exit(1) + + try: + with input_path.open("r", encoding="utf-8") as f: + intensity_data: Any = json.load(f) + except json.JSONDecodeError as e: + sys.stderr.write(f"Error reading input JSON: {e}\n") + sys.exit(1) + + # Validate that intensity_data is a list of dicts + if not isinstance(intensity_data, list) or not all(isinstance(x, dict) for x in intensity_data): + sys.stderr.write("Error: Input data must be a list of JSON objects.\n") + sys.exit(1) + + # Extract gain_values safely + gain_values = sorted(set(float(entry.get("gain_value", 0.0)) for entry in intensity_data)) + + try: + report = core.analyze_ir_gain(gain_values, intensity_data) + except Exception as e: # noqa: BLE001 + sys.stderr.write(f"Analysis failed: {e}\n") + sys.exit(1) + + # Output handling + if args.output: + output_path = Path(args.output) + try: + output_path.parent.mkdir(parents=True, exist_ok=True) + with output_path.open("w", encoding="utf-8") as f: + json.dump(report, f, indent=2) + print(f"Analysis report saved to {output_path}") + except OSError as e: + sys.stderr.write(f"Failed to write output file: {e}\n") + sys.exit(1) + else: + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main()