#include "Comunication.h"
#include "Tab.h"
#include "PWM.h"
#include "usart.h"
#include <Heure.h>

void Sync(){
	uint8_t mes = 0xF0;
	HAL_UART_Transmit(&huart6,&mes,1,1000);
}

uint8_t parse(uint8_t* mes){
	switch(mes[0] & MASKMES){
	case (WRITETABHEU):
		Com_WriteTabHeure(mes);
		return 0;
	case (WRITETABVAL):
		Com_WriteTabVal(mes);
		return 0;
	case (READVENT):
		Com_ReadVent(mes);
		return 0;
	case (WRITVENT):
		Com_WriteVent(mes);
		return 0;
/*	case (ERRORCOM):
		Com_ERROR(mes);
		return 0;*/
	case (WRITEVALESS):
		Com_WriteValEsai(mes);
		return 0;
	case (STOP):
		Com_STOP(mes);
		return 0;
	case (ESSAI):
		Com_ESSAI(mes);
		return 0;
	case (SYNCRTC):
		Com_SyncRTC(mes);
		return 0;
	default:
		return -1;//erreur
	}
}


void ReadMes(FIFO_COM *f,uint8_t* mes){
	uint8_t first = readFirst(f) & MASKMES;
	if (first == STOP|first == ESSAI|first == READVENT|first == WRITVENT)
		readFifo(f,mes,1);
	else if(first == WRITETABVAL|first == WRITEVALESS)
		readFifo(f,mes,2);
	else if(first == WRITETABHEU)
		readFifo(f,mes,3);
	else if (first == SYNCRTC)
		readFifo(f,mes,8);
	else
		while(1); // todo Erreur Synchro entre dans la fifo

}

void Com_WriteTabHeure(uint8_t* mes){
	uint8_t id = mes[0]&MASKID;
	uint16_t h = mes[1]*60 + mes[2];
	if ((mes[0]&MASKTYPE)>>3)
		tabSortie[id].Extinxtion = h;
	else
		tabSortie[id].Demmarage = h;
}

void Com_WriteTabVal(uint8_t* mes){
	uint8_t id = mes[0]&MASKID;
	if ((mes[0] & MASKTYPE )>>3)
		tabSortie[id].Pente=mes[1];
	else
		tabSortie[id].PuissanceMax=mes[1];
}

void Com_ReadVent(uint8_t* mes){

}

void Com_WriteVent(uint8_t* mes){

}
void Com_WriteValEsai(uint8_t* mes){
	uint8_t id = mes[0]&MASKID;
	tabSortie[id].PuissanceEssai = mes[1];

}

void Com_STOP(uint8_t* mes){
	gl_Stop = mes[0]&MASKON;
}

void Com_ESSAI(uint8_t* mes){
	gl_Essai = mes[0]&MASKON;
}

void Com_SyncRTC(uint8_t* mes){
	Date date;
	date.annee=mes[1];
	date.mois=mes[2];
	date.jour=mes[3];
	date.joursemaine=mes[4];
	date.heure=mes[5];
	date.minute=mes[6];
	date.second=mes[7];
	writeDate(&date);
}
