#declare the controllable devices
bb_low = new BlackBody("COM34", "1234")
bb_high = new BlackBody("COM34", "4321")
motor_rail = new MotorRail("COM12")
cc = new ClimateChamber("192.168.5.6")
cam = new Bidentifier("192.168.10.20", "root", "root")

# NOTE: functions log, make_dir, write_file are system functions,
# that the recipe can use. Same applies to BlackBody, MotorRail,
# ClimateChamber and Bidentifier Classes

# set starting params
cc_temp = -20 
motor_rail_pos_low = 1000
motor_rail_pos_high = 5000
temp_delta = 2
cc_temp_step = 5
nucs_dir = session_dir + "nucs\\"

def get_int_time_based_on_temp(temp):
    if temp < -10:
        return 16000
    elif -10 <= temp <= 10:
        return 20000
    elif 10 <= temp <= 30:
        return 25000
    else:
        return 30000

def make_nuc(slot, cc_temp):
    log("Producing nuc for slot:", slot)
    slot_dir = nucs_dir + f"nuc_{i}\\"
    make_dir(slot_dir)

    # set params
    log(f"Setting chamber temp to: {cc_temp}.") 
    cc.set_temperature(cc_temp)
    cam.set_slot(slot)
    int_time = get_int_time_based_on_temp(cc_temp)
    log(f"Setting int time to: {int_time}.") 
    cam.set_integration_time(int_time)
    
    # wait for the temperature to settle
    cc.wait_until_temperature_reached()
    bb_low.wait_until_temperature_reached()
    bb_high.wait_until_temperature_reached()

    log(f"Climate chamber temp {cc_temp} reached.") 

    #make the low part of the NUC
    motor_rail.set_position(motor_rail_pos_low)
    cam.make_2pnuc_low()

    #make the low part of the NUC
    motor_rail.set_position(motor_rail_pos_high)
    cam.make_2pnuc_high()

    #create the NUC
    cam.make_2p_nuc_calc()

    # save NUC to flash
    cam.save_nuc(slot)

    # save log data
    cam.download_nuc_raw(slot_dir + "nuc_raw")
    cam.download_nuc(slot_dir + "nuc.bin")

    # make snapshots at both locations
    status_path = slot_dir + "status.txt"
    cam.make_snapshot(slot_dir + "snapshot_high.png")
    status_high = cam.get_vpb_status()
    motor_rail.set_position(motor_rail_pos_low)
    cam.make_snapshot(slot_dir + "snapshot_low.png")
    status_low = cam.get_vpb_status()

    # write status info
    write_file(status_path, "-----Low temp status-----", status)
    write_file(status_path, status_low)
    write_file(status_path, "-----High temp status-----")
    write_file(status_path, status_high)

    log("Status Low:\n", status_low)
    log("Status High:\n", status_high)

    log("---------------------")

# configure the black bodies
bb_low.set_diff_temp(0)
bb_high.set_diff_temp(10)

log("Starting calibrating procedure!")
make_dir(nucs_dir)

for slot in range(0, 12):
    make_nuc(slot, cc_temp)

    #increment temperature
    cc_temp += cc_temp_step

log("Calibrating procedure is done!")
