/********************************************************************
  Copyright (c) 2021 Xiangyu Medical Co.，Ltd. All rights reserved.
  FileName : drv_uart.c
  Author   : zhangdawei
  Version  : V1.0
  Date     :
  Note     :
  History  :
********************************************************************/
/* Includes ------------------------------------------------------*/
#include "drv_uart.h"
#include "pca10040.h"
#include "ble_nus.h"
#include "time.h"
#include "IoControl.h"
#include "nrf_drv_timer.h"
#include "fds.h"         
/* Private define ------------------------------------------------*/
BLE_NUS_DEF(m_nus);                     //定义名称为m_nus的串口透传服务实例
/* Private typedef -----------------------------------------------*/
/* Private constants ---------------------------------------------*/
/* 接收到的方案信息 */
SchemeData_t SchemeData;
SchemeData_t PreStorageSchemeData;// 设备预存信息
uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - 3;            /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
/* Private variables ---------------------------------------------*/
//该变量用于保存连接句柄，初始值设置为无连接
uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
/* 电池电量的原始值 */
nrf_saadc_value_t Battery_Saadc_Value = 10000;
/* 电池电压百分比 */
uint8_t Battery_Percentage = 100;
/* 肌电采集定时器初始化标志 */
uint8_t TimerEegAdcInit_Flag = 0;
/* 控制电流标志 */
uint8_t CurrentFlag = 0;
/* 设备的连接状态 */
ConnectStateInfo_e DeviceConnectState = DisconnectState;
ElectrodeStatusInfo_e ElectrodeStatusInfo = ElectrodeConnectted;
ElectrodeStatusInfo_e LastElectrodeStatusInfo = ElectrodeConnectted;
/* 适配器连接状态 */
AdapterStateInfo_e AdapterState = AdapterNotConnected;
AdapterStateInfo_e LastAdapterState = AdapterNotConnected;

/* MAC地址数组 */
uint8_t BLE_MAC[BLE_GAP_ADDR_LEN];
//定义FDS异步操作标志结构体
my_fds_info_t my_fds_info;
// 初始化参数信息
SchemePara_t SchemePara = {
    .text = 0
};
uint16_t ccrvaluebuf[70] = {
    23,25,27,29,31,33,35,37,39,41, //1-10
    43,45,47,50,52,54,56,58,60,63, //11-20
    65,67,69,71,74,76,78,80,82,85, //21-30
    87,89,91,93,95,97,99,101,103,105, //31-40
    108,111,114,117,120,123,126,129,132,134, //41-50
    136,138,140,142,144,146,148,150,152,154, //51-60
    155,156,158,160,162,164,167,170,172,174  //61-70
};
#define EEG_DATA_LENGTH           ( 50 )
uint8_t aEEGData[EEG_DATA_LENGTH] = {
    23,25,27,29,31,33,35,37,39,41,
    43,45,47,50,52,54,56,58,60,63,
    65,67,69,71,74,76,78,80,82,85,
    87,89,91,93,95,97,99,101,103,105,
    108,111,114,117,120,123,126,129,132,134
};
uint8_t eegmode = 0;
uint8_t eegflag = 0;

StimStateInfo_t ChannelStimStateInfo_t;

rms_data_t rmsData = {.frameHeader = FRAME_HEADER,
					  .frameLength = sizeof(rmsData) - 4, //减去帧头、帧长度、校验和、帧尾
					  .functionCode = D_EMG_DATA_REPORT,
					  .myNumber = 0x01,
					  .channel = 0x01,
					  //.rmsDataBuffer = {0},
					  .checkSum = 0,
					  .frameTail = FRAME_TAIL
					 };

