"""
This script records current and voltage data from a Joulescope device and saves it to a timestamped file in the 'recordings' directory.
Inline script
"""


from pyjoulescope_driver.record import Record
from pyjoulescope_driver import Driver
import datetime
import time
import os

import logging

SAMPLING_FREQUENCY_HZ = 1000000
logging.basicConfig(level=logging.DEBUG)

def construct_filename(out_dir):
    timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = 'IVT_' + timestamp + '.jls'
    os.makedirs(out_dir, exist_ok=True)
    full_file_path = os.path.join(out_dir, filename)
    return full_file_path


filepath = construct_filename("recordings")

with Driver() as d:
    devices = d.device_paths()
    device = devices[0] # open first device - 
    d.open(device)

    d.publish(f'{device}/s/i/range/mode', 'auto')
    #d.publish(f'{device}/s/i/range/max', '180 mA') # Limits max range to 180mA
    #d.publish(f'{device}/s/i/range/min', '18 µA') # Limits min range to 18µA

    #d.publish(f'{device}/s/i/range/mode', 'manual')
    #d.publish(f'{device}/s/i/range/select', '1.8 mA')
    
    d.publish(f'{device}/s/v/range/mode', 'auto')
    d.publish(f'{device}/h/fs', SAMPLING_FREQUENCY_HZ)

    try:
        print(f'STARTING RECORDER....')
        recorder = Record(d, device, signals = 'current,voltage')
        recorder.open(filepath)
        logging.info("Recording started...")  
        time.sleep(5)
        recorder.close()
        logging.info("Recording ended...")

    except Exception as e:
        logging.error(f'Error: failed to start recording: {e}')
