/*-------------------------------- PRST ------------------------------
----------------------- Pristupovy registracni system ----------------
----------------------- expcom - expander board driver ----------------
**********************************************************************
*/

#include "expcom.h"


serial_t* serial; 
char ExpTxBuffer[HOST_MAX_PACKET_SIZE];

//Send packet to expander
int ExpanderSend(uint8_t* data, uint16_t length){
    uint16_t checksum=0;
    uint16_t i;
	Guard_regRQ(data[0]);
	ExpTxBuffer[EXPCOM_BORDER_OFFSET] = BORDER_P;
	ExpTxBuffer[EXPCOM_LENGTH_H_OFFSET]=((length+2)>>8);
	ExpTxBuffer[EXPCOM_LENGTH_L_OFFSET]=(length+2);

	//Compute chcecksum
	for(i=0;i<length;i++){
		ExpTxBuffer[EXPCOM_DATA_OFFSET+i] = data[i];
		checksum += data[i];
	}

	ExpTxBuffer[length+3]=((uint8_t)(checksum>>8));
	ExpTxBuffer[length+4]=((uint8_t)(checksum));
	serial_write(serial,ExpTxBuffer,length + EXPCOM_BALAST_SIZE);
	return (1);

}

//Switch FPR on or off
int ExpCom_SwitchFPR(char state){
	uint8_t command[4];
	
	command[0]=EXPOUT_FPR_SWITCH_CMD;
	command[1]=state;
	return(ExpanderSend(command,2));

}


int ExpCom_DeleteFPR(int UserID){
	uint8_t command[4];
	
	command[0]=EXPOUT_FPR_DELETE_CMD;
	command[1]=(uint8_t)(UserID>>8);
	command[2]=(uint8_t)(UserID&0x000000FF);
	return(ExpanderSend(command,3));

}

int ExpCom_DownloadFPR(int UserID, char* ftemplate){
	uint8_t command[285];
	int i=0;	
	
	command[0]=EXPOUT_FPR_DOWNLOAD_CMD;
	command[1]=(uint8_t)(UserID>>8);
	command[2]=(uint8_t)(UserID&0x000000FF);
	printf("Zapisuji na pozici %u %u\n",command[1],command[2]);
	
	for(i=0;i<278;i++){			
		command[i+3]=HexToNum8((char*)(ftemplate + (2*i)));
	}
	return(ExpanderSend(command,281));
}

int ExpCom_BootloadReset(void){
	
	uint8_t command[2];
	
	command[0]=EXPOUT_BOOTLOAD_RESET_CMD;
	return(ExpanderSend(command,1));


}

int ExpCom_ScanFPR(void){
	uint8_t command[4];
	
	command[0]= EXPOUT_FPR_SCAN_CMD;
	return(ExpanderSend(command,1));

}

int ExpCom_SwitchKeybMode(char state){
	uint8_t command[4];
	
	command[0]=EXPOUT_KEYB_MODE_CMD;
	command[1]=state;
	return(ExpanderSend(command,2));

}