/* Private function prototypes -----------------------------------*/
void StatusInquiry(ElectrodeStatusInfo_e Electrodestatus);
void StartStopCtrl(uint8_t StartStopValue);
void MACQuery(void);
/* Public constants ----------------------------------------------*/
/* Public variables ----------------------------------------------*/
/********************************************************************
* name         : void SetFreqWidth(uint8_t* AnalysisDataBffer_t)
* description  : 设置脉冲频率
* Input        : AnalysisDataBffer_t：接收到的数据缓冲区
* Output       : void
* Return       : void
********************************************************************/
void SetFreqWidth(uint8_t* AnalysisDataBffer_t)
{

}
/********************************************************************
* name         : void SetRampTime(uint8_t* AnalysisDataBfferIn_t)
* description  : 设置斜坡时间
* Input        : AnalysisDataBffer_t：接收到的数据缓冲区
* Output       : void
* Return       : void
********************************************************************/
void SetRampTime(uint8_t* AnalysisDataBffer_t)
{

}
/********************************************************************
* name         : void SetStimPara(uint8_t* AnalysisDataBfferIn_t)
* description  : 设置刺激参数
* Input        : AnalysisDataBffer_t：接收到的数据缓冲区
* Output       : void
* Return       : void
********************************************************************/
void SetStimPara(uint8_t* AnalysisDataBffer_t)
{


	//开启采集模式
	if(1 == AnalysisDataBffer_t[4])
	{
        eegmode = 1;
		return;
	}

}
/********************************************************************
* name         : static void nus_data_handler(ble_nus_evt_t * p_evt) 
* description  : BLE串口透传事件回调函数
* Input        : ble_nus_evt_t * p_evt：发生的事件
* Output       : void
* Return       : void
********************************************************************/
static void nus_data_handler(ble_nus_evt_t * p_evt) 
{
    uint8_t FrameLength  = 0;//帧长度
    uint8_t FunctionCode = 0;//功能码
    uint8_t CheckSum     = 0;//校验和
    uint8_t Sum          = 0;//数据和
    uint8_t SumCCR       = 0;//CCR值
    #define RX_BLE_DATA_LEN 100
    uint8_t RecieveData[RX_BLE_DATA_LEN] = {0}; //接收数据帧的数组
    
    if(p_evt->type == BLE_NUS_EVT_RX_DATA)
    {
        uint16_t Length = 0;
        
        Length = p_evt->params.rx_data.length;
        if(Length > RX_BLE_DATA_LEN)
        {
            NRF_LOG_ERROR("RecieveData length error");
            return;
        }
        else
        {
            memcpy(RecieveData, p_evt->params.rx_data.p_data, Length);
        }
		
        /* 解析蓝牙收到的数据 */
        if(0xAA == RecieveData[0])
        {
            FrameLength = RecieveData[1];               //帧长度
            if(FrameLength > (RX_BLE_DATA_LEN - 4))
            {
                NRF_LOG_ERROR("RecieveData length error %d", FrameLength);
                return;
            }
            else if(0x55 != RecieveData[FrameLength + 3]) //查找帧尾
            {
                NRF_LOG_ERROR("RecieveData end flag error");
                return;
            }
            CheckSum    = RecieveData[FrameLength + 2]; //校验和
            //if(0x55 == RecieveData[FrameLength + 3])    //查找帧尾
            {
                /*校验数据包*/
                for(uint8_t i = 0; i < FrameLength; i++)
                {
                   Sum += RecieveData[i+2];
                }
                SumCCR = Sum & 0xff;
                
                if(CheckSum == SumCCR)
                {
                    FunctionCode = RecieveData[2];
                    
                    /*模式、脉宽、频率、斜坡时间设置*/
                    if(STIM_PARA_CONTROL == FunctionCode)
                    {
                        SetStimPara(RecieveData);        //设置参数
                        ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
                    }
                    /*电流控制 （控制刺激强度）*/
                    else if(CURRENT_CONTROL == FunctionCode)
                    {
                        NRF_LOG_INFO("CURRENT_CONTROL");
                        
//                        SetStandardCurrent(RecieveData); //设置电流
//                        CurrentFlag = 1;                 //设置电流的标志，此标志为1时表示可以输出电流
                        ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
                    }
					/*刺激启停控制*/
                    else if(START_STOP_CONTROL == FunctionCode)
                    {
                        NRF_LOG_INFO("START_STOP_CONTROL");
//                        CurrentFlag = 0;                          //此标志清0，此时开启电流的标志由通道模式和通道状态控制
                        uint8_t StartStopValue = CH_STOP;        //初始状态为停止
                        StartStopValue = RecieveData[StartStopOffset];              //设置启停状态
                        StartStopCtrl(StartStopValue);                      //启停控制
                        ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
                    }
					/*触发采集开始*/
                    else if(TRIG_COLLECT_START_CONTROL == FunctionCode)
                    {
                        NRF_LOG_INFO("TRIG_COLLECT_START_CONTROL");
                        ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
                    }
					/*触发刺激开始*/
                    else if(TRIG_STIM_START_CONTROL == FunctionCode)
                    {
                        NRF_LOG_INFO("TRIG_STIM_START_CONTROL");
                        ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
                    }
                    /*轮询0x8A*/
                    else if(STATUS_INQUIRY == FunctionCode)
                    {
                        StatusInquiry(ElectrodeStatusInfo);
                        NRF_LOG_INFO("STATUS_INQUIRY");
                    }
					/* 运行轮询 */
                    else if(RUN_ROLL == FunctionCode)
                    {
						RunRoll();
                        NRF_LOG_INFO("RUN_ROLL");
                    }
					/* 版本查询 */
                    else if(VERSION_INQUIRY == FunctionCode)
                    {
                        CheckVersion();
                        NRF_LOG_INFO("VERSION_INQUIRY");
                    }
                    else if(SCHEME_QUERY == FunctionCode)
                    {
                        //SchemeQuery();
                        my_fds_info.read = true;
                        NRF_LOG_INFO("SCHEME_QUERY");
                    }
                    else if(MAC_QUERY == FunctionCode)
                    {
                        MACQuery();
                    }
                }
            }
        }   
        /***********end***********/
    }
}
/********************************************************************
* name         : void service_nus_init(void)
* description  : 串口透传服务初始化
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void service_nus_init(void)
{
	ret_code_t err_code;
	ble_nus_init_t nus_init;                     //定义串口透传初始化结构体
	/*------------------以下代码初始化串口透传服务-------------*/    
	memset(&nus_init, 0, sizeof(nus_init));      //清零串口透传服务初始化结构体  
	nus_init.data_handler = nus_data_handler;    //设置串口透传事件回调函数
	err_code = ble_nus_init(&m_nus, &nus_init);  //初始化串口透传服务
	APP_ERROR_CHECK(err_code);
    /*------------------初始化串口透传服务-END-----------------*/
}
/********************************************************************
* name         : void StartStopCtrl(uint8_t ucStartStopValueIn)
* description  : 启、停控制处理函数 
* Input        : ucStartStopValueIn：启、停控制值
                 ucChannelIn：通道号
* Output       : void
* Return       : void
********************************************************************/
void StartStopCtrl(uint8_t StartStopValue)
{
    switch(StartStopValue)
    {
        case CH_START: StartManage();
                       break;
        case CH_PAUSE: PauseManage();   
                       break;
        case CH_CONTINUE: RecoverManage(); 
                       break;
        case CH_STOP: StopManage(); 
                       break;
        default: break;
    }
}
/********************************************************************
* name         : void StartManage(void)
* description  : 开始处理函数 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void StartManage(void)
{
    if(eegmode == 1)
    {
        eegflag = 1;
    }

}
/********************************************************************
* name         : void PauseManage(void)
* description  : 暂停处理函数 
* Input        : Channel：通道号
* Output       : void
* Return       : void
********************************************************************/
void PauseManage(void)
{
        if(eegmode == 1)
    {
        eegflag = 0;
    }
//    CHAChannelState_e = IdleState;   //设置状态为空闲态，空闲状态下pwm_flag置0
//    ChannelStimStateInfo_t.ChannelWorkState = Pause;
//    PwmDACStop();
//    CloseOutput();          //关闭输出
//    NRF_LOG_INFO("Pause_Stim");
}
/********************************************************************
* name         : void CloseOutput(void)
* description  : 将输出电流置0，斜坡时间置0,关闭输出PWM    
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void CloseOutput(void)
{
        if(eegmode == 1)
    {
        eegmode = 0;
        eegflag = 0;
    }
    //ChannelStimStateInfo_t.ucCurrent = 0;
//    ChannelStimStateInfo_t.Ramp_e = RampIdle;//斜坡状态为空闲态
//    RampTime = 0;                //斜坡时间清0
//    SetCurrent(0);                  //设置输出电流为0
//    PwmSubtractStop();                         //关闭输出PWM
//    PwmDACStop();                      //停止充能PWM
////    GpioteInit();
}
/********************************************************************
* name         : void RecoverManage(void)
* description  : 继续处理函数 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void RecoverManage(void)
{
    if(eegmode == 1)
    {
        eegflag = 1;
    }

}
/********************************************************************
* name         : void StopManage(void)
* description  : 停止处理函数 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void StopManage(void)
{

}

/********************************************************************
* name         : void SetStandardCurrent(uint8_t* AnalysisDataBfferIn_t)
* description  : 设置标称电流值 
* Input        : AnalysisDataBfferIn_t：接收到的数据缓冲区
* Output       : void
* Return       : void
********************************************************************/
void SetStandardCurrent(uint8_t* AnalysisDataBffer_t)
{

}
/********************************************************************
* name         : void StatusInquiry(void)
* description  : 状态轮询 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void StatusInquiry(ElectrodeStatusInfo_e Electrodestatus)
{
	    uint8_t j = 2;
        static uint8_t aTxBuffer[10] = {0};
        uint32_t ulCrc = 0;
        uint16_t Length = 10;
		
        /* 帧头、帧尾*/
        aTxBuffer[HeadOffset]                 = 0xAA;
        aTxBuffer[DataLengthOffset]           = 0x06;
        aTxBuffer[FunctionCodeOffset]         = STATUS_INQUIRY;
        aTxBuffer[ChannelNumOffset]           = 0x00;
        aTxBuffer[ElectrodeStatusOffset]      = 0x01;
        aTxBuffer[StimStatusOffset]           = ChannelStimStateInfo_t.Ramp_e;
        aTxBuffer[StimCurrentOffset]          = ChannelStimStateInfo_t.ucCurrent;
        aTxBuffer[ResetOffset]                = 0x00;
        aTxBuffer[TailOffset]                 = 0x55;

        /* 校验和 */
        for(uint8_t i = 0; i < 6; i++)
        {
            ulCrc += aTxBuffer[j];
            j++;
        }
        aTxBuffer[DataCrcOffset] = (uint8_t)ulCrc;

        ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}

