#include "hal_dfu.h"
#include "system.h"
#include "ble_comm.h"

static uint8_t ScanNameflag =1;
static uint8_t AdvNameflag  =1;

static char AdvNameBuff[NRF_BLE_SCAN_NAME_MAX_LEN] = {0};
static char ScanNameBuff[NRF_BLE_SCAN_NAME_MAX_LEN] = {0};


void hal_setScanName(char *Scanname,uint8_t length){
	if(NULL == Scanname || length > NRF_BLE_SCAN_NAME_MAX_LEN || 0 == length)return;
	memset(ScanNameBuff,0,length);
	memcpy(ScanNameBuff,Scanname,length);
	ScanNameflag =1;
}

void hal_setAdvName(char *advname,uint8_t length){
	if(NULL == advname || length > NRF_BLE_SCAN_NAME_MAX_LEN || 0 == length)return;
	memset(advname,0,length);
	memcpy(advname,advname,length);
	AdvNameflag  =1;
}

void hal_name_process(void){
  static uint8_t Scanstate =0;
	switch(Scanstate){
		case 0:
			    if(ScanNameflag){ScanNameflag=0;
						 Scanstate =1;
						 if(host_isconnect())host_disconnect();
					}
			    break;
		case 1:
          if(host_isconnect()){host_disconnect();}
					else {
						 ST_scan_stop();
						 host_set_scan_name(ScanNameBuff,strlen(ScanNameBuff));
						 ST_scan_start();
						 Scanstate = 0;
					}
			    break;
		default:Scanstate =0;break; 
	}
	
	static uint8_t Advstate =0;
	switch(Advstate){
		case 0:
			    if(ScanNameflag){ScanNameflag=0;
						 Advstate =1;
						 if(slave_isconnect()) slave_disconnect();
					}
			    break;
		case 1:
          if(host_isconnect()){host_disconnect();}
					else {
						 ST_scan_stop();
						 host_set_scan_name(ScanNameBuff,strlen(ScanNameBuff));
						 ST_scan_start();
						 Advstate = 0;
					}
			    break;
		default:Scanstate =0;break; 
	}
}

void hal_name_init(void){
	Process_Start(1000,"hal_name",hal_name_process);
}

