#include "frame.h"
#include <stdint.h>
#include "usart.h"

void uart_putc(uint8_t send_char)
{
	HAL_UART_Transmit(&huart1, &send_char, 1, 20);
}

int process_command(struct smeasure *measureData, struct soutputSettings *outputSet) {
	uint8_t	correct = 0,i;
	//check function
	switch ( Buffer.data[0] ) {
		case 0x01:			// Request:	a0x01U		Response:	a'voltage''current''controlMode''enableOutput'U
				//read data
				if ( Buffer.index != 1 ) {
					break;
				}
				
				uart_putc(START_FRAME);
                uart_putc( (uint8_t)(measureData->fvoltage * 10.0) );
                uart_putc( (uint8_t)(measureData->fcurrent * 100.0) );
				uart_putc(outputSet->controlMode);
				uart_putc(outputSet->enableOutput);
				uart_putc(END_FRAME);

				Buffer.flag = 0;
				return 0;
		case 0x02:		// Request:	a0x02'address''data'U
				//write data
				if ( Buffer.index != 3 ) {
					break;
				}
				switch ( Buffer.data[1] ) {
					case 0x01:
							measureData->fvoltage_req = Buffer.data[2] / 10.0;
							correct = 1;
						break;
					case 0x02:
							measureData->fcurrent_req = Buffer.data[2] / 100.0;
							correct = 1;
						break;
				}
			break;
		case 0x03:		//a0x03(0|1)U
			//set enable output
			if ( Buffer.index != 2 ) {
				break;
			}
			outputSet->enableOutput = Buffer.data[1];
            //outputSet->enableOutputChange = 1;
			correct = 1;
			
			break;
	}
	
	if (correct) {
		//send same message back
		uart_putc(START_FRAME);
		for (i = 0; i < Buffer.index; i++) {
			uart_putc(Buffer.data[i]);
		}
		uart_putc(END_FRAME);
		
		Buffer.flag = 0;
		return 0;
	} else {
		//send error message	a0x8XU
		uart_putc(START_FRAME);
        uart_putc(Buffer.data[0] & 0x8F);
		uart_putc(END_FRAME);
		
		Buffer.flag = 0;
		return 1;
	}
}