/********************************************************************
* name         : uint8_t caculate_sum_check(void)
* description  : 运行校验和计算
* Input        : typeStructHeader：数据结构头部
                 typeStructLength：数据结构长度
* Output       : void
* Return       : 计算结果
********************************************************************/

uint8_t caculate_sum_check(uint8_t *typeStructHeader, uint8_t typeStructLength)
{
    uint8_t sum = 0;
    uint8_t * typeStructCMD = &typeStructHeader[2];
    for (uint8_t i = 0; i < typeStructLength; i++)
    {
        sum += typeStructCMD[i];
    }
    return sum&0xFF;
}

/// @brief 运行状态回复
reply_run_status_t replyRunStatus = {
    .frameHeader = FRAME_HEADER,
    .frameLength = sizeof(replyRunStatus) - 4, //减去帧头、帧长度、校验和、帧尾
    .functionCode = RUN_ROLL,
    .myNumber = 0x01,
    .channel = 0x01,
    .checkSum = 0,
    .frameTail = FRAME_TAIL
};
/********************************************************************
* name         : void RunRoll(void)
* description  : 运行轮询 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void RunRoll(void)
{
    uint32_t ulCrc = 0;
    uint16_t Length = sizeof(replyRunStatus);

    replyRunStatus.ChargeState = ChargeState;
    replyRunStatus.BatteryLevelA = Battery_Percentage;

    replyRunStatus.checkSum = (uint8_t)caculate_sum_check((uint8_t *)&replyRunStatus, replyRunStatus.frameLength);

    ble_nus_data_send(&m_nus, &replyRunStatus.frameHeader, &Length, m_conn_handle);
}
/********************************************************************
* name         : void CheckVersion(void)
* description  : 版本查询 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
check_version_t checkVersion = {
    .frameHeader = FRAME_HEADER,
    .frameLength = sizeof(checkVersion) - 4, //减去帧头、帧长度、校验和、帧尾
    .functionCode = VERSION_INQUIRY,
    .myNumber = 0x01,
    .channel = 0x01,
    .checkSum = 0,
    .frameTail = FRAME_TAIL
}
void CheckVersion(void)
{
    	uint8_t j = 2;
        static uint8_t aTxBuffer[21] = {0};
        uint32_t ulCrc = 0;
        uint16_t Length = 21;
		
        /* 帧头、帧尾*/
        aTxBuffer[HeadOffset]                 = 0xAA;
        aTxBuffer[DataLengthOffset]           = 0x11;
        aTxBuffer[FunctionCodeOffset]         = VERSION_INQUIRY;
        aTxBuffer[ChannelNumOffset]           = 0x00;
        aTxBuffer[20]                         = 0x55;

        /* 协议中规定先发送高字节，后发送低字节 */
        aTxBuffer[4] = VersionDes[0];
        aTxBuffer[5] = VersionDes[1];
        aTxBuffer[6] = VersionDes[2];
        aTxBuffer[7] = VersionDes[3];
        aTxBuffer[8] = VersionDes[4];
        aTxBuffer[9] = VersionDes[5];
        aTxBuffer[10] = VersionDes[6];
        aTxBuffer[11] = VersionDes[7];
        aTxBuffer[12] = 0x00;
        aTxBuffer[13] = 0x00;
        aTxBuffer[14] = 0x00;
        aTxBuffer[15] = 0x00;
        aTxBuffer[16] = 0x00;
        aTxBuffer[17] = 0x00;
        aTxBuffer[18] = 0x00;
        /* 校验和 */
        for(uint8_t i = 0; i < 17; i++)
        {
            ulCrc += aTxBuffer[j];
            j++;
        }
        aTxBuffer[19] = (uint8_t)ulCrc;
        ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name         : void EegDataSend(void)
