/*user interface*/

#include "ui.h"
#include "hardware.h"

extern struct results_struct results;


void send_ui_message()
{
    U1TXREG = 0xFF;                         //send anything to acquire receiving function on UI side
    send_ui_double((float)results.z_real);
    send_ui_double((float)results.z_imag);
    send_ui_double((float)results.y_real);
    send_ui_double((float)results.y_imag);
    send_ui_double((float)results.z_mod);
    send_ui_double((float)results.z_arg);
    send_ui_double((float)results.y_mod);
    send_ui_double((float)results.y_arg);
}

void send_ui_double(float float_var_to_send)   //send double variable through UART as a series of bits - this must be 32bit float
{
    int32_t temp_int32;                         //float 32bit is coded on int32_t
    const int32_t var_size = 4;                 //float sent in 4 chunks
    int32_t i_shift;
    
    temp_int32 = *((int32_t*)(&float_var_to_send));
    for(i_shift = 0; i_shift < var_size; ++i_shift)
    {
        while(!U1STAbits.TRMT || INT_PORT);      //not transmitting until ui confirms it's ready by setting INT_PORT low
        U1TXREG = (temp_int32 >> (8 * i_shift)) & 0xFF;
    }
}

void get_ui_message(struct config_struct *config)    //all messages from ui are sent through the single byte for simpler synchronization
{
    uint8_t buffer_tmp;                             //buffer that allows to access receive buffer few times (it clears when read(?))
    
    while(!U1STAbits.TRMT);
    while(!U1STAbits.RIDLE);
    buffer_tmp = U1RXREG;
    config->fq_sel = (buffer_tmp & 0x03) >> 0;       //select frequency
    config->amp_sel = (buffer_tmp & 0x0C) >> 2;      //select amplitude
    config->do_the_cal = (buffer_tmp & 0x10) >> 4;   //if set true, calibration should be requested
    config->comp_open = (buffer_tmp & 0x20) >> 5;    //if set true, do open circuit compensation
    config->comp_short = (buffer_tmp & 0x40) >> 6;   //if set true, do short circuit compensation
    config->turn_on_off = (buffer_tmp & 0x80) >> 7;  //if set true, do short circuit compensation
}
