#!/usr/bin/env python3
"""Convert a debugger capture, never a calibration/permission certificate."""
import argparse,csv,struct,sys
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument("dump");p.add_argument("--epoch-before",required=True,type=lambda x:int(x,0));p.add_argument("--epoch-after",required=True,type=lambda x:int(x,0));args=p.parse_args()
if not(0<=args.epoch_before<=0xffffffff and args.epoch_before==args.epoch_after and args.epoch_before%2==0):p.error("capture publication incomplete or changed; read again")
data=Path(args.dump).read_bytes()
if len(data)!=80:p.error("expected exactly 80 bytes")
v=struct.unpack("<20I",data)
if v[0]!=1 or v[2]>1 or v[3]>5 or v[19]!=0:p.error("unsupported/invalid diagnostic record")
if v[3]!=0 and any(v[12:17]):p.error("invalid conversion contains nominal results")
keys="version captured_ms adc_available measurement_status ntc_raw led_v_raw led_i_raw vrefint_raw first_sample_ms completed_ms adc_sequence factory_vrefint_cal estimated_vdda_uv nominal_led_uv nominal_led_current_ua nominal_ntc_ohm quality_flags input_available_bits input_bits physical_calibration_verified".split()
keys+= ["instrument_vdda_uv","instrument_led_uv","instrument_led_current_ua","instrument_ntc_ohm","instrument_temperature_c","board_serial","instrument_id","operator","notes"]
w=csv.writer(sys.stdout);w.writerow(keys);w.writerow(list(v)+[""]*9)