* description  : 发送肌电数据 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void EegDataSend(void)
{
        uint8_t j = 2;
    
        static uint8_t aTxBuffer[EEG_DATA_LENGTH+6] = {0};
        uint32_t ulCrc = 0;  
        uint16_t Length = EEG_DATA_LENGTH+6;
		ret_code_t err_code;

        /* 帧头、帧尾*/
        aTxBuffer[HeadOffset]                 = 0xAA;
        aTxBuffer[DataLengthOffset]           = 0x34;
        aTxBuffer[FunctionCodeOffset]         = EEG_DATA;
        aTxBuffer[ChannelNumOffset]           = 0x00;
        aTxBuffer[EEG_DATA_LENGTH+5]          = 0x55;

        /* 协议中规定先发送高字节，后发送低字节 */
        memcpy(&aTxBuffer[4],aEEGData,EEG_DATA_LENGTH);

        /* 校验和 */
        for(uint8_t i = 0; i < EEG_DATA_LENGTH+2; i++)
        {
            ulCrc += aTxBuffer[j];
            j++;
        }
        aTxBuffer[EEG_DATA_LENGTH+4] = (uint8_t)ulCrc;
        ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name         : void UpdateCurrent(uint8_t CurrentSend)
* description  : 同步电流 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void UpdateCurrent(uint8_t CurrentSend)
{
    uint8_t j = 2;
    uint8_t aTxBuffer[8] = {0};
    uint32_t ulCrc = 0;
    uint16_t Length = 8;
    
    /* 帧头、帧尾*/
    aTxBuffer[HeadOffset]                 = 0xAA;
    aTxBuffer[DataLengthOffset]           = 0x04;
    aTxBuffer[FunctionCodeOffset]         = CURRENT_CONTROL;
    aTxBuffer[ChannelNumOffset]           = 0x00;
    aTxBuffer[7]                          = 0x55;

    /* 协议中规定先发送高字节，后发送低字节 */
    aTxBuffer[4] = CurrentSend;
    aTxBuffer[5] = 0x01;   // 01代表蓝牙设备发送

    /* 校验和 */
    for(uint8_t i = 0; i < 4; i++)
    {
        ulCrc += aTxBuffer[j];
        j++;
    }
    aTxBuffer[6] = (uint8_t)ulCrc;
    ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}


void user_ble_or_uart_send(char * txBufferP, uint16_t Length)
{
    ble_nus_data_send(&m_nus, txBufferP, &Length, m_conn_handle);
}

/********************************************************************
* name         : void ble_send_rms_data(uint16_t rms_data)
* description  : 发送肌电数据到主机
* Input        : uint16_t rms_data：肌电数据
* Output       : void
* Return       :
********************************************************************/
void ble_send_rms_data(uint16_t rms_data)
{
	uint32_t TempSum = 0;

	static uint8_t sendCnt = 0;

	if(sendCnt < RMS_USER_DATA_LENGTH)
	{
		rmsData.rmsDataBuffer[sendCnt] = rms_data; //将rms_data存入rmsData的rmsDataBuffer数组中
		sendCnt++;
		if(sendCnt < RMS_USER_DATA_LENGTH) 
			return ; //如果发送次数小于RMS_USER_DATA_LENGTH，则不发送
	}
	sendCnt = 0; //发送次数达到RMS_USER_DATA_LENGTH后，重置发送次数
	rmsData.myNumber = 1;
	//rmsData.myNumber++;
	uint8_t * sumCheckStartP = (uint8_t *)&rmsData.functionCode;
	for(uint8_t i = 0; i < rmsData.frameLength; i++)
	{
		TempSum += sumCheckStartP[i];
	}
	rmsData.checkSum = TempSum & 0xff;
	user_ble_or_uart_send((uint8_t *)&rmsData, sizeof(rmsData)); //145us
}


/********************************************************************
* name         : void StateUpLoad(AdapterStateInfo_e AdapterStateTemp , ElectrodeStatusInfo_e ElectrodeStatusTemp)
* description  : 电极片和适配器状态上传
* Input        : AdapterStateInfo_e AdapterStateTemp , ElectrodeStatusInfo_e ElectrodeStatusTemp
* Output       : void
* Return       : void
********************************************************************/
void StateUpLoad(AdapterStateInfo_e AdapterStateTemp , ElectrodeStatusInfo_e ElectrodeStatusTemp)
{
    uint8_t j = 2;
    uint8_t aTxBuffer[8] = {0};
    uint32_t ulCrc = 0;
    uint16_t Length = 8;
    
    AdapterStateInfo_e AdapterStateIn;
    ElectrodeStatusInfo_e ElectrodeStatusIn;
    
    AdapterStateIn = AdapterStateTemp;
    ElectrodeStatusIn = ElectrodeStatusTemp;
    
    /* 帧头、帧尾*/
    aTxBuffer[HeadOffset]                 = 0xAA;
    aTxBuffer[DataLengthOffset]           = 0x04;
    aTxBuffer[FunctionCodeOffset]         = STATE_UPLOAD;
    aTxBuffer[ChannelNumOffset]           = 0x00;
    aTxBuffer[7]                          = 0x55;

    aTxBuffer[4] = AdapterStateIn;   // 适配器连接状态
    aTxBuffer[5] = ElectrodeStatusIn;   // 电极片状态
    
    if(ElectrodeStatusIn == ElectrodeFalloff)
    {

        ElectrodeStatusInfo = ElectrodeConnectted;
    }
    
    		NRF_LOG_INFO("Electrodestatus = %d",ElectrodeStatusIn);
    /* 校验和 */
    for(uint8_t i = 0; i < 4; i++)
    {
        ulCrc += aTxBuffer[j];
        j++;
    }
    aTxBuffer[6] = (uint8_t)ulCrc;
    ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name         : void UpdateControlStatus(uint8_t ControlStatus)
* description  : 同步电流 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void UpdateControlStatus(uint8_t ControlStatus)
{
    uint8_t j = 2;
    uint8_t aTxBuffer[8] = {0};
    uint32_t ulCrc = 0;
    uint16_t Length = 8;
    
    /* 帧头、帧尾*/
    aTxBuffer[HeadOffset]                 = 0xAA;
    aTxBuffer[DataLengthOffset]           = 0x04;
    aTxBuffer[FunctionCodeOffset]         = START_STOP_CONTROL;
    aTxBuffer[ChannelNumOffset]           = 0x00;
    aTxBuffer[7]                          = 0x55;

    /* 协议中规定先发送高字节，后发送低字节 */
    aTxBuffer[4] = ControlStatus;
    aTxBuffer[5] = 0x01;   // 01代表蓝牙设备发送

    /* 校验和 */
    for(uint8_t i = 0; i < 4; i++)
    {
        ulCrc += aTxBuffer[j];
        j++;
    }
    aTxBuffer[6] = (uint8_t)ulCrc;
    ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name         : void SchemeQuery(uint8_t idMSB,uint8_t idLSB)
* description  : 方案查询 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void SchemeQuery(uint8_t idMSB,uint8_t idLSB)
{
    	uint8_t j = 2;
        static uint8_t aTxBuffer[8] = {0};
        uint32_t ulCrc = 0;
        uint16_t Length = 8;
		
        /* 帧头、帧尾*/
        aTxBuffer[HeadOffset]                 = 0xAA;
        aTxBuffer[DataLengthOffset]           = 0x04;
        aTxBuffer[FunctionCodeOffset]         = SCHEME_QUERY;
        aTxBuffer[ChannelNumOffset]           = 0x00;
        aTxBuffer[7]                          = 0x55;

        /* 协议中规定先发送高字节，后发送低字节 */
        aTxBuffer[4] = idMSB;
        aTxBuffer[5] = idLSB;

        /* 校验和 */
        for(uint8_t i = 0; i < 4; i++)
        {
            ulCrc += aTxBuffer[j];
            j++;
        }
        aTxBuffer[6] = (uint8_t)ulCrc;
        ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name         : void MACQuery(void)
* description  : MAC地址查询 
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void MACQuery(void)
{
    	uint8_t j = 2;
        static uint8_t aTxBuffer[12] = {0};
        uint32_t ulCrc = 0;
        uint16_t Length = 12;

        /* 帧头、帧尾*/
        aTxBuffer[HeadOffset]                 = 0xAA;
        aTxBuffer[DataLengthOffset]           = 0x08;
        aTxBuffer[FunctionCodeOffset]         = MAC_QUERY;
        aTxBuffer[ChannelNumOffset]           = 0x00;
        aTxBuffer[11]                         = 0x55;

        aTxBuffer[4] = BLE_MAC[5];
        aTxBuffer[5] = BLE_MAC[4];
        aTxBuffer[6] = BLE_MAC[3];
        aTxBuffer[7] = BLE_MAC[2];   
        aTxBuffer[8] = BLE_MAC[1];
        aTxBuffer[9] = BLE_MAC[0];
        /* 校验和 */
        for(uint8_t i = 0; i < 8; i++)
        {
            ulCrc += aTxBuffer[j];
            j++;
        }
        aTxBuffer[10] = (uint8_t)ulCrc;
        ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}

/********************************************************************
* name         : void JudgeLedMode(void)
* description  :  
* Input        : void
* Output       : void
* Return       : void
********************************************************************/
void JudgeLedMode(void)
{

}

void DisconnectControl(void)
{
    StopManage();
}

/*************************** END OF FILE ***************************/


