智能门锁

#include  "dorlock_user_mgr.h"
#include  "dr_lock_cmd.h"


#include  "cmd_packet.h"
#include  "app_error.h"
#include  "sk_flash.h"
#include  "fds.h"
#include  "nrf_log.h"
#include  "lock_cmd_def.h"
#include  "dorlock_cmd_rsp.h"
#include  "timer_modif.h"
#include  "ble_nus.h"
#include  "user_cipher_mgr.h"




uint8_t   *TimelineUserTab[PRESCRIP_USER_SIZE] =
{
"Hgyj",
"Tvbh",
"Jxdi",
"Hvkr",
"Jxce",
"Tabg",
"Dqyh",
"Ased",
"Gyxt",
"Kcel"
};










enum  
{
TIME_SLOT_USE = 1,
   TIME_NODE_USE,
   TIME_FASTEN_USE
};












LockUartCmd_t  LockUartCmdHandle;
   


static  uint8_t   UserMgrBuf[sizeof(UserMgrFlashOpera_t)];
static  uint8_t   UserCrtBuf[12];
UserMgrFlashOpera_t   UserMgrFlashOpera;


static SystemUserMgr_t   SystemUserMgr;










void  GetSystemUserMgrAdd(SystemUserMgr_t *UserMgr)
{
*UserMgr  =  SystemUserMgr;
}




void  GetUserMgrCmdHandleAdd(LockUartCmd_t *UartCmd)
{
*UartCmd  = LockUartCmdHandle;
}




//ÓÃÓÚÉϵç¶ÁÈ¡flash²»´¿Ôھͳõʼ»¯Ò»´Î
void   InitSystemUserNoneCreat(void)
{
uint8_t   i;

   for(i = 0; i < sizeof(SystemUserMgr.UserCreatRecordTab)/sizeof(SystemUserMgr.UserCreatRecordTab[0]); i++)
   {
SystemUserMgr.UserCreatRecordTab[i] = USER_NONE_CREAT_FLAG;
}
}






//ÓÃÓÚÉϵç¶ÁÈ¡flash²»´¿Ôھͳõʼ»¯Ò»´Î
void   InitUserMgrFlashOpera(void)
{
UserMgrFlashOpera.UserCipherAddDelateFlag  = 0x0000;  //ÓÃλ±íʾ¶ÔӦʱЧÃÜÂëΪ¿Õ
   memset(UserMgrFlashOpera.UserCipherLiveTime, 0, sizeof(UserMgrFlashOpera.UserCipherLiveTime));
//    memset(UserMgrFlashOpera.UserIdCreatFlashBuf, USER_NONE_CREAT_FLAG, sizeof(UserMgrFlashOpera.UserIdCreatFlashBuf));
   for(uint8_t i = 0; i < 11; i++)
   {
UserMgrFlashOpera.UserIdCreatFlashBuf[i]  =  USER_NONE_CREAT_FLAG;
}
   memset(UserMgrFlashOpera.UserCipherNumList, 0, sizeof(UserMgrFlashOpera.UserCipherNumList));
   memset(UserMgrFlashOpera.UserCipherLenList, 0, sizeof(UserMgrFlashOpera.UserCipherLenList));
   memset(UserMgrFlashOpera.CipherUseTimeSta, 0, sizeof(UserMgrFlashOpera.CipherUseTimeSta));
//    memset(IsUserCreat, 0, sizeof(IsUserCreat));
}




/*
void  InitUserMgr(void)
{
memset(SystemUserMgr.UserCreatRecordTab, USER_NONE_CREAT_FLAG, sizeof(UserMgrFlashOpera.UserIdCreatFlashBuf));
}
*/




uint32_t  LockUserMgrFlashAccess(UserMgrFlashOpera_t *p_UserMgr, es_flash_access_t access_type)
{
flash_access_params_t params =
   {
.record_key  =  RECORD_KEY_USER_MGR,
   .file_id     =  FILE_ID_USER_MGR_FLASH,
   .p_data_buf  =  UserMgrBuf,
   .p_data      =  (uint8_t *)p_UserMgr,
   .size_bytes  =  sizeof(UserMgrFlashOpera_t),
   .access_type =  access_type
};

return access_flash_data(&params);
}




uint32_t  LockUserCreatFlashAccess(uint8_t *UserFlag, es_flash_access_t access_type)
{
flash_access_params_t params =
   {
.record_key  =  RECORD_KEY_USER_CREAT,
   .file_id     =  FILE_ID_USER_CREAT,
   .p_data_buf  =  UserCrtBuf,
   .p_data      =  (uint8_t *)UserFlag,
   .size_bytes  =  12,
   .access_type =  access_type
};

return access_flash_data(&params);
}


//Éϵç³õʼ»¯µ÷ÓÃ
void  UserMgrPowerOnInit(void)
{
uint32_t  Error;

   Error  =  LockUserMgrFlashAccess(&UserMgrFlashOpera, ES_FLASH_ACCESS_READ);

   if(Error ==  FDS_ERR_NOT_FOUND)
{
InitUserMgrFlashOpera();
   Error  =  LockUserMgrFlashAccess(&UserMgrFlashOpera, ES_FLASH_ACCESS_WRITE);
   APP_ERROR_CHECK(Error);
}
else
{
APP_ERROR_CHECK(Error);
}
/*
Error  =  LockUserCreatFlashAccess(IsUserCreat, ES_FLASH_ACCESS_READ);

if(Error ==  FDS_ERR_NOT_FOUND)
{
Error  =  LockUserCreatFlashAccess(IsUserCreat, ES_FLASH_ACCESS_WRITE);
   APP_ERROR_CHECK(Error);
}
else
{
APP_ERROR_CHECK(Error);
}
*/
}






/*
void   SaveUserCreatFlag(void)
{
uint32_t  Error;
   Error  =  LockUserCreatFlashAccess(IsUserCreat, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(Error);
}
*/




void  UserMgrFlashUpdata(void)
{
uint8_t  i;
   uint32_t  Error;

   UserMgrFlashOpera_t  UserMgrStore;

   UserMgrStore.UserCipherAddDelateFlag  = SystemUserMgr.UserCipherMgrFlag;
   UserMgrStore.TemporCipherId  =  SystemUserMgr.TemporUserMgr.CipherId;
   memcpy(UserMgrStore.UserIdCreatFlashBuf, SystemUserMgr.UserCreatRecordTab, sizeof(SystemUserMgr.UserCreatRecordTab));
   memcpy(UserMgrStore.IsUserCreat, SystemUserMgr.IsUserCreat, sizeof(SystemUserMgr.IsUserCreat));
   for(i = 0; i< sizeof(UserMgrStore.UserCipherLiveTime)/sizeof(UserMgrStore.UserCipherLiveTime[0]); i++)
   {
if(i == SystemUserMgr.TemporUserIdRecordIndex)
{
UserMgrStore.UserCipherLiveTime[i].UserCipherStartUseTime  = SystemUserMgr.TemporUserMgr.CipherValidStartTime;
   UserMgrStore.UserCipherLiveTime[i].UserCipherEndUseTime  = SystemUserMgr.TemporUserMgr.CipherValidEndTime; 
   UserMgrStore.CipherUseTimeSta[i]  = SystemUserMgr.TemporUserMgr.DorLockUseTimeSchedul;
}
else
{
UserMgrStore.UserCipherLiveTime[i].UserCipherStartUseTime  =  SystemUserMgr.NormalUserMgr[i].CipherValidStartTime;
   UserMgrStore.UserCipherLiveTime[i].UserCipherEndUseTime  =  SystemUserMgr.NormalUserMgr[i].CipherValidEndTime;
   UserMgrStore.CipherUseTimeSta[i]  =  SystemUserMgr.NormalUserMgr[i].DorLockUseTimeSchedul;
}
}
for(i = 0; i < sizeof(UserMgrFlashOpera.UserCipherLenList)/sizeof(UserMgrFlashOpera.UserCipherLenList[0]); i++)
{
if(i == SystemUserMgr.TemporUserIdRecordIndex)
{
UserMgrStore.UserCipherLenList[i]  = SystemUserMgr.TemporUserMgr.CipherLenth;
   memcpy(&UserMgrStore.UserCipherNumList[i*PASSWORD_SIZE], SystemUserMgr.TemporUserMgr.DorLockOperaCipher, PASSWORD_SIZE);
}
else if(i == SystemUserMgr.MasterIdRecordIndex)
{
UserMgrStore.UserCipherLenList[i]  =  SystemUserMgr.MasterMgr.CipherLenth;
   memcpy(&UserMgrStore.UserCipherNumList[i*PASSWORD_SIZE], SystemUserMgr.MasterMgr.DorLockOperaCipher, PASSWORD_SIZE);
}
else
{
UserMgrStore.UserCipherLenList[i]  =  SystemUserMgr.NormalUserMgr[i].CipherLenth;
   memcpy(&UserMgrStore.UserCipherNumList[i*PASSWORD_SIZE], SystemUserMgr.NormalUserMgr[i].DorLockOperaCipher, PASSWORD_SIZE);
}
}


Error  =  LockUserMgrFlashAccess(&UserMgrStore, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(Error);
}








//µ÷ÓÃUserMgrPowerOnInit(void)ºóµ÷ÓÃ
void  SystemUserMgrConfig(void)
{
   uint8_t  i;
   SystemUserMgr.TemporUserIdRecordIndex  = TEMPOR_ID_SIGN_POS;
   SystemUserMgr.MasterIdRecordIndex  = MASTER_ID_SIGN_POS;
SystemUserMgr.UserCipherMgrFlag  =  UserMgrFlashOpera.UserCipherAddDelateFlag;
   memcpy(SystemUserMgr.UserCreatRecordTab, UserMgrFlashOpera.UserIdCreatFlashBuf, sizeof(SystemUserMgr.UserCreatRecordTab));
   SystemUserMgr.TemporUserMgr.CipherId  =  UserMgrFlashOpera.TemporCipherId;
   memcpy(SystemUserMgr.IsUserCreat, UserMgrFlashOpera.IsUserCreat, sizeof(SystemUserMgr.IsUserCreat));
   for(i = 0; i< sizeof(UserMgrFlashOpera.UserCipherLiveTime)/sizeof(UserMgrFlashOpera.UserCipherLiveTime[0]); i++)
   {
if(i == SystemUserMgr.TemporUserIdRecordIndex)
{
SystemUserMgr.TemporUserMgr.CipherValidStartTime  =  UserMgrFlashOpera.UserCipherLiveTime[i].UserCipherStartUseTime;
   SystemUserMgr.TemporUserMgr.CipherValidEndTime  =  UserMgrFlashOpera.UserCipherLiveTime[i].UserCipherEndUseTime;
   SystemUserMgr.TemporUserMgr.DorLockUseTimeSchedul  =  UserMgrFlashOpera.CipherUseTimeSta[i];
}
else
{
SystemUserMgr.NormalUserMgr[i].CipherValidStartTime  =  UserMgrFlashOpera.UserCipherLiveTime[i].UserCipherStartUseTime;
   SystemUserMgr.NormalUserMgr[i].CipherValidEndTime  = UserMgrFlashOpera.UserCipherLiveTime[i].UserCipherEndUseTime;
   SystemUserMgr.NormalUserMgr[i].DorLockUseTimeSchedul  =  UserMgrFlashOpera.CipherUseTimeSta[i];
}
}

for(i = 0; i < sizeof(UserMgrFlashOpera.UserCipherLenList)/sizeof(UserMgrFlashOpera.UserCipherLenList[0]); i++)
{
if(i == SystemUserMgr.TemporUserIdRecordIndex)
{
SystemUserMgr.TemporUserMgr.CipherLenth  = UserMgrFlashOpera.UserCipherLenList[i];
                  memcpy(SystemUserMgr.TemporUserMgr.DorLockOperaCipher, &UserMgrFlashOpera.UserCipherNumList[PASSWORD_SIZE*i],PASSWORD_SIZE);
}
else if(i == SystemUserMgr.MasterIdRecordIndex)
{
SystemUserMgr.MasterMgr.CipherLenth  = UserMgrFlashOpera.UserCipherLenList[i];
   memcpy(SystemUserMgr.MasterMgr.DorLockOperaCipher, &UserMgrFlashOpera.UserCipherNumList[PASSWORD_SIZE*i], PASSWORD_SIZE);
}
else
{
SystemUserMgr.NormalUserMgr[i].CipherLenth  =  UserMgrFlashOpera.UserCipherLenList[i];
   memcpy(SystemUserMgr.NormalUserMgr[i].DorLockOperaCipher, &UserMgrFlashOpera.UserCipherNumList[PASSWORD_SIZE*i], PASSWORD_SIZE);
}
}
}






void   FillAllDorLockUserId(void)
{
   uint8_t   i;
   SystemUserMgr.MasterIdRecordIndex  = MASTER_ID_SIGN_POS;
   SystemUserMgr.TemporUserIdRecordIndex  = TEMPOR_ID_SIGN_POS;
for(i = 0; i < sizeof(SystemUserMgr.UserCreatRecordTab)/sizeof(SystemUserMgr.UserCreatRecordTab[0]); i++)
{
if(i == SystemUserMgr.MasterIdRecordIndex)
{
SystemUserMgr.MasterMgr.DorLockUserId  =  SystemUserMgr.UserCreatRecordTab[i];
}
else if(i == SystemUserMgr.TemporUserIdRecordIndex)
{
SystemUserMgr.TemporUserMgr.DorLockUserId  = SystemUserMgr.UserCreatRecordTab[i];
}
else
{
SystemUserMgr.NormalUserMgr[i].DorLockUserId =  SystemUserMgr.UserCreatRecordTab[i];
}
}
}






#if  0
bool   IsThisNormalUserCreat(uint8_t  id)
{
if(SystemUserMgr.NormalUserMgr[id].DorLockUserId  < USER_NONE_CREAT_FLAG-1)
{
return  true;
}

return  false;
}






bool  IsTemporUserCreat(void)
{
if(SystemUserMgr.TemporUserMgr.DorLockUserId < USER_NONE_CREAT_FLAG-1)
{
return  true;
}

return  false;
}
#endif




#if   DOR_LOCK_RESET_USER_CREAT_ENABLE


void   AddOneNormalUserCipher(uint8_t UserIndex, RealTime_t *TimeStart, RealTime_t *TimeEnd, uint8_t *Cipher,uint8_t CipherSize)
{
   uint16_t  UserCipherMgrMask;
//    ret_code_t err_code;  

   UserCipherMgrMask  =  0x0001 << UserIndex;
if((SystemUserMgr.UserCipherMgrFlag & UserCipherMgrMask) ==  0)
{
// SystemUserMgr.UserCipherMgrFlag  |=  UserCipherMgrMask;

   SystemUserMgr.NormalUserMgr[UserIndex].CipherValidStartTime  = *TimeStart;
   SystemUserMgr.NormalUserMgr[UserIndex].CipherValidEndTime = *TimeEnd;
//    memcpy(SystemUserMgr.NormalUserMgr[UserIndex].DorLockOperaCipher, Cipher, sizeof(Cipher)/sizeof(Cipher[0]));
   memcpy(SystemUserMgr.NormalUserMgr[UserIndex].DorLockOperaCipher, Cipher, CipherSize);
   SystemUserMgr.NormalUserMgr[UserIndex].CipherLenth  = CipherSize;
   SystemUserMgr.NormalUserMgr[UserIndex].DorLockUseTimeSchedul  = BEFORE_TIME_USING;
   UserMgrFlashUpdata();
   
//    if((SystemUserMgr.UserCreatRecordTab[UserIndex] == USER_NONE_CREAT_FLAG))
//    if(SystemUserMgr.IsUserCreat[UserIndex] == 0)
//    if(Sockets.IsRtcSetting[UserIndex] == 0)
{
//                  SystemUserMgr.IsUserCreat[UserIndex]  = 1;
//    UserMgrFlashUpdata();
//    SaveUserCreatFlag();
//    Sockets.IsRtcSetting[UserIndex]  = 1;
//    err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
//    APP_ERROR_CHECK(err_code);
   SetCurDorLockUartCmdExe(DOR_LOCK_USER_MGR_CMD, DOOR_LOCK_CMD_ADD_USER , ETMARS_CMD_EXE_TRIGGER, UserIndex);
   SystemUserMgr.NormalUserMgr[UserIndex].DorLockUserName  =  TimelineUserTab[UserIndex];
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
   LockUartCmdHandle.FunCode    =  DOOR_LOCK_CMD_ADD_USER;
   LockUartCmdHandle.CurUartExeCmd  =  DOOR_LOCK_CMD_ADD_USER;
   LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
   LockUartCmdHandle.lenth      =  sizeof(SystemUserMgr.NormalUserMgr[UserIndex].DorLockUserName) +1;
   memcpy(LockUartCmdHandle.Content, SystemUserMgr.NormalUserMgr[UserIndex].DorLockUserName, sizeof(SystemUserMgr.NormalUserMgr[UserIndex].DorLockUserName));
   CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
//    UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}
//      else
{
#if   0
LockUartCmdHandle.CurUartExeCmd  =  LOCK_CMD_ADD_CIPHER;
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
LockUartCmdHandle.FunCode    =  LOCK_CMD_ADD_CIPHER;
   LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
   PacketAddUserCipherCmdContent(&LockUartCmdHandle, NORMAL_USER, &SystemUserMgr);
   CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
#endif
}
}
}




#else    
void   AddOneNormalUserCipher(uint8_t UserIndex, RealTime_t *TimeStart, RealTime_t *TimeEnd, uint8_t *Cipher,uint8_t CipherSize)
{
   uint16_t  UserCipherMgrMask;
   ret_code_t err_code;  

   UserCipherMgrMask  =  0x0001 << UserIndex;
if((SystemUserMgr.UserCipherMgrFlag & UserCipherMgrMask) ==  0)
{
SystemUserMgr.UserCipherMgrFlag  |=  UserCipherMgrMask;

   SystemUserMgr.NormalUserMgr[UserIndex].CipherValidStartTime  = *TimeStart;
   SystemUserMgr.NormalUserMgr[UserIndex].CipherValidEndTime = *TimeEnd;
//    memcpy(SystemUserMgr.NormalUserMgr[UserIndex].DorLockOperaCipher, Cipher, sizeof(Cipher)/sizeof(Cipher[0]));
   memcpy(SystemUserMgr.NormalUserMgr[UserIndex].DorLockOperaCipher, Cipher, CipherSize);
   SystemUserMgr.NormalUserMgr[UserIndex].CipherLenth  = CipherSize;
   SystemUserMgr.NormalUserMgr[UserIndex].DorLockUseTimeSchedul  = BEFORE_TIME_USING;
   UserMgrFlashUpdata();
   
//    if((SystemUserMgr.UserCreatRecordTab[UserIndex] == USER_NONE_CREAT_FLAG))
//    if(SystemUserMgr.IsUserCreat[UserIndex] == 0)
   if(Sockets.IsRtcSetting[UserIndex] == 0)
{
//                  SystemUserMgr.IsUserCreat[UserIndex]  = 1;
//    UserMgrFlashUpdata();
//    SaveUserCreatFlag();
   Sockets.IsRtcSetting[UserIndex]  = 1;
   err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
   APP_ERROR_CHECK(err_code);
   SetCurDorLockUartCmdExe(DOR_LOCK_USER_MGR_CMD, DOOR_LOCK_CMD_ADD_USER , ETMARS_CMD_EXE_TRIGGER, UserIndex);
   SystemUserMgr.NormalUserMgr[UserIndex].DorLockUserName  =  TimelineUserTab[UserIndex];
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
   LockUartCmdHandle.FunCode    =  DOOR_LOCK_CMD_ADD_USER;
   LockUartCmdHandle.CurUartExeCmd  =  DOOR_LOCK_CMD_ADD_USER;
   LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
   LockUartCmdHandle.lenth      =  sizeof(SystemUserMgr.NormalUserMgr[UserIndex].DorLockUserName) +1;
   memcpy(LockUartCmdHandle.Content, SystemUserMgr.NormalUserMgr[UserIndex].DorLockUserName, sizeof(SystemUserMgr.NormalUserMgr[UserIndex].DorLockUserName));
   CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
//    UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}
     else
{
#if   0
LockUartCmdHandle.CurUartExeCmd  =  LOCK_CMD_ADD_CIPHER;
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
LockUartCmdHandle.FunCode    =  LOCK_CMD_ADD_CIPHER;
   LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
   PacketAddUserCipherCmdContent(&LockUartCmdHandle, NORMAL_USER, &SystemUserMgr);
   CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
#endif
}
}
}
#endif




void   CreatTemporUserSuccess(uint8_t UserIndex)
{
uint16_t  UserCipherMgrMask;
   UserCipherMgrMask  =  0x0001 << UserIndex;

   SystemUserMgr.UserCipherMgrFlag  |=  UserCipherMgrMask;
}




#if   DOR_LOCK_RESET_USER_CREAT_ENABLE
void   CreatTemporUserCipher(RealTime_t *TimeEnd, uint8_t *Cipher, uint8_t UserIndex, uint8_t CipherSize)
{
uint16_t  UserCipherMgrMask;
//    ret_code_t err_code;
   UserCipherMgrMask  =  0x0001 << UserIndex;

   if((SystemUserMgr.UserCipherMgrFlag & UserCipherMgrMask) ==  0)
{
// SystemUserMgr.UserCipherMgrFlag  |=  UserCipherMgrMask;

   SystemUserMgr.TemporUserMgr.CipherValidEndTime = *TimeEnd;
//    memcpy(SystemUserMgr.TemporUserMgr.DorLockOperaCipher, Cipher, sizeof(Cipher)/sizeof(Cipher[0])); 
   memcpy(SystemUserMgr.TemporUserMgr.DorLockOperaCipher, Cipher, CipherSize); 
   SystemUserMgr.TemporUserMgr.CipherLenth  =  CipherSize;
   SystemUserMgr.TemporUserMgr.DorLockUseTimeSchedul  =  TIME_IN_USING;

   UserMgrFlashUpdata();
    NRF_LOG_DEBUG("start creat Tempor User Cipher.");
// NRF_LOG_INFO("USER ID----  %x ", SystemUserMgr.UserCreatRecordTab[UserIndex]);
//    if((SystemUserMgr.UserCreatRecordTab[UserIndex] == USER_NONE_CREAT_FLAG))
//    if(SystemUserMgr.IsUserCreat[UserIndex] == 0)
//    if(Sockets.IsRtcSetting[UserIndex] == 0)
{
//    IsUserCreat[UserIndex] = 1;
//    SaveUserCreatFlag();
//    SystemUserMgr.IsUserCreat[UserIndex]  = 1;
//    UserMgrFlashUpdata();
//    Sockets.IsRtcSetting[UserIndex]  = 1;
//    err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
//    APP_ERROR_CHECK(err_code);
//    NRF_LOG_DEBUG("start creat user.");
   SetCurDorLockUartCmdExe(DOR_LOCK_USER_MGR_CMD, DOOR_LOCK_CMD_ADD_USER, ETMARS_CMD_EXE_TRIGGER, UserIndex);
SystemUserMgr.TemporUserMgr.DorLockUserName  =  TEMPOR_USER_NAME;
   LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
   LockUartCmdHandle.FunCode  = DOOR_LOCK_CMD_ADD_USER;
                  LockUartCmdHandle.CurUartExeCmd  =  DOOR_LOCK_CMD_ADD_USER;
   LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
                  LockUartCmdHandle.lenth  =  sizeof(SystemUserMgr.TemporUserMgr.DorLockUserName) + 1;
                  memcpy(LockUartCmdHandle.Content, SystemUserMgr.TemporUserMgr.DorLockUserName, sizeof(SystemUserMgr.TemporUserMgr.DorLockUserName));
CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
//    UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}
// else
{
 #if  0
   SetCurDorLockUartCmdExe(DOR_LOCK_USER_MGR_CMD, LOCK_CMD_ADD_CIPHER, ETMARS_CMD_EXE_TRIGGER, UserIndex);
LockUartCmdHandle.CurUartExeCmd  =  LOCK_CMD_ADD_CIPHER;
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
LockUartCmdHandle.FunCode    =  LOCK_CMD_ADD_CIPHER;
   LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
   PacketAddUserCipherCmdContent(&LockUartCmdHandle, TEMPOR_USER, &SystemUserMgr);
   CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
 #endif
//    UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}
}
}


#else
void   CreatTemporUserCipher(RealTime_t *TimeEnd, uint8_t *Cipher, uint8_t UserIndex, uint8_t CipherSize)
{
uint16_t  UserCipherMgrMask;
   ret_code_t err_code;
   UserCipherMgrMask  =  0x0001 << UserIndex;

   if((SystemUserMgr.UserCipherMgrFlag & UserCipherMgrMask) ==  0)
{
SystemUserMgr.UserCipherMgrFlag  |=  UserCipherMgrMask;

   SystemUserMgr.TemporUserMgr.CipherValidEndTime = *TimeEnd;
//    memcpy(SystemUserMgr.TemporUserMgr.DorLockOperaCipher, Cipher, sizeof(Cipher)/sizeof(Cipher[0])); 
   memcpy(SystemUserMgr.TemporUserMgr.DorLockOperaCipher, Cipher, CipherSize); 
   SystemUserMgr.TemporUserMgr.CipherLenth  =  CipherSize;
   SystemUserMgr.TemporUserMgr.DorLockUseTimeSchedul  =  TIME_IN_USING;

   UserMgrFlashUpdata();
NRF_LOG_DEBUG("start creat userppppppppp.");
NRF_LOG_INFO("USER ID----  %x ", SystemUserMgr.UserCreatRecordTab[UserIndex]);
//    if((SystemUserMgr.UserCreatRecordTab[UserIndex] == USER_NONE_CREAT_FLAG))
//    if(SystemUserMgr.IsUserCreat[UserIndex] == 0)
   if(Sockets.IsRtcSetting[UserIndex] == 0)
{
//    IsUserCreat[UserIndex] = 1;
//    SaveUserCreatFlag();
//    SystemUserMgr.IsUserCreat[UserIndex]  = 1;
//    UserMgrFlashUpdata();
   Sockets.IsRtcSetting[UserIndex]  = 1;
   err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
   APP_ERROR_CHECK(err_code);
   NRF_LOG_DEBUG("start creat user.");
   SetCurDorLockUartCmdExe(DOR_LOCK_USER_MGR_CMD, DOOR_LOCK_CMD_ADD_USER, ETMARS_CMD_EXE_TRIGGER, UserIndex);
SystemUserMgr.TemporUserMgr.DorLockUserName  =  TEMPOR_USER_NAME;
   LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
   LockUartCmdHandle.FunCode  = DOOR_LOCK_CMD_ADD_USER;
                  LockUartCmdHandle.CurUartExeCmd  =  DOOR_LOCK_CMD_ADD_USER;
   LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
                  LockUartCmdHandle.lenth  =  sizeof(SystemUserMgr.TemporUserMgr.DorLockUserName) + 1;
                  memcpy(LockUartCmdHandle.Content, SystemUserMgr.TemporUserMgr.DorLockUserName, sizeof(SystemUserMgr.TemporUserMgr.DorLockUserName));
CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
//    UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}
else
{
   SetCurDorLockUartCmdExe(DOR_LOCK_USER_MGR_CMD, LOCK_CMD_ADD_CIPHER, ETMARS_CMD_EXE_TRIGGER, UserIndex);
LockUartCmdHandle.CurUartExeCmd  =  LOCK_CMD_ADD_CIPHER;
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
LockUartCmdHandle.FunCode    =  LOCK_CMD_ADD_CIPHER;
   LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
   PacketAddUserCipherCmdContent(&LockUartCmdHandle, TEMPOR_USER, &SystemUserMgr);
   CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
//    UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}
}
}
#endif








bool   DelateOneNormalUserCipher(uint8_t UserIndex, uint8_t CmdTrigType)
{
//      SystemUserMgr.UserCipherMgrFlag  &=  ~(0x0001 << UserIndex);

//    UserMgrFlashUpdata();
   bool  DelateOneNormalFlag;
   if(SystemUserMgr.NormalUserMgr[UserIndex].DorLockUseTimeSchedul == TIME_IN_USING)
{
 NRF_LOG_INFO("cmd del  NormalUserPass----%x", UserIndex);
SetCurDorLockUartCmdExe(DOR_LOCK_USER_MGR_CMD, DOOR_LOCK_CMD_DEL_CIPHER, CmdTrigType, UserIndex);
LockUartCmdHandle.CurUartExeCmd  =  DOOR_LOCK_CMD_DEL_CIPHER;
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
LockUartCmdHandle.FunCode  =  DOOR_LOCK_CMD_DEL_CIPHER;
LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
PacketDelUserCipherCmdContent(&LockUartCmdHandle, NORMAL_USER, &SystemUserMgr);
CalculaLockCmdPacketLrc(&LockUartCmdHandle);
LockCmdPacketStringToUart(&LockUartCmdHandle);
 DelateOneNormalFlag  =  false;
}
else if(SystemUserMgr.NormalUserMgr[UserIndex].DorLockUseTimeSchedul  ==  BEFORE_TIME_USING)
{
 NRF_LOG_INFO("clr mgr del  NormalUserPass----%x", UserIndex);
SystemUserMgr.UserCipherMgrFlag  &=  ~(0x0001 << UserIndex);
 UserMgrFlashUpdata();
 APP_SendData[0] = APP_ReceiveData[0];
APP_SendData[1] = APP_ReceiveData[1];
APP_SendData[2] = 0x01;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
 DelateOneNormalFlag  =  true;
//  UartCmdTestStop();
}
//    UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);

return  DelateOneNormalFlag;
}








void   CancelTemporUserCipher(uint8_t UserIndex, uint8_t CmdTrigType)
{
// SystemUserMgr.UserCipherMgrFlag  &=  ~(0x0001 << UserIndex);
//    UserMgrFlashUpdata();
   
   if(SystemUserMgr.TemporUserMgr.DorLockUseTimeSchedul == TIME_IN_USING)
{
SetCurDorLockUartCmdExe(DOR_LOCK_USER_MGR_CMD, DOOR_LOCK_CMD_DEL_CIPHER, CmdTrigType, UserIndex);
LockUartCmdHandle.CurUartExeCmd  =  DOOR_LOCK_CMD_DEL_CIPHER;
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
LockUartCmdHandle.FunCode  =  DOOR_LOCK_CMD_DEL_CIPHER;
LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
PacketDelUserCipherCmdContent(&LockUartCmdHandle, TEMPOR_USER, &SystemUserMgr);
CalculaLockCmdPacketLrc(&LockUartCmdHandle);
LockCmdPacketStringToUart(&LockUartCmdHandle);
}
//    UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}








void  TimeForPermitNormalUserCipher(uint8_t UserIndex)
{
   SetCurDorLockUartCmdExe(DOR_LOCK_USER_MGR_CMD, LOCK_CMD_ADD_CIPHER, INTERNAL_TIME_ARRIVE_CMD_EXE_TRIGGER, UserIndex);
LockUartCmdHandle.CurUartExeCmd  =  LOCK_CMD_ADD_CIPHER;
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
LockUartCmdHandle.FunCode    =  LOCK_CMD_ADD_CIPHER;
LockUartCmdHandle.CurCmdExeHandle  =  UserIndex;
PacketAddUserCipherCmdContent(&LockUartCmdHandle, NORMAL_USER, &SystemUserMgr);
CalculaLockCmdPacketLrc(&LockUartCmdHandle);
LockCmdPacketStringToUart(&LockUartCmdHandle);
//    UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}






void  SetNormalUserCipherTimeSta(uint8_t UserIndex, uint8_t CipherTimeSta)
{
SystemUserMgr.NormalUserMgr[UserIndex].DorLockUseTimeSchedul  = CipherTimeSta;
}






void  SetTemporUserCipherTimeSta(uint8_t CipherTimeSta)
{
SystemUserMgr.TemporUserMgr.DorLockUseTimeSchedul  = CipherTimeSta;
}




void  LockUartUserMgrReply(uint8_t *CmdLine, uint8_t CmdSize)
{
    uint16_t  UserId;
    uint8_t   UserSelect;
    uint16_t  CmdReturnVal;
     uint8_t  CipherLenth = 0;
uint8_t   i = 8;
switch(LockUartCmdHandle.CurUartExeCmd)
{
case  DOOR_LOCK_CMD_ADD_USER:
       if(CmdLine[4] == ADD_USER_FAIL)
{
NRF_LOG_DEBUG("creat user fail.");
   LockUartCmdHandle.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
}
else if(CmdLine[4] == ADD_USER_SUCCESS)
{
NRF_LOG_DEBUG("creat user ok.");
   
   UserId  =  (((uint16_t)CmdLine[7]) << 8) | ((uint16_t)CmdLine[8]);
   if(LockUartCmdHandle.CurCmdExeHandle  == TEMPOR_USER_CMD_HANDLE)
{
   if((CmdLine[7] < 0x20)&&(CmdLine[8] == 0))
{
SystemUserMgr.UserCreatRecordTab[10] = UserId;
}
NRF_LOG_INFO("Creat TEMPOR user id[i]   ----%x  %x  %x",LockUartCmdHandle.CurCmdExeHandle, CmdLine[7], CmdLine[8]);
   UserSelect  =  TEMPOR_USER;
}
else if(LockUartCmdHandle.CurCmdExeHandle == MASTER_CMD_HANDLE)
{
   if((CmdLine[7] < 0x20)&&(CmdLine[8] == 0))
{
SystemUserMgr.UserCreatRecordTab[11] = UserId;
}
   UserSelect  =  MASTER_USER;
}
else
{
   if((CmdLine[7] < 0x20)&&(CmdLine[8] == 0))
{
SystemUserMgr.UserCreatRecordTab[LockUartCmdHandle.CurCmdExeHandle] = UserId;
}
SystemUserMgr.UserCipherMgrFlag  |=  (0x0001 << LockUartCmdHandle.CurCmdExeHandle);
UartCmdTestStop();
APP_SendData[0] = APP_ReceiveData[0];
APP_SendData[1] = APP_ReceiveData[1];
APP_SendData[2] = 0x01;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
   NRF_LOG_INFO("Creat NORMAL user id[i]   ----%x  %x  %x",LockUartCmdHandle.CurCmdExeHandle, CmdLine[7], CmdLine[8]);
   UserSelect  =  NORMAL_USER;
}

UserMgrFlashUpdata();




                              if((UserSelect == TEMPOR_USER) || (UserSelect == MASTER_USER))
{
LockUartCmdHandle.CurUartExeCmd  =  LOCK_CMD_ADD_CIPHER;
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
LockUartCmdHandle.FunCode  =  LOCK_CMD_ADD_CIPHER;
 PacketAddUserCipherCmdContent(&LockUartCmdHandle, UserSelect, &SystemUserMgr);
CalculaLockCmdPacketLrc(&LockUartCmdHandle);
LockCmdPacketStringToUart(&LockUartCmdHandle);
}
else if(UserSelect == NORMAL_USER)
{
LockUartCmdHandle.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
}

}
break;

case   LOCK_CMD_ADD_CIPHER:
       if(CmdLine[4] == 0x00)
{
NRF_LOG_DEBUG("add passcode ok. -- id %x ",  LockUartCmdHandle.CurCmdExeHandle);
   if(LockUartCmdHandle.CurCmdExeHandle  == TEMPOR_USER_CMD_HANDLE)
{
SystemUserMgr.UserCipherMgrFlag  |=  (0x0001 << TEMPOR_USER_CMD_HANDLE);
   UserMgrFlashUpdata();
   UartCmdTestStop();
   APP_SendData[0] = APP_ReceiveData[0];
                         APP_SendData[1] = 0x01;
                         ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else if(LockUartCmdHandle.CurCmdExeHandle != TEMPOR_USER_CMD_HANDLE)
{
   AddCipherTestStop();
}
}
else if(CmdLine[4] == 0x02)
{
NRF_LOG_DEBUG("add passcode error user nor in.");
}
else if(CmdLine[4] == 0x01)
{
NRF_LOG_DEBUG("add passcode jiaoyan error .");
}
else if(CmdLine[4] == 0x03)
{
NRF_LOG_DEBUG("add passcode full error .");
}
else if(CmdLine[4] == 0x04)
{
NRF_LOG_DEBUG("add  passcode  have in.");
}
else if(CmdLine[4] == 0x05)
{
NRF_LOG_DEBUG("add  passcode  time  out.");
}
NRF_LOG_INFO("LOCK_CMD_ADD_CIPHER  return %x ", CmdLine[4]);
LockUartCmdHandle.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
break;

case   DOOR_LOCK_CMD_DEL_CIPHER:
       CmdReturnVal  =  (((uint16_t)CmdLine[5]) << 8) | ((uint16_t)CmdLine[6]);
       
         if(CmdReturnVal < 0xFFFD)
{
 NRF_LOG_DEBUG("DEL  passcode  success.");
   //×îºÃÔÚÕâÀïÏòÊÖ»úApp·µ»ØÃÜÂëɾ³ý³É¹¦£¬¸ù¾Ýµ÷ÊÔ½á¹û°ì°É
   if(LockUartCmdHandle.CurCmdExeHandle != TEMPOR_USER_CMD_HANDLE)
{
 SystemUserMgr.UserCipherMgrFlag  &=  ~(0x0001 << LockUartCmdHandle.CurCmdExeHandle);
                         UserMgrFlashUpdata();
                         APP_SendData[0] = APP_ReceiveData[0];
                       APP_SendData[1] = APP_ReceiveData[1];
                       APP_SendData[2] = 0x01;
                       ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
 UartCmdTestStop();
 DelCipherTestStop();
}
else if(LockUartCmdHandle.CurCmdExeHandle == TEMPOR_USER_CMD_HANDLE)
{
SystemUserMgr.UserCipherMgrFlag  &=  ~(0x0001 << TEMPOR_USER_CMD_HANDLE);
                         UserMgrFlashUpdata();
 APP_SendData[0] = APP_ReceiveData[0];
                       APP_SendData[1] = 0x01;
                       ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
 UartCmdTestStop();
}
}
else
{
NRF_LOG_DEBUG("DEL  passcode  fail.");
}
LockUartCmdHandle.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
break;

case   LOCK_CMD_MODIFY_RTC:
       if(CmdLine[4]  ==  0x00)
           {
NRF_LOG_DEBUG("Modify  time  success.");
}
           LockUartCmdHandle.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
       break;

case   LOCK_CMD_QUERY_CIPHER:
      
       if(CmdLine[7] == 1)
{
 while(CmdLine[i] != 0)
{
CipherLenth++;
   i++;
}

if(APP_ReceiveData[0] == 0x01)
{
 NRF_LOG_INFO("lock  master0  Password----  %x   %x    %x", CmdLine[8],CmdLine[9], CmdLine[10]);
                         NRF_LOG_INFO("lock  master0  Password----  %x   %x    %x", CmdLine[11],CmdLine[12], CmdLine[13]);
                         NRF_LOG_INFO("lock  master0  Password----  %x   %x    %x", CmdLine[14],CmdLine[15], CmdLine[16]);
 NRF_LOG_INFO("lock  master0  Password----  %x   %x    %x", CmdLine[17],CmdLine[18], CmdLine[19]);
if(memcmp(&CmdLine[8], &APP_ReceiveData[2], CipherLenth) == 0)
{
   NRF_LOG_INFO("lock  master0  open success");
APP_SendData[0]  = 0x01;
   APP_SendData[1]  = 1;
   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
   DoorLockNormalOpen();
}
else
{
APP_SendData[0]  = 0x01;
   APP_SendData[1]  = 0;
   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
   LockUartCmdHandle.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
}
}
else if(APP_ReceiveData[0] == 0x3a)
{
 APP_SendData[0] = 0x3a;
 APP_SendData[1] = CipherLenth;
memcpy(&APP_SendData[2], &CmdLine[8], CipherLenth);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
}

if((APP_ReceiveData[0] == 0x3a) || (CmdLine[7] != 1))
{
LockUartCmdHandle.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
}
break;

case  LOCK_CMD_OPEN_CLOSE:
       if(CmdLine[4] == LOCK_CMD_OPEN_CLOSE)
{
if(CmdLine[5] == 0x00)
{
NRF_LOG_DEBUG("Lock  open  success.");
}
}
LockUartCmdHandle.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
break;

case   LOCK_CMD_CIPHER_UPDATA:
       if((CmdLine[5] == 0xFF)&&(CmdLine[6] == 0xFE))
{
NRF_LOG_DEBUG("UPDATA USER CIPHER  success.");
}
LockUartCmdHandle.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
break;
}
}








void  DoorLockNormalOpen(void)
{
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
   LockUartCmdHandle.CurUartExeCmd  =  LOCK_CMD_OPEN_CLOSE;
   LockUartCmdHandle.FunCode  =  LOCK_CMD_OPEN_CLOSE;
   LockUartCmdHandle.lenth    =  2;
   LockUartCmdHandle.Content[0] =  NORMAL_OPEN_LOCK;
   CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
}






void    SetLockUartCmdHandle(LockUartCmd_t  *LockUartCmd)
{
LockUartCmdHandle.CurUartExeCmd  =  LockUartCmd->CurUartExeCmd;
   LockUartCmdHandle.CmdHeader  =  LockUartCmd->CmdHeader;
   LockUartCmdHandle.FunCode    =  LockUartCmd->FunCode;
   LockUartCmdHandle.CurCmdExeHandle  = LockUartCmd->CurCmdExeHandle;
}






void  SetCurUartExeCmd(uint8_t  UartExeCmd)
{
LockUartCmdHandle.CurUartExeCmd  = UartExeCmd; 
}






void  FillInNewUserIdCode(uint8_t  CmdExeHandle, uint16_t  UserId)
{
SystemUserMgr.UserCreatRecordTab[CmdExeHandle] = UserId;
}




void  FillInTemporCipherIdCode(uint16_t  CipherId)
{
SystemUserMgr.TemporUserMgr.CipherId  = CipherId;
}




void   AddUserPassCodeOperation(uint8_t  UserType, uint8_t UserHandle)
{
LockUartCmdHandle.CurUartExeCmd  =  LOCK_CMD_ADD_CIPHER;
LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
LockUartCmdHandle.FunCode  =  LOCK_CMD_ADD_CIPHER;
   LockUartCmdHandle.CurCmdExeHandle  = UserHandle;
PacketAddUserCipherCmdContent(&LockUartCmdHandle, UserType, &SystemUserMgr);
CalculaLockCmdPacketLrc(&LockUartCmdHandle);
LockCmdPacketStringToUart(&LockUartCmdHandle);
}








void   MasterCipherQuery(void)
{
   uint16_t  CipherSerial;

   CipherSerial  =  0;

   LockUartCmdHandle.CurUartExeCmd  =  LOCK_CMD_QUERY_CIPHER;
   LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
   LockUartCmdHandle.FunCode  =  LOCK_CMD_QUERY_CIPHER;
   PacketCipherQueryCmdContent(CIPHER_USER_ID_QUERY, CipherSerial, &LockUartCmdHandle, MASTER_USER);
   CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
}








void  ModifyMasterPassCode(uint8_t PassCodeSize, uint8_t *PassCodeContent)
{
LockUartCmdHandle.CurUartExeCmd  = LOCK_CMD_CIPHER_UPDATA;
   LockUartCmdHandle.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
   LockUartCmdHandle.FunCode  = LOCK_CMD_CIPHER_UPDATA;
   LockUartCmdHandle.lenth  = 5+PassCodeSize+1;
   LockUartCmdHandle.Content[0]  = 1;
   LockUartCmdHandle.Content[1]  = 0;
   LockUartCmdHandle.Content[2]  = 0;
   LockUartCmdHandle.Content[3]  = 1;
   memcpy(&LockUartCmdHandle.Content[4],PassCodeContent,PassCodeSize);
   LockUartCmdHandle.Content[PassCodeSize+4] = 0x00;
   CalculaLockCmdPacketLrc(&LockUartCmdHandle);
   LockCmdPacketStringToUart(&LockUartCmdHandle);
}






uint8_t GetCurUartExeCmd(void)
{
return  LockUartCmdHandle.CurUartExeCmd;

}



#include  "cmd_packet.h"
#include  "dr_lock_cmd.h"
#include  "nrf_log.h"
#include  "lock_cmd_def.h"




#define  CMD_STR_SIZE   150






void CalculaLockCmdPacketLrc(LockUartCmd_t *LockUartCmd)
{
   uint8_t  i;
LockUartCmd->Lcr = 0x0000;
   LockUartCmd->Lcr +=  LockUartCmd->lenth;
   LockUartCmd->Lcr +=  LockUartCmd->FunCode;

   for(i = 0; i < LockUartCmd->lenth-1; i++)
   {
LockUartCmd->Lcr += LockUartCmd->Content[i];
}
}








void LockCmdPacketStringToUart(LockUartCmd_t *LockUartCmd)
{
uint8_t  LockCmdStrData[CMD_STR_SIZE];
   uint8_t  i;

   LockCmdStrData[0]  =  LockUartCmd->CmdHeader;
      LockCmdStrData[1]  =  (uint8_t)((LockUartCmd->Lcr >> 8) & 0x000000FF);
      LockCmdStrData[2] =  (uint8_t)(LockUartCmd->Lcr & 0x000000FF);
   LockCmdStrData[3]  =  LockUartCmd->lenth;
   LockCmdStrData[4]  =  LockUartCmd->FunCode;

   for(i = 0; i < LockUartCmd->lenth-1; i++)
   {
LockCmdStrData[i+5] =  LockUartCmd->Content[i];
}
NRF_LOG_INFO("lock----  %x   %x    %x", LockCmdStrData[0],LockCmdStrData[1], LockCmdStrData[2]);
NRF_LOG_INFO("lock----  %x   %x    %x", LockCmdStrData[3],LockCmdStrData[4], LockCmdStrData[5]);
NRF_LOG_INFO("lock----  %x   %x    %x", LockCmdStrData[6],LockCmdStrData[7], LockCmdStrData[8]);


// UartSendBytesToDorLock(LockCmdStrData, LockUartCmd->lenth+4);
send_data_to_boad(LockCmdStrData, LockUartCmd->lenth+4);
}








void  PacketAddUserCipherCmdContent(LockUartCmd_t *LockUartCmdHandle, uint8_t UserType, SystemUserMgr_t *SystemUserMgr)
{
   uint8_t  UserHandle;
   uint8_t  PassCodeSize;
switch(UserType)
{
case  NORMAL_USER:
     UserHandle   =  LockUartCmdHandle->CurCmdExeHandle;
PassCodeSize =  SystemUserMgr->NormalUserMgr[UserHandle].CipherLenth;
     memset(LockUartCmdHandle->Content, 0, sizeof(LockUartCmdHandle->Content));
     LockUartCmdHandle->Content[0] = 0xFF;
       LockUartCmdHandle->Content[1] = 0XFF;
       LockUartCmdHandle->Content[2] = (uint8_t)(SystemUserMgr->UserCreatRecordTab[UserHandle] >> 8);
       LockUartCmdHandle->Content[3] = (uint8_t)(SystemUserMgr->UserCreatRecordTab[UserHandle]);
       NRF_LOG_INFO("use NORMAL user id[i]   ----%x  %x  %x",LockUartCmdHandle->CurCmdExeHandle, LockUartCmdHandle->Content[2], LockUartCmdHandle->Content[3]);
//        memcpy(&LockUartCmdHandle->Content[0],TimelineUserTab[UserHandle],sizeof(TimelineUserTab[UserHandle])-1);
LockUartCmdHandle->Content[9] = 0x01;
memcpy(&LockUartCmdHandle->Content[10], SystemUserMgr->NormalUserMgr[UserHandle].DorLockOperaCipher,PassCodeSize);
       LockUartCmdHandle->Content[10+PassCodeSize] = 0x00;
       LockUartCmdHandle->lenth  =  1+9+1+PassCodeSize+1;
//        LockUartCmdHandle->Content[10+PassCodeSize] = 0x00;
//        LockUartCmdHandle->lenth  =  1+9+1+6+1;
break;

case  TEMPOR_USER:
     UserHandle   =  LockUartCmdHandle->CurCmdExeHandle;
       PassCodeSize =  SystemUserMgr->TemporUserMgr.CipherLenth;
memset(LockUartCmdHandle->Content, 0, sizeof(LockUartCmdHandle->Content));
       LockUartCmdHandle->Content[0] = 0xFF;
       LockUartCmdHandle->Content[1] = 0XFF;
       LockUartCmdHandle->Content[2] = (uint8_t)(SystemUserMgr->UserCreatRecordTab[UserHandle] >> 8);
       LockUartCmdHandle->Content[3] = (uint8_t)(SystemUserMgr->UserCreatRecordTab[UserHandle]);
       NRF_LOG_INFO("use TEMPOR user id[i]   ----%x  %x  %x",LockUartCmdHandle->CurCmdExeHandle, LockUartCmdHandle->Content[2], LockUartCmdHandle->Content[3]);
       LockUartCmdHandle->Content[9] = 0x01;
memcpy(&LockUartCmdHandle->Content[10], SystemUserMgr->TemporUserMgr.DorLockOperaCipher, PassCodeSize);
       LockUartCmdHandle->Content[10+PassCodeSize] = 0x00;
LockUartCmdHandle->lenth  =  1+9+1+PassCodeSize+1;
break;

case  MASTER_USER:
break;
}
}








void  PacketDelUserCipherCmdContent(LockUartCmd_t *LockUartCmdHandle, uint8_t UserType, SystemUserMgr_t *SystemUserMgr)
{
uint8_t  UserHandle;
   uint8_t  PassCodeSize;
if(UserType  == NORMAL_USER)
{
    UserHandle   =  LockUartCmdHandle->CurCmdExeHandle;
    PassCodeSize =  SystemUserMgr->NormalUserMgr[UserHandle].CipherLenth;
    memset(LockUartCmdHandle->Content, 0, sizeof(LockUartCmdHandle->Content));
      LockUartCmdHandle->Content[0] = 0xFF;
    LockUartCmdHandle->Content[1] = 0XFF;
    LockUartCmdHandle->Content[2] = (uint8_t)(SystemUserMgr->UserCreatRecordTab[UserHandle] >> 8);
    LockUartCmdHandle->Content[3] = (uint8_t)(SystemUserMgr->UserCreatRecordTab[UserHandle]);
    
    LockUartCmdHandle->Content[9] = 0x01;
    memcpy(&LockUartCmdHandle->Content[10], SystemUserMgr->NormalUserMgr[UserHandle].DorLockOperaCipher, PassCodeSize);
    LockUartCmdHandle->Content[10+PassCodeSize] = 0x00;
    LockUartCmdHandle->lenth  =  1+9+1+PassCodeSize+1;
}
else if(UserType  == TEMPOR_USER)
{
UserHandle   =  LockUartCmdHandle->CurCmdExeHandle;
    PassCodeSize =  SystemUserMgr->TemporUserMgr.CipherLenth;
memset(LockUartCmdHandle->Content, 0, sizeof(LockUartCmdHandle->Content));
    LockUartCmdHandle->Content[0] = 0xFF;
    LockUartCmdHandle->Content[1] = 0XFF;
    LockUartCmdHandle->Content[2] = (uint8_t)(SystemUserMgr->UserCreatRecordTab[UserHandle] >> 8);
    LockUartCmdHandle->Content[3] = (uint8_t)(SystemUserMgr->UserCreatRecordTab[UserHandle]);
    LockUartCmdHandle->Content[9] = 0x01;
    memcpy(&LockUartCmdHandle->Content[10], SystemUserMgr->TemporUserMgr.DorLockOperaCipher, PassCodeSize);
    LockUartCmdHandle->Content[10+PassCodeSize] = 0x00;
LockUartCmdHandle->lenth  =  1+9+1+PassCodeSize+1;
}
}










void  PacketCipherQueryCmdContent(uint8_t  CipherQueryType, uint16_t  CipherSerial, LockUartCmd_t *LockUartCmdHandle, uint8_t UserType)
{
if(CipherQueryType  ==  CIPHER_USER_ID_QUERY)
{
LockUartCmdHandle->Content[0] =  (uint8_t)CipherSerial;
   LockUartCmdHandle->Content[1] =  (uint8_t)(CipherSerial >> 8);
   if(UserType == MASTER_USER)
{
LockUartCmdHandle->Content[2] = 0xFF;
   LockUartCmdHandle->Content[3] = 0xFF;
   LockUartCmdHandle->Content[4] = 0x00;
   LockUartCmdHandle->Content[5] = 0x00;
}

LockUartCmdHandle->lenth  =  7;
}
}








#include  "app_timer.h"
#include  "dorlock_user_mgr.h"
#include  "dr_lock_cmd.h"
#include  "nrf_log.h"
#include  "cmd_packet.h"
#include  "bd_wall_clock_timer.h"
#include  "lock_cmd_def.h"
#include  "dorlock_cmd_rsp.h"
#include  "user_cipher_mgr.h"


#define   CIPHER_TIME_USE_MGR_NUM     (PRESCRIP_USER_SIZE+1)
#define   TEMPOR_USER_PASSCODE_MGR_HANDLE    TEMPOR_ID_SIGN_POS




#define   CIPHER_MGR_SHORT_DELAY_TIME    20
#define   CIPHER_MGR_LONG_DELAY_TIME     3000


APP_TIMER_DEF(CipherMgrClk);







LockUartCmd_t   RtcExeCmd;




void  CipherMgrHandle(void * p_context);
//bool  UserPassCodeTimeMgr(uint8_t UserHandle, uint8_t UseTimePeriod, RealTime_t *Mts, RealTime_t *Mte, RealTime_t *LocalTime, uint16_t CipherExsitFlag);








void    CreatCipherMgrEvt(void)
{
uint32_t  error;

   error   =  app_timer_create(&CipherMgrClk, APP_TIMER_MODE_SINGLE_SHOT, CipherMgrHandle);
   APP_ERROR_CHECK(error);
}






void  CipherMgrTaskStart(uint16_t  TaskDelay)
{
   uint32_t  error;
error = app_timer_start(CipherMgrClk, APP_TIMER_TICKS(TaskDelay), NULL);
APP_ERROR_CHECK(error);
}






void  CipherMgrTaskStop(void)
{
uint32_t  error;
  error = app_timer_stop(CipherMgrClk);
APP_ERROR_CHECK(error);
}






#if   0
void  CipherMgrHandle(void * p_context)
{
  LockUartCmd_t  LockUartCmd;
  GetUserMgrCmdHandleAdd(&LockUartCmd);
//   (LockUartCmd.CurUartExeCmd ==  DOOR_LOCK_CMD_IDLE)&&
  if((RtcExeCmd.CurUartExeCmd == DOOR_LOCK_CMD_IDLE))
{
RtcExeCmd.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
RtcExeCmd.FunCode    =  LOCK_CMD_READ_RTC;
RtcExeCmd.CurUartExeCmd  =  LOCK_CMD_READ_RTC;
RtcExeCmd.lenth   = 1;
CalculaLockCmdPacketLrc(&RtcExeCmd);
LockCmdPacketStringToUart(&RtcExeCmd);
  
}
else
{
CipherMgrTaskStart(CIPHER_MGR_SHORT_DELAY_TIME);
}
}
#endif






void  CipherMgrHandle(void * p_context)
{
static  uint8_t  UserScanIndex = 0;
   SystemUserMgr_t  UserLockUseMgr;
   uint8_t   TimeModifyFlag;
   UTCTimeStruct *time;
   uint8_t   Yearl;
   uint8_t   month;
   uint8_t   day;
   uint8_t   hour;
   uint8_t   minute;
   uint16_t  year;

   time  =  get_wall_clock_time();
   GetSystemUserMgrAdd(&UserLockUseMgr);

  

   NRF_LOG_INFO("lock time----  %d   %d    %d", time->day,time->hour, time->minutes);

   if(UserScanIndex  ==  TEMPOR_USER_PASSCODE_MGR_HANDLE)
{
if(UserLockUseMgr.UserCipherMgrFlag & (0x0001 << UserScanIndex))
{
if(UserLockUseMgr.TemporUserMgr.DorLockUseTimeSchedul == TIME_IN_USING)
{

 TimeModifyFlag   = 0x00;
 
 Yearl  =  UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Yearl;
 month =  UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Month;
 day   =  UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Day;
 hour  =  UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Hour;
 minute = UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Minute;

 Yearl  =  (Yearl>>4)*10+ (Yearl&0x0f);
  year  =  2000 + Yearl;
   month =  (month>>4)*10+ (month&0x0f);
   day =  (day>>4)*10+ (day&0x0f);
   hour =  (hour>>4)*10+ (hour&0x0f);
   minute =  (minute>>4)*10+ (minute&0x0f);

   if(year  ==  time->year) 
{
TimeModifyFlag |= 0x01;
//    NRF_LOG_INFO("tempor user end time year  user[i]----  %d  %d", year, UserScanIndex);
}

if(month ==  time->month)
{
TimeModifyFlag |= 0x02;
//   NRF_LOG_INFO("tempor user end time month  user[i]----  %d  %d", month, UserScanIndex);
}

if(day ==  time->day)
{
TimeModifyFlag |= 0x04;
//    NRF_LOG_INFO("tempor user end time day  user[i]----  %d  %d", day, UserScanIndex);

}

if(hour < time->hour)
{
TimeModifyFlag |= 0x08;
//    NRF_LOG_INFO("tempor user end time hour  user[i]----  %d  %d", hour, UserScanIndex);
}
else if(hour == time->hour)
{
if(minute <= time->minutes)
{
TimeModifyFlag |= 0x08;
}
}


 //NRF_LOG_INFO("tempor user end time Hour ----  %d %d", hour, UserScanIndex);
//NRF_LOG_INFO("tempor user end time Minute ----  %d %d", minute, UserScanIndex);
if(TimeModifyFlag == 0x0F)
{
 if(!MonitorUartBusyExe())
{
 CancelTemporUserCipher(UserScanIndex, INTERNAL_TIME_ARRIVE_CMD_EXE_TRIGGER);
 #if  0
 SetTemporUserCipherTimeSta(AFTER_TIME_USING);
 #endif
 UserScanIndex = 0;
                          }  
   }
else
{
UserScanIndex = 0;
}

CipherMgrTaskStart(CIPHER_MGR_LONG_DELAY_TIME);
}
}
else
{
UserScanIndex = 0;
   CipherMgrTaskStart(CIPHER_MGR_LONG_DELAY_TIME);
}
}
else
{

for(uint8_t i = 0; i < 10; i++) {

if((UserLockUseMgr.UserCipherMgrFlag & (0x0001 << i))&&(UserLockUseMgr.NormalUserMgr[i].DorLockUseTimeSchedul  == BEFORE_TIME_USING)) {
     UserScanIndex = i;
   break;
}
}

if(UserLockUseMgr.UserCipherMgrFlag & (0x0001 << UserScanIndex))
{
#if   0
   NRF_LOG_INFO("normal user  pwd  index ----  %x", UserScanIndex);
   NRF_LOG_INFO("normal user  pwd0 ----  %x", UserLockUseMgr.NormalUserMgr[UserScanIndex].DorLockOperaCipher[0]);
   NRF_LOG_INFO("normal user  pwd1 ----  %x", UserLockUseMgr.NormalUserMgr[UserScanIndex].DorLockOperaCipher[1]);
   NRF_LOG_INFO("normal user  pwd2 ----  %x", UserLockUseMgr.NormalUserMgr[UserScanIndex].DorLockOperaCipher[2]);
   NRF_LOG_INFO("normal user  pwd3 ----  %x", UserLockUseMgr.NormalUserMgr[UserScanIndex].DorLockOperaCipher[3]);
   NRF_LOG_INFO("normal user  pwd4 ----  %x", UserLockUseMgr.NormalUserMgr[UserScanIndex].DorLockOperaCipher[4]);
   NRF_LOG_INFO("normal user  pwd5 ----  %x", UserLockUseMgr.NormalUserMgr[UserScanIndex].DorLockOperaCipher[5]);
 #endif
   TimeModifyFlag   = 0x00;
if(UserLockUseMgr.NormalUserMgr[UserScanIndex].DorLockUseTimeSchedul  == BEFORE_TIME_USING)
{
Yearl  =  UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidStartTime.Yearl;
   month =  UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidStartTime.Month;
   day   =  UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidStartTime.Day;
   hour  =  UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidStartTime.Hour;
   minute = UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidStartTime.Minute;

   Yearl  =  (Yearl>>4)*10+ (Yearl&0x0f);
   year  =  2000 + Yearl;
   month =  (month>>4)*10+ (month&0x0f);
   day =  (day>>4)*10+ (day&0x0f);
   hour =  (hour>>4)*10+ (hour&0x0f);
   minute =  (minute>>4)*10+ (minute&0x0f);

   if(year  ==  time->year) 
{
TimeModifyFlag |= 0x01;
//  NRF_LOG_INFO("notmal user start time year  user[i]----  %d  %d", year, UserScanIndex);
}

if(month ==  time->month)
{
TimeModifyFlag |= 0x02;
//   NRF_LOG_INFO("notmal user start time month  user[i]----  %d  %d", month, UserScanIndex);
}

if(day ==  time->day)
{
TimeModifyFlag |= 0x04;
//   NRF_LOG_INFO("notmal user start time day  user[i]----  %d  %d", day, UserScanIndex);

}

if(hour < time->hour)
{
TimeModifyFlag |= 0x08;
 //  NRF_LOG_INFO("notmal user start time hour  user[i]----  %d  %d", hour, UserScanIndex);
}
else if(hour == time->hour)
{
if(minute <= time->minutes)
{
TimeModifyFlag |= 0x08;
}
}
//NRF_LOG_INFO("notmal user start time Hour ----  %d  %d", hour, UserScanIndex);
// NRF_LOG_INFO("notmal user start time Minute ----  %d %d", minute, UserScanIndex);

if(TimeModifyFlag == 0x0F)
{
 if(!MonitorUartBusyExe())
{
TimeForPermitNormalUserCipher(UserScanIndex);
SetNormalUserCipherTimeSta(UserScanIndex, TIME_IN_USING);
#if  1
 AddCipherTestStart(700);
 SetAddCipherFailHandle(UserScanIndex);
#endif
 NRF_LOG_INFO("pwd creat id  ----  %d %d",UserScanIndex);
 UserScanIndex++;
}
}
else
{
UserScanIndex++;
}
CipherMgrTaskStart(CIPHER_MGR_LONG_DELAY_TIME);
}
else if(UserLockUseMgr.NormalUserMgr[UserScanIndex].DorLockUseTimeSchedul == TIME_IN_USING)
{
Yearl  =  UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidEndTime.Yearl;
   month =  UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidEndTime.Month;
   day   =  UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidEndTime.Day;
   hour  =  UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidEndTime.Hour;
   minute = UserLockUseMgr.NormalUserMgr[UserScanIndex].CipherValidEndTime.Minute;

   Yearl  =  (Yearl>>4)*10+ (Yearl&0x0f);
   year  =  2000 + Yearl;
   month =  (month>>4)*10+ (month&0x0f);
   day =  (day>>4)*10+ (day&0x0f);
   hour =  (hour>>4)*10+ (hour&0x0f);
   minute =  (minute>>4)*10+ (minute&0x0f);

   if(year  ==  time->year) 
{
TimeModifyFlag |= 0x01;
   //NRF_LOG_INFO("notmal  user  end time year  user[i]----  %d  %d", year, UserScanIndex);
}

if(month ==  time->month)
{
TimeModifyFlag |= 0x02;
  // NRF_LOG_INFO("notmal user  end time month  user[i]----  %d  %d", month, UserScanIndex);
}

if(day ==  time->day)
{
TimeModifyFlag |= 0x04;
  // NRF_LOG_INFO("notmal user  end time day  user[i]----  %d  %d", day, UserScanIndex);

}

if(hour < time->hour)
{
TimeModifyFlag |= 0x08;
 //  NRF_LOG_INFO("notmal user  end  time hour  user[i]----  %d  %d", hour, UserScanIndex);
}
else if(hour == time->hour)
{
if(minute <= time->minutes)
{
TimeModifyFlag |= 0x08;
}
}

//NRF_LOG_INFO("notmal user  end time Hour ----  %d ", hour);
 //NRF_LOG_INFO("notmal user  end time Minute ----  %d ", minute);

if(TimeModifyFlag == 0x0F)
 {
 if(!MonitorUartBusyExe())
 {
bool  DelateFlag;

 DelateFlag  =  DelateOneNormalUserCipher(UserScanIndex, INTERNAL_TIME_ARRIVE_CMD_EXE_TRIGGER);
                        //      SetNormalUserCipherTimeSta(UserScanIndex, AFTER_TIME_USING);
                              #if  1
// AddCipherTestStart(500);
// SetAddCipherFailHandle(UserScanIndex);
if(DelateFlag  == false)
{
DelCipherTestStart(700);
SetDelCipherFailHandle(UserScanIndex);
}
#endif
                              UserScanIndex++;
}
 }
 else
 {
UserScanIndex++;
 }

CipherMgrTaskStart(CIPHER_MGR_LONG_DELAY_TIME);
}
}
else
{
UserScanIndex++;
   CipherMgrTaskStart(CIPHER_MGR_LONG_DELAY_TIME);
}
}
}








#if  0
void   LockUartRtcUserMgrTask(uint8_t *cmdLine, uint8_t data_len)
{
  static  SystemUserMgr_t  UserLockUseMgr;
  RealTime_t  PassCodeMgrTimeStart;
  RealTime_t  PassCodeMgrTimeEnd;
  RealTime_t  DorLockLocalTime;
  uint16_t  UserCipherExsitFlag;
  static  uint8_t   Year;
  static  uint8_t   month;
  static  uint8_t   day;
  static  uint8_t   hour;
  static  uint8_t   minute;
  static  uint8_t   i;
  static  uint8_t   RtcUserMgrTaskExeSta = 0;
  uint8_t  UserPassCodeUseTimePeriod;
  bool  IsCurUserAddDelOpera;
 
  if(RtcExeCmd.CurUartExeCmd  ==  LOCK_CMD_READ_RTC)
{
if(RtcUserMgrTaskExeSta == 0)
{
if(cmdLine[4]  ==  0x00)
{
RtcUserMgrTaskExeSta  = 1;
GetSystemUserMgrAdd(&UserLockUseMgr);
Year  = cmdLine[5];
month = cmdLine[6];
day   = cmdLine[7];
hour  = cmdLine[8];
minute =  cmdLine[9];
 UserCipherExsitFlag  =  UserLockUseMgr.UserCipherMgrFlag;
 DorLockLocalTime.Yearl = Year;
 DorLockLocalTime.Month = month;
 DorLockLocalTime.Day   = day;
 DorLockLocalTime.Hour  = hour;
 DorLockLocalTime.Minute  = minute;
 NRF_LOG_INFO("lock time----  %x   %x    %x", day,hour, minute);
for(i = 0; i< CIPHER_TIME_USE_MGR_NUM; i++)
{
   if(i == TEMPOR_USER_PASSCODE_MGR_HANDLE)
{
UserPassCodeUseTimePeriod  = UserLockUseMgr.TemporUserMgr.DorLockUseTimeSchedul;
   PassCodeMgrTimeStart  =  UserLockUseMgr.TemporUserMgr.CipherValidStartTime;
   PassCodeMgrTimeEnd    =  UserLockUseMgr.TemporUserMgr.CipherValidEndTime;
}
else
{
UserPassCodeUseTimePeriod  = UserLockUseMgr.NormalUserMgr[i].DorLockUseTimeSchedul;
   PassCodeMgrTimeStart  =  UserLockUseMgr.NormalUserMgr[i].CipherValidStartTime;
   PassCodeMgrTimeEnd    =  UserLockUseMgr.NormalUserMgr[i].CipherValidEndTime;
}
   
                         
IsCurUserAddDelOpera  =  UserPassCodeTimeMgr(i, UserPassCodeUseTimePeriod, &PassCodeMgrTimeStart, &PassCodeMgrTimeEnd, &DorLockLocalTime, UserCipherExsitFlag);

if(IsCurUserAddDelOpera)
{
break;
}
}

if(i  >=  CIPHER_TIME_USE_MGR_NUM)
{
   RtcUserMgrTaskExeSta  = 0;
   RtcExeCmd.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
CipherMgrTaskStart(CIPHER_MGR_LONG_DELAY_TIME);
}
}
else
{
CipherMgrTaskStart(CIPHER_MGR_SHORT_DELAY_TIME);
}
}
          else if(RtcUserMgrTaskExeSta  == 1)
{
 UserCipherExsitFlag  =  UserLockUseMgr.UserCipherMgrFlag;
 DorLockLocalTime.Yearl = Year;
DorLockLocalTime.Month = month;
DorLockLocalTime.Day   = day;
DorLockLocalTime.Hour  = hour;
DorLockLocalTime.Minute  = minute;
 do
{
i++;
if(i >= CIPHER_TIME_USE_MGR_NUM)
{
RtcUserMgrTaskExeSta  = 0;
   RtcExeCmd.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
CipherMgrTaskStart(CIPHER_MGR_LONG_DELAY_TIME);
break;
}

if(i == TEMPOR_USER_PASSCODE_MGR_HANDLE)
{
UserPassCodeUseTimePeriod  = UserLockUseMgr.TemporUserMgr.DorLockUseTimeSchedul;
PassCodeMgrTimeStart  =  UserLockUseMgr.TemporUserMgr.CipherValidStartTime;
PassCodeMgrTimeEnd    =  UserLockUseMgr.TemporUserMgr.CipherValidEndTime;
}
else
 {
UserPassCodeUseTimePeriod  = UserLockUseMgr.NormalUserMgr[i].DorLockUseTimeSchedul;
PassCodeMgrTimeStart  =  UserLockUseMgr.NormalUserMgr[i].CipherValidStartTime;
 PassCodeMgrTimeEnd    =  UserLockUseMgr.NormalUserMgr[i].CipherValidEndTime;
}

IsCurUserAddDelOpera  =  UserPassCodeTimeMgr(i, UserPassCodeUseTimePeriod, &PassCodeMgrTimeStart, &PassCodeMgrTimeEnd, &DorLockLocalTime, UserCipherExsitFlag);

} while(!IsCurUserAddDelOpera);
}
}
 else if(RtcExeCmd.CurUartExeCmd  ==  LOCK_CMD_MODIFY_RTC)
{
if(cmdLine[4]  ==  0x00)
{
NRF_LOG_DEBUG("Modify  time  success.");
}
RtcExeCmd.CurUartExeCmd  = DOOR_LOCK_CMD_IDLE;
}
}
#endif




#if   0
bool   UserPassCodeTimeMgr(uint8_t UserHandle, uint8_t UseTimePeriod, RealTime_t *Mts, RealTime_t *Mte, RealTime_t *LocalTime, uint16_t CipherExsitFlag)
{
 uint8_t   TimeModifyFlag;
 bool   IsCurUserAddDelOpera;

if((CipherExsitFlag) & (0x0001 << UserHandle))
{
   TimeModifyFlag   = 0x00;
if(UserHandle == TEMPOR_USER_PASSCODE_MGR_HANDLE)
{
if(UseTimePeriod == TIME_IN_USING)
{
if(Mte->Yearl == LocalTime->Yearl)
{
TimeModifyFlag  |= 0x01;
 NRF_LOG_INFO("tempor time Mte->Yearl ----  %x ", Mte->Yearl);
}

if(Mte->Month == LocalTime->Month)
{
TimeModifyFlag  |= 0x02;
 NRF_LOG_INFO("tempor time Mte->Month ----  %x ", Mte->Month);
}

if(Mte->Day == LocalTime->Day)
{
TimeModifyFlag  |= 0x04;
 NRF_LOG_INFO("tempor time Mte->Day ----  %x ", Mte->Day);
}

if(Mte->Hour < LocalTime->Hour)
{
TimeModifyFlag  |= 0x08;
}
else if(Mte->Hour == LocalTime->Hour)
{
   if(Mte->Minute <= LocalTime->Minute)
TimeModifyFlag  |= 0x08;
}
NRF_LOG_INFO("tempor time Mte->Hour ----  %x ", Mte->Hour);
NRF_LOG_INFO("tempor time Mte->Minute ----  %x ", Mte->Minute);
if(TimeModifyFlag == 0x0F)
{
CancelTemporUserCipher(UserHandle);
                            IsCurUserAddDelOpera  =  true;
//                            SetNormalUserCipherTimeSta(UserHandle, AFTER_TIME_USING);
}
else
{
IsCurUserAddDelOpera  = false;
}

NRF_LOG_DEBUG("TEMPOR  UseTimePeriod  handle.");
}
}
else
{
if(UseTimePeriod == BEFORE_TIME_USING)
{
if(Mts->Yearl == LocalTime->Yearl)

TimeModifyFlag  |= 0x01;

if(Mts->Month == LocalTime->Month)
TimeModifyFlag  |= 0x02;

if(Mts->Day == LocalTime->Day)
TimeModifyFlag  |= 0x04;

if(Mts->Hour < LocalTime->Hour)
{
TimeModifyFlag  |= 0x08;
}
else if(Mts->Hour == LocalTime->Hour)
{
   if(Mts->Minute <= LocalTime->Minute)
TimeModifyFlag  |= 0x08;
}

if(TimeModifyFlag == 0x0F)
{
TimeForPermitNormalUserCipher(UserHandle);
                            IsCurUserAddDelOpera  =  true;
                            SetNormalUserCipherTimeSta(UserHandle, TIME_IN_USING);
}
else
{
IsCurUserAddDelOpera  = false;
}
}
else if(UseTimePeriod == TIME_IN_USING)
{
if(Mte->Yearl == LocalTime->Yearl)
TimeModifyFlag  |= 0x01;

if(Mte->Month == LocalTime->Month)
TimeModifyFlag  |= 0x02;

if(Mte->Day == LocalTime->Day)
TimeModifyFlag  |= 0x04;

if(Mte->Hour < LocalTime->Hour)
{
TimeModifyFlag  |= 0x08;
}
else if(Mte->Hour == LocalTime->Hour)
{
   if(Mte->Minute <= LocalTime->Minute)
TimeModifyFlag  |= 0x08;
}

if(TimeModifyFlag == 0x0F)
{
DelateOneNormalUserCipher(UserHandle);
                            IsCurUserAddDelOpera  =  true;
                            SetNormalUserCipherTimeSta(UserHandle, AFTER_TIME_USING);
}
else
{
IsCurUserAddDelOpera  = false;
}
}
}
}
else
{
IsCurUserAddDelOpera  = false;
}
 
return  IsCurUserAddDelOpera;
}
#endif






bool   ModifyLockLocalTime(RealTime_t *LocalTime)
{
LockUartCmd_t  LockUartCmd;
  bool  IsExeModifyTimeCmd;
  GetUserMgrCmdHandleAdd(&LockUartCmd);

  if(!MonitorUartBusyExe())
{
IsExeModifyTimeCmd  =  true;
     SetCurDorLockUartCmdExe(DOR_LOCK_TIME_MGR_CMD, LOCK_CMD_MODIFY_RTC , ETMARS_CMD_EXE_TRIGGER, 0xFF);
//      UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
     RtcExeCmd.CmdHeader  =  DOOR_LOCK_CMD_HEAD;
   RtcExeCmd.FunCode    =  LOCK_CMD_MODIFY_RTC;
   RtcExeCmd.CurUartExeCmd  =  LOCK_CMD_MODIFY_RTC;
     SetCurUartExeCmd(LOCK_CMD_MODIFY_RTC);
   RtcExeCmd.lenth   = 7;
     RtcExeCmd.Content[0] = LocalTime->Yearl;
     RtcExeCmd.Content[1] = LocalTime->Month;
     RtcExeCmd.Content[2] = LocalTime->Day;
     RtcExeCmd.Content[3] = LocalTime->Hour;
     RtcExeCmd.Content[4] = LocalTime->Minute;
     RtcExeCmd.Content[5] = LocalTime->Second;
   CalculaLockCmdPacketLrc(&RtcExeCmd);
   LockCmdPacketStringToUart(&RtcExeCmd);
//      UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}
else
{
 IsExeModifyTimeCmd  =  false;
}
 
return  IsExeModifyTimeCmd;
}





#include  "app_timer.h"
#include  "dorlock_user_mgr.h"
#include  "ble_nus.h"
#include  "string.h"
#include  "BleCommand.h"
#include  "rtc_cripht_mgr.h"
#include  "dorlock_user_mgr.h"
#include  "user_cipher_mgr.h"
#include  "dorlock_cmd_rsp.h"
#include  "lock_cmd_def.h"
#include  "nrf_log.h"


#define  NOR_USER_CIPHER_SERIAL        PRESCRIP_USER_SIZE
#define  TEMPOR_USER_CIPHER_HANDLE     TEMPOR_ID_SIGN_POS
#define  PASS_CODE_SIZE     6


APP_TIMER_DEF(NorUserCipherTxClk);
APP_TIMER_DEF(UartCmdTestClk);
APP_TIMER_DEF(AddCipherTestClk);
APP_TIMER_DEF(DelCipherTestClk);




void   UartCmdTestHandle(void * p_context);
void  NorUserCipherInforTx(void * p_context);
void   AddCipherTest(void * p_context);
void  DelCipherTest(void * p_context);
void  SetTemporUserPassCodeInfor(void);


bool  UartCmdTestBootFlag = false;
uint8_t  AddCipherFailUserNum;
uint8_t  DelCipherFailUserNum;


void  CreatNorUserCipherEvt(void)
{
uint32_t  error;

   error   =  app_timer_create(&NorUserCipherTxClk, APP_TIMER_MODE_SINGLE_SHOT, NorUserCipherInforTx);
   APP_ERROR_CHECK(error);
}




void  CreatAddCipherTestEvt(void)
{
uint32_t  error;

   error   =  app_timer_create(&AddCipherTestClk, APP_TIMER_MODE_SINGLE_SHOT, AddCipherTest);
   APP_ERROR_CHECK(error);
}




void  CreatDelCipherTestEvt(void)
{
uint32_t  error;

   error   =  app_timer_create(&DelCipherTestClk, APP_TIMER_MODE_SINGLE_SHOT, DelCipherTest);
   APP_ERROR_CHECK(error);
}




void  DelCipherTestStart(uint16_t  TaskDelay)
{
uint32_t  error;
error = app_timer_start(DelCipherTestClk, APP_TIMER_TICKS(TaskDelay), NULL);
APP_ERROR_CHECK(error);
}






void  DelCipherTestStop(void)
{
uint32_t  error;
   error  =  app_timer_stop(DelCipherTestClk);
   APP_ERROR_CHECK(error);
}  






void  CreatUartCmdTestEvt(void)
{
uint32_t  error;

   error   =  app_timer_create(&UartCmdTestClk, APP_TIMER_MODE_SINGLE_SHOT, UartCmdTestHandle);
   APP_ERROR_CHECK(error);
}




void  AddCipherTestStart(uint16_t  TaskDelay)
{
uint32_t  error;
error = app_timer_start(AddCipherTestClk, APP_TIMER_TICKS(TaskDelay), NULL);
APP_ERROR_CHECK(error);
}




void  AddCipherTestStop(void)
{
uint32_t  error;
   error  =  app_timer_stop(AddCipherTestClk);
   APP_ERROR_CHECK(error);
}






void  NorUserCipherTxStart(uint16_t  TaskDelay)
{
   uint32_t  error;
error = app_timer_start(NorUserCipherTxClk, APP_TIMER_TICKS(TaskDelay), NULL);
APP_ERROR_CHECK(error);
}






void  UartCmdTestStart(uint16_t  TaskDelay)
{
   uint32_t  error;
error = app_timer_start(UartCmdTestClk, APP_TIMER_TICKS(TaskDelay), NULL);
APP_ERROR_CHECK(error);
}






void  UartCmdTestStop(void)
{
uint32_t  error;
   error  =  app_timer_stop(UartCmdTestClk);
   APP_ERROR_CHECK(error);
}






void   SetAddCipherFailHandle(uint8_t UserScanIndex)
{
AddCipherFailUserNum  =  UserScanIndex;
}






void   SetDelCipherFailHandle(uint8_t UserScanIndex)
{
DelCipherFailUserNum  =  UserScanIndex;
}






void  DelCipherTest(void * p_context)
{
if(GetCurUartExeCmd() != DOOR_LOCK_CMD_IDLE)
{
 SetNormalUserCipherTimeSta(DelCipherFailUserNum, TIME_IN_USING);
}
}




void   AddCipherTest(void * p_context)
{
if(GetCurUartExeCmd() != DOOR_LOCK_CMD_IDLE)
{
SetNormalUserCipherTimeSta(AddCipherFailUserNum, BEFORE_TIME_USING);
}
}




#if   0
void   UartCmdTestHandle(void * p_context)
{
   static  uint8_t  i = 0;



{
if(GetCurUartExeCmd() == DOOR_LOCK_CMD_ADD_USER)
{
if(0x37 == APP_ReceiveData[0])
{
SetTemporUserPassCodeInfor();
UartCmdTestStart(700);
}
}
else if(GetCurUartExeCmd() == LOCK_CMD_ADD_CIPHER)
{

   if(0x37 == APP_ReceiveData[0])
{
SetTemporUserPassCodeInfor();
UartCmdTestStart(700);
}
}
else if(GetCurUartExeCmd() == DOOR_LOCK_CMD_IDLE)
{
if(0x37 == APP_ReceiveData[0])
{
CreatTemporUserSuccess(TEMPOR_USER_CIPHER_HANDLE);
   
}
}
}


}
#endif






void   UartCmdTestHandle(void * p_context)
{
if((APP_ReceiveData[0] == BLE_CMD_TIMEREDIT) && (GetCurUartExeCmd() != DOOR_LOCK_CMD_IDLE))
{
APP_SendData[0] = APP_ReceiveData[0];
   APP_SendData[1] = APP_ReceiveData[1];
     APP_SendData[2] = 0x00;
   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else if((APP_ReceiveData[0] == 0x37) && (GetCurUartExeCmd() != DOOR_LOCK_CMD_IDLE))
{
APP_SendData[0] = APP_ReceiveData[0];
   APP_SendData[1] = 0x00;
   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else if((BLE_CMD_TIMERDELETE  == APP_ReceiveData[0]) && (GetCurUartExeCmd()!= DOOR_LOCK_CMD_IDLE))
{
APP_SendData[0] = APP_ReceiveData[0];
   APP_SendData[1] = APP_ReceiveData[1];
   APP_SendData[2] = 0x00;
   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else if((0x38  ==  APP_ReceiveData[0]) && (GetCurUartExeCmd()!= DOOR_LOCK_CMD_IDLE))
{
APP_SendData[0] = APP_ReceiveData[0];
   APP_SendData[1] = 0x00;
   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
}




void  NorUserCipherInforTx(void * p_context)
{
static  uint8_t  NorUserHandle = 0;
   SystemUserMgr_t  UserLockUseMgr;
   GetSystemUserMgrAdd(&UserLockUseMgr);
//    uint8_t  Cmd;
//    uint8_t  UserSerial;
   
   if(NorUserHandle < NOR_USER_CIPHER_SERIAL)
{
if((UserLockUseMgr.UserCipherMgrFlag) & (0x0001 << NorUserHandle))
{
APP_SendData[0]  = BLE_CMD_TIMERGET;
   APP_SendData[1]  = NorUserHandle;
   memcpy(&APP_SendData[2], UserLockUseMgr.NormalUserMgr[NorUserHandle].DorLockOperaCipher, UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth);
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+2] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidStartTime.Yearh;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+3] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidStartTime.Yearl;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+4] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidStartTime.Month;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+5] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidStartTime.Day;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+6] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidStartTime.Hour;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+7] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidStartTime.Minute;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+8] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidEndTime.Yearh;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+9] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidEndTime.Yearl;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+10] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidEndTime.Month;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+11] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidEndTime.Day;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+12] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidEndTime.Hour;
   APP_SendData[UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherLenth+13] = UserLockUseMgr.NormalUserMgr[NorUserHandle].CipherValidEndTime.Minute;
//  NRF_LOG_INFO("quire----  %x   %x    %x", APP_SendData[2],APP_SendData[3], APP_SendData[4]);
//  NRF_LOG_INFO("quire----  %x   %x    %x", APP_SendData[5],APP_SendData[6], APP_SendData[7]);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
NorUserHandle++;
   
NorUserCipherTxStart(100);
}
else
{
     NorUserHandle = 0;
//    NRF_LOG_INFO("quire----end");
   APP_SendData[0]  = BLE_CMD_TIMERGET;
   APP_SendData[1]  = 0xff;
   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
}








void  GetNormalUserCipherInfor(void)
{
   NorUserCipherTxStart(100);
// NRF_LOG_INFO("quire----start");
}






void  AddNormalUserPassCodeInfor(void)
{
SystemUserMgr_t  UserLockUseMgr;
   GetSystemUserMgrAdd(&UserLockUseMgr);

   RealTime_t   TimeStart;
   RealTime_t   TimeEnd;
   uint8_t   UserPassCode[PASS_CODE_SIZE];
//    NRF_LOG_INFO("app  send  pwd  index---- %x",  APP_ReceiveData[1]);
//    NRF_LOG_INFO("app  send  pwd  data----  %x   %x    %x", APP_ReceiveData[2], APP_ReceiveData[3], APP_ReceiveData[4]);
// NRF_LOG_INFO("app  send  pwd  data----  %x   %x    %x", APP_ReceiveData[5], APP_ReceiveData[6], APP_ReceiveData[7]);
   memcpy(UserPassCode, &APP_ReceiveData[2], PASS_CODE_SIZE);
   TimeStart.Yearh = APP_ReceiveData[8];
   TimeStart.Yearl = APP_ReceiveData[9];
   TimeStart.Month = APP_ReceiveData[10];
   TimeStart.Day   = APP_ReceiveData[11];
   TimeStart.Hour  = APP_ReceiveData[12];
   TimeStart.Minute  = APP_ReceiveData[13];
   
   TimeEnd.Yearh = APP_ReceiveData[14];
   TimeEnd.Yearl = APP_ReceiveData[15];
   TimeEnd.Month = APP_ReceiveData[16];
   TimeEnd.Day   = APP_ReceiveData[17];
   TimeEnd.Hour  = APP_ReceiveData[18];
   TimeEnd.Minute  = APP_ReceiveData[19];

//    if(!MonitorUartBusyExe())
{
AddOneNormalUserCipher(APP_ReceiveData[1], &TimeStart, &TimeEnd, UserPassCode, PASS_CODE_SIZE);
 UartCmdTestStart(1000);
}
// else
{
#if  0
APP_SendData[0] = APP_ReceiveData[0];
APP_SendData[1] = APP_ReceiveData[1];
 APP_SendData[2] = 0x01;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
#endif
}

}








void DelNormalUserPassCodeInfor(void)
{
//    if(!MonitorUartBusyExe())
{
//  NRF_LOG_INFO("del  NormalUserPass----%x", APP_ReceiveData[1]);
if(DelateOneNormalUserCipher(APP_ReceiveData[1], ETMARS_CMD_EXE_TRIGGER) == false)
{
UartCmdTestStart(1000);
}
}
//    else
{
#if  0  
APP_SendData[0] = APP_ReceiveData[0];
APP_SendData[1] = APP_ReceiveData[1];
APP_SendData[2] = 0x01;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
#endif
}
}










void  SetTemporUserPassCodeInfor(void)
{
   RealTime_t  TimeEnd;
   uint8_t  TemporPassCode[PASS_CODE_SIZE];

   memcpy(TemporPassCode, &APP_ReceiveData[1], PASS_CODE_SIZE);
   TimeEnd.Yearh    =  APP_ReceiveData[7];
   TimeEnd.Yearl    =  APP_ReceiveData[8];
   TimeEnd.Month    =  APP_ReceiveData[9];
   TimeEnd.Day      =  APP_ReceiveData[10];
   TimeEnd.Hour     =  APP_ReceiveData[11];
   TimeEnd.Minute   =  APP_ReceiveData[12];

//    if(!MonitorUartBusyExe())
{
CreatTemporUserCipher(&TimeEnd, TemporPassCode, TEMPOR_USER_CIPHER_HANDLE, PASS_CODE_SIZE);
 UartCmdTestStart(2000);
#if   0
 if(UartCmdTestBootFlag == false)
{
   UartCmdTestBootFlag  = true;
UartCmdTestStart(700);
}
#endif
}
//    else
{
#if  0
APP_SendData[0] = APP_ReceiveData[0];
APP_SendData[1] = 0x01;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
 #endif
}
}










void  CancleTemporUserPassCodeInfor(void)
{
//    if(!MonitorUartBusyExe())
{
CancelTemporUserCipher(TEMPOR_USER_CIPHER_HANDLE, ETMARS_CMD_EXE_TRIGGER);
 UartCmdTestStart(1000);
//  UartCmdTestStart(500);
}


// else
{
#if  0
APP_SendData[0] = APP_ReceiveData[0];
APP_SendData[1] = 0x01;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
 #endif
}
}






void  GetTemporUserPassCodeInfor(void)
{
SystemUserMgr_t  UserLockUseMgr;
   GetSystemUserMgrAdd(&UserLockUseMgr);
   
   APP_SendData[0] = APP_ReceiveData[0];
   if((UserLockUseMgr.UserCipherMgrFlag & (0x0001 << TEMPOR_USER_CIPHER_HANDLE)))
{
memcpy(&APP_SendData[1], UserLockUseMgr.TemporUserMgr.DorLockOperaCipher, UserLockUseMgr.TemporUserMgr.CipherLenth);
APP_SendData[UserLockUseMgr.TemporUserMgr.CipherLenth+1] = UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Yearh;
APP_SendData[UserLockUseMgr.TemporUserMgr.CipherLenth+2] = UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Yearl;
APP_SendData[UserLockUseMgr.TemporUserMgr.CipherLenth+3] = UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Month;
APP_SendData[UserLockUseMgr.TemporUserMgr.CipherLenth+4] = UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Day;
APP_SendData[UserLockUseMgr.TemporUserMgr.CipherLenth+5] = UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Hour;
APP_SendData[UserLockUseMgr.TemporUserMgr.CipherLenth+6] = UserLockUseMgr.TemporUserMgr.CipherValidEndTime.Minute;
}
else
{
APP_SendData[1] = 0xff;
}

   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}






#include "bd_wall_clock_timer.h"






void   ModifyLockRealTimeBCD(void)
{
RealTime_t  ModifyTime;
   bool  IsExeModifyTimeCmd;
   time_union_t time;

   ModifyTime.Yearh  = APP_ReceiveData[1];
   ModifyTime.Yearl  = APP_ReceiveData[2];
   ModifyTime.Month  = APP_ReceiveData[3];
   ModifyTime.Day    = APP_ReceiveData[4];
   ModifyTime.Hour   = APP_ReceiveData[5];
   ModifyTime.Minute = APP_ReceiveData[6];
   ModifyTime.Second = APP_ReceiveData[7];

   time.time.year = (APP_ReceiveData[2]>>4)*10+ (APP_ReceiveData[2]&0x0f);
 
   time.time.month = (APP_ReceiveData[3]>>4)*10+ (APP_ReceiveData[3]&0x0f);
   time.time.day = (APP_ReceiveData[4]>>4)*10+ (APP_ReceiveData[4]&0x0f);
   time.time.hours = (APP_ReceiveData[5]>>4)*10+ (APP_ReceiveData[5]&0x0f);
   time.time.minute = (APP_ReceiveData[6]>>4)*10+ (APP_ReceiveData[6]&0x0f);
   time.time.seconds = (APP_ReceiveData[7]>>4)*10+ (APP_ReceiveData[7]&0x0f);


      set_system_clock(time);
   CipherMgrTaskStart(1000);
// UartCmdTestStart(500);

   IsExeModifyTimeCmd  = ModifyLockLocalTime(&ModifyTime);

// if(IsExeModifyTimeCmd == false)
{
APP_SendData[0] = APP_ReceiveData[0];
         APP_SendData[1] = 0x01;
         ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}


/*
   if(IsExeModifyTimeCmd)
{
APP_SendData[0] = APP_ReceiveData[0];
APP_SendData[1] = 0x01;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
//    CipherMgrTaskStart(1000);
}
else
{
 APP_SendData[0] = APP_ReceiveData[0];
         APP_SendData[1] = 0x00;
         ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
*/
}


typedef struct 
{
uint16_t year;
uint8_t  mon;
uint8_t  day;
uint8_t  hour;
uint8_t  min;
uint8_t  sec;
}Rtctime;


void   ModifyLockRealTime(void)
{
RealTime_t  ModifyTime;
   bool  IsExeModifyTimeCmd;
   time_union_t time;
static Rtctime rtctime;

   rtctime.year = APP_ReceiveData[8]<<0x08|APP_ReceiveData[9];
   rtctime.mon = APP_ReceiveData[2];
   rtctime.day = APP_ReceiveData[3]; 
   rtctime.hour = APP_ReceiveData[5];
   rtctime.min = APP_ReceiveData[6];
   rtctime.sec = APP_ReceiveData[7];

   ModifyTime.Yearh  = (rtctime.year/1000)<<4|(rtctime.year%1000/100);
   ModifyTime.Yearl  = ((rtctime.year%100)/10)<<4|rtctime.year%10;
   ModifyTime.Month  = (rtctime.mon/10)<<4|rtctime.mon%10;
   ModifyTime.Day    = (rtctime.day/10)<<4|rtctime.day%10;
   ModifyTime.Hour   = (rtctime.hour/10)<<4|rtctime.hour%10;
   ModifyTime.Minute = (rtctime.min/10)<<4|rtctime.min%10;
   ModifyTime.Second = (rtctime.sec/10)<<4|rtctime.sec%10;

   time.time.year = rtctime.year - 2000;
 
   time.time.month = rtctime.mon;
   time.time.day = rtctime.day;
   time.time.hours = rtctime.hour;
   time.time.minute = rtctime.min;
   time.time.seconds = rtctime.sec;


      set_system_clock(time);
   CipherMgrTaskStart(1000);


   IsExeModifyTimeCmd  = ModifyLockLocalTime(&ModifyTime);

// if(IsExeModifyTimeCmd == false)
{
APP_SendData[0] = APP_ReceiveData[0];
         APP_SendData[1] = 0x01;
         ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}


/*
   if(IsExeModifyTimeCmd)
{
APP_SendData[0] = APP_ReceiveData[0];
APP_SendData[1] = 0x01;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
//    CipherMgrTaskStart(1000);
}
else
{
 APP_SendData[0] = APP_ReceiveData[0];
         APP_SendData[1] = 0x00;
         ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
*/
}








void  DoorLockOpen(void)
{
// DoorLockNormalOpen();
  MasterCipherQuery();
}








void  GetMasterPassCode(void)
{
MasterCipherQuery();
}






void UpdataMasterPassCode(void)
{
ModifyMasterPassCode(APP_ReceiveData[1], &APP_ReceiveData[2]);

   APP_SendData[0] = APP_ReceiveData[0];
   APP_SendData[1] = 1;
   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}






#include <stdint.h>
#include <string.h>
#include "nordic_common.h"
#include "nrf.h"
#include "app_timer.h"
#include "bd_wall_clock_timer.h"
#include "nrf_log.h"


#define APP_TIMER_PRESCALER 0
//wall clock id
APP_TIMER_DEF(wallClockID);


#define ONE_MINUTE_INTERVAL         APP_TIMER_TICKS(1000*60)
#define ONE_SECOND_INTERVAL         APP_TIMER_TICKS(1000)


UTCTimeStruct Global_Time;
static UTCTime SecondCountRTC;      /*This value should be stored in flash*/




uint8_t monthLength( uint8_t lpyr, uint8_t mon )
{
    uint8_t days = 31;


    if ( mon == 1 ) // feb
    {
        days = ( 28 + lpyr );
    } else {
        if ( mon > 6 ) // aug-dec
        {
            mon--;
        }


        if ( mon & 1 ) {
            days = 30;
        }
    }


    return ( days );
}


void ConvertToUTCTime( UTCTimeStruct *tm, UTCTime secTime )
{
    // calculate the time less than a day - hours, minutes, seconds
    {
        uint32_t day = secTime % DAY;
        tm->seconds = day % 60UL;
        tm->minutes = (day % 3600UL) / 60UL;
        tm->hour = day / 3600UL;
    }


    // Fill in the calendar - day, month, year
    {
        uint16_t numDays = secTime / DAY;
        tm->year = BEGYEAR;
        while ( numDays >= YearLength( tm->year ) )
        {
            numDays -= YearLength( tm->year );
            tm->year++;
        }


        tm->month = 0;
        while ( numDays >= monthLength( IsLeapYear( tm->year ), tm->month ))
        {
            numDays -= monthLength( IsLeapYear( tm->year ), tm->month );
            tm->month++;
        }


        tm->day = numDays;
    }
}






/**********************************************
* Time out handle
***********************************************/
static void update_wall_clock(void * p_context)
{
    (void)p_context;
//UTCTimeStruct *tm;


    /* Here we should use RTC attributes */
    SecondCountRTC++;
    
    uint8_t s = SecondCountRTC%60;
    
// SystemUserMgr_t  UserLockUseMgr;
// GetSystemUserMgrAdd(&UserLockUseMgr);
//  tm = get_wall_clock_time();
//  NRF_LOG_INFO("year %d month %d day %d  ",tm->year,tm->month,tm->day);
//  NRF_LOG_INFO("SecondCountRTC  %d",SecondCountRTC);
//   NRF_LOG_INFO("normal user  pwd ----  %d   %d    %d", time->day, time->hour, time->minutes);


    if( s == 0 || s == 30 ){    //update battery 30 secs.
  
    }
    


}




/**************************************************************************
* system clock init
***************************************************************************/
void system_clock_init(void)
{
    uint32_t err_code;


    /* set a default value */
    Global_Time.year = 2000;
    Global_Time.month = 0;
    Global_Time.day = 0;
    Global_Time.hour = 0;
    Global_Time.minutes = 0;
    Global_Time.seconds = 0;


    /* Init ticks from RTC */
    SecondCountRTC = 0;       /* This should read from flash */
    //  00 42 00 40 01
    //  1000010000000000100000000000001
    err_code = app_timer_create(&wallClockID, APP_TIMER_MODE_REPEATED, update_wall_clock);
    APP_ERROR_CHECK(err_code);
    err_code = app_timer_start(wallClockID, ONE_SECOND_INTERVAL, NULL);
    APP_ERROR_CHECK(err_code);
}




UTCTime convert_time_to_Second(time_union_t time)
{
    uint32_t i = 0;
    UTCTime offset = 0;


    //day time
    offset += time.time.seconds;
    offset += time.time.minute * 60;
    offset += time.time.hours * 60 * 60;


    uint8_t leapYear = IsLeapYear(time.time.year + 2000);


    offset += DAY * (time.time.day - 1);


    for(i = 0; i < time.time.month - 1; ++i) { //month start from 1
        offset += monthLength(leapYear,i) * DAY;
    }


    for(i = 0; i< time.time.year ;++i) {
        if(IsLeapYear(i + 2000)) {
            offset += DAY * 366;
        } else {
            offset += DAY * 365;
        }
    }


    return offset;


}


void set_system_clock(time_union_t time)
{
    uint32_t i = 0;
    UTCTime offset = 0;


    //day time
    offset += time.time.seconds;
    offset += time.time.minute * 60;
    offset += time.time.hours * 60 * 60;


    uint8_t leapYear = IsLeapYear(time.time.year + 2000);


    offset += DAY * (time.time.day - 1);


    for(i = 0; i < time.time.month - 1; ++i) { //month start from 1
        offset += monthLength(leapYear,i) * DAY;
    }


    for(i = 0; i< time.time.year ;++i) {
        if(IsLeapYear(i + 2000)) {
            offset += DAY * 366;
        } else {
            offset += DAY * 365;
        }
    }


    SecondCountRTC = offset;


    /************************************************************
    * restart timer
    ************************************************************/
    app_timer_stop(wallClockID);
    app_timer_start(wallClockID, ONE_SECOND_INTERVAL, NULL);


}


UTCTimeStruct * get_wall_clock_time(void)
{
    ConvertToUTCTime(&Global_Time,SecondCountRTC);
    Global_Time.month += 1; //calibration
    Global_Time.day += 1; //calibration
    return &Global_Time;
}




           UTCTime get_wall_clock_time_counter(void)
           {
               return SecondCountRTC;
           }


           /******************************************************
           * update utctime only used in restart set time 
           *******************************************************/
           void set_wall_clock_time_counter(UTCTime counter)
           {
               SecondCountRTC = counter;


               /************************************************************
               * restart timer
               ************************************************************/
               app_timer_stop(wallClockID);
               app_timer_start(wallClockID, ONE_SECOND_INTERVAL, NULL);
           }



#include <stdint.h>
#include "dr_lock_cmd.h"


#include "lock_cmd_def.h"
#include "nrf_log.h"
#include "ble_nus.h"
#include "dorlock_user_mgr.h"
#include "app_timer.h"
#include "dorlock_cmd_rsp.h"


#define   CMD_RESPOND_SIZE    cmdLenMax


#define   EXE_CMD_ADVANCE_USER_HANDLE      TEMPOR_USER_CMD_HANDLE


typedef  struct
{
uint8_t  CurCmdExeType;
   uint8_t  CurCmdExeCode;
   uint8_t  CurCmdExeReason;
   uint8_t  CurCmdExeHandle;
   uint8_t  CurExeCmdRspContent[CMD_RESPOND_SIZE];
   uint8_t  CurExeCmdRspLenth;
   bool     IsCurDorLockCmdExeing;  
}CurCmdExeRspHandle_t;






CurCmdExeRspHandle_t   CurCmdExeRspHandle =
{
.IsCurDorLockCmdExeing  = false,
};


APP_TIMER_DEF(UartCmdRspMgrClk);


void  UartCmdRspMgrHandle(void * p_context);




void    CreatUartCmdRspMgrEvt(void)
{
uint32_t  error;

   error   =  app_timer_create(&UartCmdRspMgrClk, APP_TIMER_MODE_SINGLE_SHOT, UartCmdRspMgrHandle);
   APP_ERROR_CHECK(error);
}








void  UartCmdRspProceStart(uint16_t  TaskDelay)
{
   uint32_t  error;
error = app_timer_start(UartCmdRspMgrClk, APP_TIMER_TICKS(TaskDelay), NULL);
APP_ERROR_CHECK(error);
}








bool  MonitorUartBusyExe(void)
{
return  CurCmdExeRspHandle.IsCurDorLockCmdExeing;
}








void  SetCurDorLockUartCmdExe(uint8_t  CmdExeType, uint8_t  CmdExeCode, uint8_t  CmdExeReason, uint8_t  CmdExeHandle)
{
// CurCmdExeRspHandle.IsCurDorLockCmdExeing  = true;
   CurCmdExeRspHandle.CurCmdExeCode    =  CmdExeCode;
   CurCmdExeRspHandle.CurCmdExeHandle  =  CmdExeHandle;
   CurCmdExeRspHandle.CurCmdExeReason  =  CmdExeReason;
   CurCmdExeRspHandle.CurCmdExeType    =  CmdExeType;
}






void  SetCurDorLockUartCmdRsp(uint8_t *cmdLine, uint8_t RspLenth)
{
memcpy(CurCmdExeRspHandle.CurExeCmdRspContent, cmdLine, RspLenth);
   CurCmdExeRspHandle.CurExeCmdRspLenth  = RspLenth;
}








void  UartCmdRspMgrHandle(void * p_context)
{
   uint8_t  UartRspSta;
   uint16_t  UserId;
   uint16_t  CipherId;
   uint8_t   UserSelect;
uint16_t  CmdReturnVal;
   static  uint8_t   CmdRspMonitorCnt = 0;

   GetUartCmdRspSta(&UartRspSta);

   if(UartRspSta == CMD_RSP_END)  //50msÆô¶¯Ò»´ÎÈÎÎñ£¬Ö±µ½´¦ÀíÍêÃüÁî»Ø¸´
{
switch(CurCmdExeRspHandle.CurCmdExeType)
{
case  DOR_LOCK_USER_MGR_CMD:
       if(CurCmdExeRspHandle.CurCmdExeCode == DOOR_LOCK_CMD_ADD_USER)
{
if(CurCmdExeRspHandle.CurCmdExeReason == ETMARS_CMD_EXE_TRIGGER)
{
if(CurCmdExeRspHandle.CurExeCmdRspContent[4] == ADD_USER_FAIL)
                  {
                  NRF_LOG_DEBUG("creat user fail.");
                      if(CurCmdExeRspHandle.CurCmdExeHandle == EXE_CMD_ADVANCE_USER_HANDLE)
{
APP_SendData[0] = APP_ReceiveData[0];
                                                   APP_SendData[1] = 0x00;
                                                   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else
{
APP_SendData[0] = APP_ReceiveData[0];
                                               APP_SendData[1] = APP_ReceiveData[1];
APP_SendData[2] = 0x00;
                                               ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
 
CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
SetUartCmdRspSta(CMD_RSP_WATT);
CmdRspMonitorCnt  = 0;
                  }
else if(CurCmdExeRspHandle.CurExeCmdRspContent[4] == ADD_USER_SUCCESS)
{
NRF_LOG_DEBUG("creat user ok.");
    UserId  =  (((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[5]) << 8) | ((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[6]);
    if(CurCmdExeRspHandle.CurCmdExeHandle == EXE_CMD_ADVANCE_USER_HANDLE)
{
UserSelect  =  TEMPOR_USER;
     FillInNewUserIdCode(EXE_CMD_ADVANCE_USER_HANDLE, UserId);
     UserMgrFlashUpdata();
     APP_SendData[0] = APP_ReceiveData[0];
                                                     APP_SendData[1] = 0x01;
                                                     ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else
{
UserSelect  =  NORMAL_USER;
     FillInNewUserIdCode(CurCmdExeRspHandle.CurCmdExeHandle, UserId);
     UserMgrFlashUpdata();
     APP_SendData[0] = APP_ReceiveData[0];
                                                 APP_SendData[1] = APP_ReceiveData[1];
 APP_SendData[2] = 0x01;
                                                 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
 
 
if(UserSelect == TEMPOR_USER)
{
CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  true;
       UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
     SetUartCmdRspSta(CMD_RSP_WATT);
     CmdRspMonitorCnt  = 0;
     AddUserPassCodeOperation(TEMPOR_USER, EXE_CMD_ADVANCE_USER_HANDLE);
     CurCmdExeRspHandle.CurCmdExeCode    =  LOCK_CMD_ADD_CIPHER;
                                                     CurCmdExeRspHandle.CurCmdExeHandle  =  EXE_CMD_ADVANCE_USER_HANDLE;
                                                     CurCmdExeRspHandle.CurCmdExeReason  =  ETMARS_CMD_EXE_TRIGGER;
                                                     CurCmdExeRspHandle.CurCmdExeType    =  DOR_LOCK_USER_MGR_CMD;
}
else if(UserSelect == NORMAL_USER)
{
CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
     SetUartCmdRspSta(CMD_RSP_WATT);
     CmdRspMonitorCnt  = 0;
}
}
}

}
else if(CurCmdExeRspHandle.CurCmdExeCode == LOCK_CMD_ADD_CIPHER)
{
if(CurCmdExeRspHandle.CurCmdExeReason == ETMARS_CMD_EXE_TRIGGER)
{
if(CurCmdExeRspHandle.CurExeCmdRspContent[4] ==  0x00)
{
   NRF_LOG_DEBUG("add passcode ok.");
if(CurCmdExeRspHandle.CurCmdExeHandle == EXE_CMD_ADVANCE_USER_HANDLE)
{
APP_SendData[0] = APP_ReceiveData[0];
                                              APP_SendData[1] = 0x01;
                                              ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
  CipherId  =  (((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[7]) << 8) | ((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[8]);
  FillInTemporCipherIdCode(CipherId);
  UserMgrFlashUpdata();
}
else
{
APP_SendData[0] = APP_ReceiveData[0];
                                           APP_SendData[1] = APP_ReceiveData[1];
 APP_SendData[2] = 0x01;
                                           ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}

CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
SetUartCmdRspSta(CMD_RSP_WATT);
CmdRspMonitorCnt  = 0;
}
else if(CurCmdExeRspHandle.CurExeCmdRspContent[4] == 0x02)
{
NRF_LOG_DEBUG("add passcode error user nor in.");
   if(CurCmdExeRspHandle.CurCmdExeHandle == EXE_CMD_ADVANCE_USER_HANDLE)
{
APP_SendData[0] = APP_ReceiveData[0];
                                               APP_SendData[1] = 0x00;
                                               ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else
{
APP_SendData[0] = APP_ReceiveData[0];
                                           APP_SendData[1] = APP_ReceiveData[1];
 APP_SendData[2] = 0x00;
                                           ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}

CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
SetUartCmdRspSta(CMD_RSP_WATT);
CmdRspMonitorCnt  = 0;
}
else if(CurCmdExeRspHandle.CurExeCmdRspContent[4] == 0x04)
{
NRF_LOG_DEBUG("add  passcode  have in.");

   if(CurCmdExeRspHandle.CurCmdExeHandle == EXE_CMD_ADVANCE_USER_HANDLE)
{
#if   0
CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  true;
   SetUartCmdRspSta(CMD_RSP_WATT);
   
   UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
   DelUserPassCodeOperation(TEMPOR_USER, EXE_CMD_ADVANCE_USER_HANDLE);
CurCmdExeRspHandle.CurCmdExeCode    =  DOOR_LOCK_CMD_DEL_CIPHER;
                                               CurCmdExeRspHandle.CurCmdExeHandle  =  EXE_CMD_ADVANCE_USER_HANDLE;
                                               CurCmdExeRspHandle.CurCmdExeReason  =  ETMARS_CMD_EXE_TRIGGER;
                                               CurCmdExeRspHandle.CurCmdExeType    =  DOR_LOCK_USER_MGR_CMD;
#endif
   CmdRspMonitorCnt  = 0;
   CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
   SetUartCmdRspSta(CMD_RSP_WATT);
}
else
{

}
}
else
{
NRF_LOG_DEBUG("add passcode error other reason.");
   CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
   SetUartCmdRspSta(CMD_RSP_WATT);
   CmdRspMonitorCnt  = 0;
}
}
else if(CurCmdExeRspHandle.CurCmdExeReason == INTERNAL_TIME_ARRIVE_CMD_EXE_TRIGGER)
{
if(CurCmdExeRspHandle.CurExeCmdRspContent[4] ==  0x00)
{
NRF_LOG_DEBUG("NORMAL add passcode ok.");
}

CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
SetUartCmdRspSta(CMD_RSP_WATT);
CmdRspMonitorCnt  = 0;
}
}
else if(CurCmdExeRspHandle.CurCmdExeCode == DOOR_LOCK_CMD_DEL_CIPHER)
{
if(CurCmdExeRspHandle.CurCmdExeHandle == EXE_CMD_ADVANCE_USER_HANDLE)
{
if(CurCmdExeRspHandle.CurCmdExeReason == ETMARS_CMD_EXE_TRIGGER)
{
CmdReturnVal  =  (((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[5]) << 8) | ((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[6]);
       
if(CmdReturnVal < 0xFFFD)
{
NRF_LOG_DEBUG("ETMARS  DEL  passcode  success.");
   APP_SendData[0] = APP_ReceiveData[0];
                                                 APP_SendData[1] = 0x01;
                                                 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else
{
NRF_LOG_DEBUG("ETMARS DEL  passcode  fail.");
}
CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
SetUartCmdRspSta(CMD_RSP_WATT);
       CmdRspMonitorCnt  = 0;
}
else if(CurCmdExeRspHandle.CurCmdExeReason == INTERNAL_TIME_ARRIVE_CMD_EXE_TRIGGER)
{
CmdReturnVal  =  (((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[5]) << 8) | ((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[6]);
   if(CmdReturnVal < 0xFFFD)
{
NRF_LOG_DEBUG("INTERNAL_TIME_ARRIVE  DEL  passcode  success.");
//    APP_SendData[0] = APP_ReceiveData[0];
                                     //            APP_SendData[1] = 0x01;
                                     //            ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else
{
NRF_LOG_DEBUG("INTERNAL_TIME_ARRIVE DEL  passcode  fail.");
}
CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
SetUartCmdRspSta(CMD_RSP_WATT);
       CmdRspMonitorCnt  = 0;
}
}
else
{
   CmdReturnVal  =  (((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[5]) << 8) | ((uint16_t)CurCmdExeRspHandle.CurExeCmdRspContent[6]);
 if(CurCmdExeRspHandle.CurCmdExeReason == ETMARS_CMD_EXE_TRIGGER)
 {
if(CmdReturnVal < 0xFFFD)
{
NRF_LOG_DEBUG("%x  ETMARS  DEL  passcode  success.", CurCmdExeRspHandle.CurCmdExeHandle);
   APP_SendData[0] = APP_ReceiveData[0];
                                             APP_SendData[1] = APP_ReceiveData[1];
   APP_SendData[2] = 0x01;
                                                 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else
{
NRF_LOG_DEBUG("%x  ETMARS DEL  passcode  fail.", CurCmdExeRspHandle.CurCmdExeHandle);
}
CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
SetUartCmdRspSta(CMD_RSP_WATT);
       CmdRspMonitorCnt  = 0;
}
else if(CurCmdExeRspHandle.CurCmdExeReason == INTERNAL_TIME_ARRIVE_CMD_EXE_TRIGGER)
{
if(CmdReturnVal < 0xFFFD)
{
NRF_LOG_DEBUG("%x  INTERNAL_TIME_ARRIVE  DEL  passcode  success.", CurCmdExeRspHandle.CurCmdExeHandle);
//    APP_SendData[0] = APP_ReceiveData[0];
                                 //            APP_SendData[1] = APP_ReceiveData[1];
                                     //            ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else
{
NRF_LOG_DEBUG("%x  INTERNAL_TIME_ARRIVE  DEL  passcode  fail.", CurCmdExeRspHandle.CurCmdExeHandle);
}
CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
SetUartCmdRspSta(CMD_RSP_WATT);
       CmdRspMonitorCnt  = 0;
}
}
}
break;

case  DOR_LOCK_TIME_MGR_CMD:
       if(CurCmdExeRspHandle.CurCmdExeCode  == LOCK_CMD_MODIFY_RTC)
{
   if(CurCmdExeRspHandle.CurCmdExeReason == ETMARS_CMD_EXE_TRIGGER)
{
if(CurCmdExeRspHandle.CurExeCmdRspContent[4]  ==  0x00)
{
NRF_LOG_DEBUG("Modify  time  success.");
APP_SendData[0] = APP_ReceiveData[0];
APP_SendData[1] = 0x01;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}

CurCmdExeRspHandle.IsCurDorLockCmdExeing  =  false;
SetUartCmdRspSta(CMD_RSP_WATT);
CmdRspMonitorCnt  = 0;
}
}
       break;
}
}
else if(UartRspSta != CMD_RSP_END)
{
   CmdRspMonitorCnt++;
   if(CmdRspMonitorCnt < 60)
{
UartCmdRspProceStart(RSP_WAIT_SINGLE_TIME);
}
else
{
CmdRspMonitorCnt  = 0;
}
}
}



#include <stdint.h>
#include <string.h>
#include <stdbool.h>


#include "dr_lock_cmd.h"
#include "app_uart.h"
#include "nrf_log.h"
#include "app_scheduler.h"
#include "ble_nus.h"
#include "rtc_cripht_mgr.h"














#define CMD_STATE_IDILE 0
#define CMD_STATE_HEADER 1
#define CMD_STATE_CHECKSUM 2
#define CMD_STATE_LENGTH 3












static uint8_t cmdLine[cmdLenMax];


uint16_t  data_len;


uint8_t state;
uint8_t CmdRspSta;


void uart_recv(void)
{
static uint8_t *pCmdLine;
uint8_t temp;
static uint8_t index;


    app_uart_get(&temp);
//NRF_LOG_INFO("- %x" , temp);
    switch(state)
    {
case CMD_STATE_IDILE: 
          if(temp == 0xF5) {
 NRF_LOG_INFO("CMD start");
pCmdLine = cmdLine;
*pCmdLine = temp;
pCmdLine++;
 state = CMD_STATE_HEADER;
 CmdRspSta  = CMD_RSP_START;
index = 0;
}
break;

case CMD_STATE_HEADER: 
*pCmdLine = temp;
pCmdLine++;
 index++;


 if(index >= 3) {
 state = CMD_STATE_LENGTH;
              data_len = temp;
 index = 0;
}
break;

case CMD_STATE_LENGTH: 
*pCmdLine = temp;
pCmdLine++;
 index++;
          if(index >= data_len ) {

state = CMD_STATE_IDILE;
NRF_LOG_INFO("data_len %d" ,data_len);
            //NRF_LOG_HEXDUMP_DEBUG(cmdLine, data_len+4);
scheduler_proc(recv_proc);
}
break;


default:


state = CMD_STATE_IDILE;
break;


}

}






void recv_proc(void )
{
 if((cmdLine[0] == 0xf5) &&
(cmdLine[1] == 0x00) &&
  (cmdLine[2] == 0x01) &&
  (cmdLine[3] == 0x01) &&
  (cmdLine[4] == 0x00))
{
ble_send_data(cmdLine,data_len+4);
}
//  ProxReporter_SetParameter(&Tx_Rx_Nux, uint8_t * p_string, uint16_t * p_length);
//  LockUartReplyProcess(cmdLine,data_len+4);
 LockUartUserMgrReply(cmdLine,data_len+4);
//  LockUartRtcUserMgrTask(cmdLine, data_len+4);

//   SetCurDorLockUartCmdRsp(cmdLine, data_len+4);
//   CmdRspSta = CMD_RSP_END;
//   UartCmdRspProceStart(20);  //»Ø¸´½áÊøÁ¢¼´½øÈë»Ø¸´´¦Àí
}






void  GetUartCmdRspSta(uint8_t *RspSta)
{
*RspSta  =  CmdRspSta;
}






void  SetUartCmdRspSta(uint8_t  RspSta)
{
CmdRspSta  = RspSta;
}








void scheduler_proc(sched_handler_t pro_func)
{


 app_sched_event_put(NULL, 0, (app_sched_event_handler_t)pro_func);


    NRF_LOG_INFO("scheduler_proc");
}




void  DisplayOneByte(uint8_t  ShowByte)
{
 uint32_t err_code; 
do
    {
                err_code = app_uart_put(ShowByte);
                if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_BUSY))
                {
                    NRF_LOG_ERROR("Failed receiving NUS message. Error 0x%x. ", err_code);
                    APP_ERROR_CHECK(err_code);
                }
    } while (err_code == NRF_ERROR_BUSY);
}






void  UartSendBytesToDorLock(uint8_t *p_data_tx_buf, uint16_t size_bytes)
{
 for (uint32_t i = 0; i < size_bytes; i++)
    {
          DisplayOneByte(p_data_tx_buf[i]);  
    }
}








void  DisplayWholeChrater(uint8_t *p_data_tx_buf, uint8_t EndChar)
{
 uint8_t  LastByte = '\n';
 for(uint32_t i = 0; p_data_tx_buf[i] != EndChar; i++)
 {
DisplayOneByte(p_data_tx_buf[i]); 
}

DisplayOneByte(LastByte);
}










/**
  * @}
  */


#include "timer_modif.h"
#include "ble_nus.h"
#include "BleCommand.h"
#include  "bond.h"
#include "switch_action.h"
#include "timer_correct.h"
#include "sk_flash.h"
#include "adv_evt.h"
#include "sk_evt.h"


//ÔÚ ¿ª ¹Ø ״̬Óõ½µÄ¼ÆÊý
uint8 Status_count =0;








//´¦Àí¿ª×´Ì¬ÏµĶ¨Ê±
void ProcessTimerFunc(void)
{
    ret_code_t err_code;
 
 if(Sockets.IsTimerActive[Status_count] == 0)
{
return;
}
    if(Sockets.Valid[Status_count] & 0x01)//¿ªÓÐЧ
    {
        uint8 hour;
        uint8 min;
        hour = (Sockets.ClockOn[Status_count] >> 8) & 0xff;
        min  = Sockets.ClockOn[Status_count] & 0xff;
        if(hour == rtcTime.Hour && min == rtcTime.Minute)
        {
            SwitchOn();
            Sockets.Status = 1;
            
            if(Tx_Rx_Nux.conn_handle != BLE_CONN_HANDLE_INVALID)
            {
//                APP_SendData[0] = 0x20;
                APP_SendData[0] = BLE_CMD_SWITCH;                
                APP_SendData[1] = 1;
                APP_SendData[2] = 1;
 APP_SendData[3] = SWITCH_ACTION_TRIGGER_TYPE_TIME_RTC_ARRIVE;
//                ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
            }
            UpdateAdvData();
            
            //¶ÔÓÚ²»Öظ´µÄ£¬Ö»Ö´ÐÐÒ»´Î
            if(Sockets.Repeat[Status_count] == 0)
            {
                Sockets.Valid[Status_count] &= ~0x01;
 Sockets.IsTimerActive[Status_count] = 0;
//  IsTimerPermit[Status_count] = 0;

//  err_code = sk_flash_access_timer_permit(IsTimerPermit, ES_FLASH_ACCESS_WRITE);
//            APP_ERROR_CHECK(err_code);
//            WaitFlashWriteEnd();
//                osal_snv_write( ENV_SOCKET_STORE_ADDR, sizeof(Sockets), &Sockets );//zd
 err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);
 
//  while(sk_flash_num_pending_ops())
{
            ;
         }
            }
            return;
        }
    }
    if(Sockets.Valid[Status_count] & 0x02)//¹ØÓÐЧ
    {
        uint8 hour;
        uint8 min;
        hour = (Sockets.ClockOff[Status_count] >> 8) & 0xff;
        min  = Sockets.ClockOff[Status_count] & 0xff;
        if(hour == rtcTime.Hour && min == rtcTime.Minute)
        {
            //¿ªÆôÁ˸½¼Ó¹¦ÄÜ£¬Á¬½Óʱ½ûÖ¹¹Ø±Õ
            if(Tx_Rx_Nux.conn_handle != BLE_CONN_HANDLE_INVALID)
            {
                //¿ªÆôÁ˸½¼Ó¹¦ÄÜ£¬Á¬½Óʱ½ûÖ¹¹Ø±Õ
                if(AdditionalCtrl & ADDCTRL_TIMING_NOCLOSE)
                {
                    //if(Status_Idx==0)
                    //{
                    AdditionalCtrl |= ADDCTRL_NOCLOSE;
                    //}
                    return;
                }
            }
          
            SwitchOff();
            Sockets.Status = 0;
          
            if(Tx_Rx_Nux.conn_handle != BLE_CONN_HANDLE_INVALID)
            {
//                APP_SendData[0] = 0x20;
                APP_SendData[0] = BLE_CMD_SWITCH;              
                APP_SendData[1] = 1;
                APP_SendData[2] = 0;
 APP_SendData[3] = SWITCH_ACTION_TRIGGER_TYPE_TIME_RTC_ARRIVE;
//                ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
            }
            UpdateAdvData();
            
            //¶ÔÓÚ²»Öظ´µÄ£¬Ö»Ö´ÐÐÒ»´Î
            if(Sockets.Repeat[Status_count] == 0)
            {
                Sockets.Valid[Status_count] &= ~0x02;
 
 Sockets.IsTimerActive[Status_count] = 0;
//  IsTimerPermit[Status_count] = 0;
//  err_code = sk_flash_access_timer_permit(IsTimerPermit, ES_FLASH_ACCESS_WRITE);
//            APP_ERROR_CHECK(err_code);
//            WaitFlashWriteEnd();
//                osal_snv_write( ENV_SOCKET_STORE_ADDR, sizeof(Sockets), &Sockets );//zd
 err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);
 
//  while(sk_flash_num_pending_ops())
{
            ;
         }
 
            }
        }
    }
}






void CountDown_Cancel(uint8 SwitchIdx)//È¡Ïûµ¹¼Æʱ
{
  if(SwitchIdx == 0)//È«²¿È¡Ïû
  {
    for(int i=0;i<NUMBER_OF_SMARTSWITCH;i++)
    {
      CountDown[i].CountDownNum = 0;
    }  
  }
  else if((SwitchIdx<=NUMBER_OF_SMARTSWITCH)&&(SwitchIdx>0))//²¿·ÖÈ¡Ïû
  {
    CountDown[SwitchIdx-1].CountDownNum = 0;
  } 

memset(APP_SendData,0,sizeof(APP_SendData));
APP_SendData[0] = BLE_CMD_TIMER_DOWN_CANCEL;
APP_SendData[1] = SwitchIdx;
// ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}






void ClientObtainRemainCountTime(int SwitchIdx)//·¢Ë͵¹¼ÆʱʣÓàʱ¼ä¸ø¿Í»§¶Ë
{
  uint16 CountDownNum_H;
  uint16 CountDownNum_L;
  
  memset(APP_SendData,0,sizeof(APP_SendData));


  if(SwitchIdx==0)
  {
    APP_SendData[0] = BLE_CMD_OBTAIN_COUNT_TIME;
  
    for(int i=0;i<NUMBER_OF_SMARTSWITCH;i++)
    {
       CountDownNum_H = CountDown[i].CountDownNum>>8;
       CountDownNum_L = CountDown[i].CountDownNum&0xff;  
       
       APP_SendData[1] = i+1;                           //¿ª¹ØºÅ
       APP_SendData[2] = CountDown[i].Delay_Switch;     //µ¹¼Æʱ¿ª/¹Ø
       APP_SendData[3] = (uint8)CountDownNum_H;         
       APP_SendData[4] = (uint8)CountDownNum_L;         //µ¹¼Æʱʱ¼ä
//       ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
    APP_SendData[0] = BLE_CMD_OBTAIN_COUNT_TIME;
    APP_SendData[1] = 0xff;
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);//±¨¸æ·¢ËÍÍê±Ï
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
  }
  else if((SwitchIdx<=NUMBER_OF_SMARTSWITCH)&&(SwitchIdx>0))
  {
    CountDownNum_H = CountDown[SwitchIdx-1].CountDownNum>>8;
    CountDownNum_L = CountDown[SwitchIdx-1].CountDownNum&0xff;    
    
    APP_SendData[0] = BLE_CMD_OBTAIN_COUNT_TIME;
    APP_SendData[1] = SwitchIdx;  
    APP_SendData[2] = CountDown[SwitchIdx-1].Delay_Switch;
    APP_SendData[3] = (uint8)CountDownNum_H;
    APP_SendData[4] = (uint8)CountDownNum_L;     
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);

memset(APP_SendData,0,sizeof(APP_SendData));
APP_SendData[0] = BLE_CMD_OBTAIN_COUNT_TIME;
    APP_SendData[1] = 0xff;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
  }
}






void ClientSetCountDown(uint8 SwitchIdx)//ÉèÖõ¹¼Æʱ
{
  uint16 CountDownNum_H;
  uint16 CountDownNum_L;


  CountDownNum_H = APP_ReceiveData[3];
  CountDownNum_L = APP_ReceiveData[4];
 
  
  if(SwitchIdx==0)//ͳһÉèÖÃ
  {
    for(int i=0;i<NUMBER_OF_SMARTSWITCH;i++)
    {
      CountDown[i].Delay_Switch = APP_ReceiveData[2];
      CountDown[i].CountDownNum = (CountDownNum_H<<8)|CountDownNum_L;       
    }
  }
  else if((SwitchIdx<=NUMBER_OF_SMARTSWITCH)&&(SwitchIdx>0))//²¿·ÖÉèÖÃ
  {
    CountDown[SwitchIdx-1].Delay_Switch = APP_ReceiveData[2];
    CountDown[SwitchIdx-1].CountDownNum = (CountDownNum_H<<8)|CountDownNum_L;  
  } 
  
SocketTaskAction(TIMER_DOWN_CNT, 1000);
memset(APP_SendData,0,sizeof(APP_SendData));
  APP_SendData[0] = BLE_CMD_SET_COUNTDOWN;
  APP_SendData[1] = SwitchIdx;
  APP_SendData[2] = APP_ReceiveData[2];
  APP_SendData[3] = CountDownNum_H;
  APP_SendData[4] = CountDownNum_L;
//  ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}


#include "ble_nus.h"
#include "bond.h"
#include "string.h"
#include "sk_flash.h"




















//**************************************************************************************************
void TIMERABLE(void)
{
 ret_code_t err_code;
    if(APP_ReceiveData[1] == 1)
    {
        AdditionalCtrl |= ADDCTRL_OPEN_TIMING;
        AdditionalCtrl &= ~(ADDCTRL_NOCLOSE);
        
        STORE_MAC_DATA[ADDCTRL_STORE_INDEX] = AdditionalCtrl;
//        osal_snv_write( ENV_STORE_MAC_ADDR, sizeof(STORE_MAC_DATA), STORE_MAC_DATA );
 err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
//  while(sk_flash_num_pending_ops())
{
  ;
 }
        
        APP_SendData[0] = 0x06;
        APP_SendData[1] = 1;
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
        ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    } 
    else if(APP_ReceiveData[1] == 0)
    {
        AdditionalCtrl &= ~ADDCTRL_OPEN_TIMING;
        AdditionalCtrl &= ~(ADDCTRL_NOCLOSE);
        
        STORE_MAC_DATA[ADDCTRL_STORE_INDEX] = AdditionalCtrl;
//        osal_snv_write( ENV_STORE_MAC_ADDR, sizeof(STORE_MAC_DATA), STORE_MAC_DATA );
 err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
//  while(sk_flash_num_pending_ops())
{
  ;
 }
        
        APP_SendData[0] = 0x06;
        APP_SendData[1] = 0;
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData); 
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
    else
    {
        memset(APP_SendData,0,sizeof(APP_SendData));
        APP_SendData[0] = 0x06;
        if(AdditionalCtrl & ADDCTRL_OPEN_TIMING)
        {
            APP_SendData[1] = 1;
        }
        else
        {
            APP_SendData[1] = 0;
        }
        
        if(AdditionalCtrl & ADDCTRL_TIMING_NOCLOSE)
        {
            APP_SendData[2] = 1;
        }
        else
        {
            APP_SendData[2] = 0;
        }
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
}






//**************************************************************************************************
void TEMERLOSE(void)
{


    if(APP_ReceiveData[1] == 3)
    {
        memset(APP_SendData,0,sizeof(APP_SendData));
        APP_SendData[0] = 0x06;
        if(AdditionalCtrl & ADDCTRL_OPEN_TIMING)
        {
            APP_SendData[1] = 1;
        }
        else
        {
            APP_SendData[1] = 0;
        }
        
        if(AdditionalCtrl & ADDCTRL_TIMING_NOCLOSE)
        {
            APP_SendData[2] = 1;
        }
        else
        {
            APP_SendData[2] = 0;
        }
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
}



#include "ble_nus.h"
#include "BleCommand.h"
#include "socket_cfg.h"
#include "sk_flash.h"
#include "app_timer.h"
#include "sk_evt.h"
#include <string.h>


//ÖÇÄܲå×ù
Smart_Socket_t  Sockets;
//·¢ËͶ¨Ê±×éµÄ¿ª¹ØÐòºÅ
uint8 SendClocksIndex;
uint8 IsTimerPermit[NUMBER_OF_CLOCKS];




//**************************************************************************************************
void TIMERDELETE(void)
{
 ret_code_t err_code;
    if(APP_ReceiveData[1] == 1)
    {
        if(APP_ReceiveData[2] < NUMBER_OF_CLOCKS)
        {
            Sockets.Valid[APP_ReceiveData[2]] = 0;
 Sockets.IsRtcSetting[APP_ReceiveData[2]] = 0;
//  SokActionType[APP_ReceiveData[2]] = 0;
            
//            osal_snv_write( ENV_SOCKET_STORE_ADDR, sizeof(Sockets), &Sockets );
 err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 WaitFlashWriteEnd();
 
// while(sk_flash_num_pending_ops())
{
;
}
        }
    }    
}




#if  1
void SetTimerActive(void)
{
 ret_code_t err_code;
uint8_t  SwitchIndex = APP_ReceiveData[1];
 uint8_t  TimerIndex  = APP_ReceiveData[2];
 uint8_t  ActiveCfg   = APP_ReceiveData[3];
/*  
 if((SwitchIndex != 0) && (SwitchIndex != 1))
{
return;
}

if(TimerIndex >= NUMBER_OF_CLOCKS)
{
return;
}

if((ActiveCfg != 0) && (ActiveCfg != 1))
{
return;
}

if(Sockets.IsRtcSetting[TimerIndex] == 0)
{
return;
}
*/
Sockets.IsTimerActive[APP_ReceiveData[2]] = ActiveCfg;
// IsTimerPermit[APP_ReceiveData[2]] = ActiveCfg;

err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
// err_code = sk_flash_access_timer_permit(IsTimerPermit, ES_FLASH_ACCESS_WRITE);
// APP_ERROR_CHECK(err_code);





memset(APP_SendData,0,sizeof(APP_SendData));
APP_SendData[0] = BLE_CMD_TIMER_ACTIVE;
APP_SendData[1] = SwitchIndex;
APP_SendData[2] = TimerIndex;
APP_SendData[3] = ActiveCfg;

ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
#endif






//**************************************************************************************************
void TIMEREDIT(void)
{
 ret_code_t err_code;
    if(APP_ReceiveData[2] < NUMBER_OF_CLOCKS)
    {
        Sockets.Valid[APP_ReceiveData[2]] = APP_ReceiveData[8];
//  SokActionType[APP_ReceiveData[2]] = APP_ReceiveData[8];
 Sockets.TimerActionType[APP_ReceiveData[2]] = APP_ReceiveData[8];
        Sockets.ClockOn[APP_ReceiveData[2]] = APP_ReceiveData[3]*256+APP_ReceiveData[4];
        Sockets.ClockOff[APP_ReceiveData[2]] = APP_ReceiveData[5]*256+APP_ReceiveData[6];
        Sockets.Repeat[APP_ReceiveData[2]] = APP_ReceiveData[7];
 Sockets.IsTimerActive[APP_ReceiveData[2]] = 1;
 Sockets.IsRtcSetting[APP_ReceiveData[2]] = 1;
//  IsTimerPermit[APP_ReceiveData[2]] = 1;
//  Sockets.IsRtcSetting[APP_ReceiveData[2]] = APP_ReceiveData[8];
        
//        osal_snv_write( ENV_SOCKET_STORE_ADDR, sizeof(Sockets), &Sockets );
//  err_code = sk_flash_access_timer_permit(IsTimerPermit, ES_FLASH_ACCESS_WRITE);
//    APP_ERROR_CHECK(err_code);
//    WaitFlashWriteEnd();
 
 err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);

 WaitFlashWriteEnd();
 
// while(sk_flash_num_pending_ops())
{
    ;
 }
    }    
}










//**************************************************************************************************
void TIMERGET(void)
{
    SendClocksIndex = APP_ReceiveData[1];
//    Util_restartClock(&SendClocksClock,200);
//    app_timer_start(SendClocksClock,APP_TIMER_TICKS(200), NULL);
    SocketTaskAction(SEND_CLOCKS, 200);
}




#include "ble_nus.h"
#include "BleCommand.h"
#include "socket_cfg.h"
#include "sk_flash.h"
#include "app_timer.h"
#include "sk_evt.h"




//ʱ¼ä
RTC_Time_t rtcTime;






//**************************************************************************************************
void APPTIME(void)
{
 ret_code_t err_code;
    rtcTime.Week = APP_ReceiveData[4];
    rtcTime.Hour = APP_ReceiveData[5];
    rtcTime.Minute = APP_ReceiveData[6];
//    Util_restartClock(&RtcTimerClock,60000);
//  app_timer_start(RtcTimerClock,APP_TIMER_TICKS(60000), NULL);
 SocketTaskAction(RTC_TIMER, 60000);
    
    //дÈëʱÖÓ
//    osal_snv_write( ENV_RTC_TIME_ADDR, sizeof(rtcTime), &rtcTime );  
 err_code = sk_flash_access_rtc_time(&rtcTime, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
// while(sk_flash_num_pending_ops())
{
;
}
    
    APP_SendData[0] = BLE_CMD_APPTIME;
    APP_SendData[1] = 1;
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}


#include "ble_nus.h"
#include "string.h"
#include "BleCommand.h"
#include "timer_modif.h"
#include "switch_action.h"
#include "sk_flash.h"
#include "app_timer.h"
#include "sk_evt.h"
#include "adv_evt.h"


//**************************************************************************************************
void SOCKETOFF(void)
{
    if((APP_ReceiveData[1] == 1)||(APP_ReceiveData[1] == 0))
    {
        SwitchOff();
        Sockets.Status = 0;
        
        memset(APP_SendData,0,sizeof(APP_SendData));        
        APP_SendData[0] = BLE_CMD_SWITCH;
        APP_SendData[1] = APP_ReceiveData[1];
        APP_SendData[2] = Sockets.Status;
 APP_SendData[3] = SWITCH_ACTION_TRIGGER_TYPE_USER_PHONE_TOUCH;
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
    UpdateAdvData();    
}






//**************************************************************************************************
void SOCKETON(void)
{
    if((APP_ReceiveData[1] == 1)||(APP_ReceiveData[1] == 0))
    {
        SwitchOn();
        Sockets.Status = 1;
        
        memset(APP_SendData,0,sizeof(APP_SendData));        
        APP_SendData[0] = BLE_CMD_SWITCH;
        APP_SendData[1] = APP_ReceiveData[1];
        APP_SendData[2] = Sockets.Status;
 APP_SendData[3] = SWITCH_ACTION_TRIGGER_TYPE_USER_PHONE_TOUCH;
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
    UpdateAdvData(); 
}


#if  0
static void AllswithstatusOff(void)
{
   ret_code_t err_code;
      Sockets.Status = 0;
//      osal_snv_write( ENV_SOCKET_STORE_ADDR, sizeof(Sockets), &Sockets );
   err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
// while(sk_flash_num_pending_ops())
{
 ;
}
      SwitchOff();
}






static void Keepswithstatus(void)
{
      if(Sockets.Status == 1)SwitchOn();
      else SwitchOff();


}
#endif


//¿ª¹Ø¿ª
void SwitchOn(void)
{
    BSP_LED_SET(IO_LED_CTRL)
    BSP_RELAY_SET(IO_RELAY_CTRL)
}




//¿ª¹Ø¹Ø
void SwitchOff(void)
{
    BSP_LED_CLR(IO_LED_CTRL)
    BSP_RELAY_CLR(IO_RELAY_CTRL)
}




void  SwitchOnAction(int idx)
{
if(idx == 0)
{
BSP_LED_SET(IO_LED_CTRL)
        BSP_RELAY_SET(IO_RELAY_CTRL)
}
else if(idx == 1)
{
   #if NUMBER_OF_SMARTSWITCH>1
BSP_LED_SET(IO_LED1_CTRL)
          BSP_RELAY_SET(IO_RELAY1_CTRL)
 #endif
}
else if(idx == 2)
{
#if NUMBER_OF_SMARTSWITCH>2
BSP_LED_SET(IO_LED2_CTRL)
          BSP_RELAY_SET(IO_RELAY2_CTRL)
 #endif
}
}




void  SwitchOffAction(int idx)
{
if(idx == 0)
{
BSP_LED_CLR(IO_LED_CTRL)
        BSP_RELAY_CLR(IO_RELAY_CTRL)
}
else if(idx == 1)
{
   #if NUMBER_OF_SMARTSWITCH>1
BSP_LED_CLR(IO_LED1_CTRL)
          BSP_RELAY_CLR(IO_RELAY1_CTRL)
 #endif
}
else if(idx == 2)
{
#if NUMBER_OF_SMARTSWITCH>2
BSP_LED_CLR(IO_LED2_CTRL)
          BSP_RELAY_CLR(IO_RELAY2_CTRL)
 #endif
}
}


void control_led2(void)
{                
    //LED³£ÁÁ»òÕß³¤Ãð
//    Util_stopClock(&LedFlashClock);
//  app_timer_stop(LedFlashClock);
 SocketTaskStop(LED_FLASH);
    
    if(Sockets.Mode & MODE_AUTO)
    {
        SwitchOn();
        Sockets.Status=1;
    }
    if(Sockets.Status == 1)
    {BSP_LED_SET(IO_LED_CTRL)}
    else
    {BSP_LED_CLR(IO_LED_CTRL)}
    
    //Ôڹ㲥Öиüвå×ùµÄ״̬
    UpdateAdvData();
    //·¢Ë͵±Ç°¿ª¹Ø״̬
    sendswithstatus2();
}




void control_led(void)
{                
    //LED³£ÁÁ»òÕß³¤Ãð
//    Util_stopClock(&LedFlashClock);
//  app_timer_stop(LedFlashClock);
 SocketTaskStop(LED_FLASH);
    
    if(Sockets.Mode & MODE_AUTO)
    {
        SwitchOn();
        Sockets.Status=1;
    }
    if(Sockets.Status == 1)
    {BSP_LED_SET(IO_LED_CTRL)}
    else
    {BSP_LED_CLR(IO_LED_CTRL)}
    
    //Ôڹ㲥Öиüвå×ùµÄ״̬
    UpdateAdvData();
    //·¢Ë͵±Ç°¿ª¹Ø״̬
    sendswithstatus();
}




//´«Ê俪¹Ø״̬
static void sendswithstatus2(void)
{
    APP_SendData[2] =1;
    APP_SendData[3]=Sockets.Status;
    APP_SendData[4]=0;
    APP_SendData[5]=0;
    APP_SendData[6]=Sockets.Mode;
    APP_SendData[7]=0;
    APP_SendData[8]=0;
}




//´«Ê俪¹Ø״̬
static void sendswithstatus(void)
{
    APP_SendData[1] =1;
    APP_SendData[2]=Sockets.Status;
    APP_SendData[3]=0;
    APP_SendData[4]=0;
    APP_SendData[5]=Sockets.Mode;
    APP_SendData[6]=0;
    APP_SendData[7]=0;
}



#include "ble_nus.h"
#include "string.h"
#include "BleCommand.h"
#include "bond.h"
#include "sk_flash.h"
#include "fds.h"








uint32 PowerOnCount;






//*********************************************************************
void PD_TYPE_GET(void)
{
    memset(APP_SendData,0,sizeof(APP_SendData));
    APP_SendData[0] = BLE_CMD_PD_TYPE_GET;
    //strcpy(APP_SendData+1,version);
    APP_SendData[1] = 10;
    uint8 i = 0;
    for(i=0;i<15;i++)
    {
        APP_SendData[i+2] = PD_TYPE[i];
    }
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);





//************************************************************************************************** 
void VERSION_GET(void)
{
    memset(APP_SendData,0,sizeof(APP_SendData));
    APP_SendData[0] = BLE_CMD_VERSION_GET;
 APP_SendData[1] = sizeof(FirmwareVersion)-1;
    //strcpy(APP_SendData+1,version);
    uint8 i = 0;
    for(i=0;i<sizeof(FirmwareVersion)-1;i++)
    {
        APP_SendData[i+2] = FirmwareVersion[i];
    }
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}




//**************************************************************************************
//ÀÛ¼ÆÉϵç´ÎÊý
//**************************************************************************************
void Accumulative_PowerOn(void)
{
ret_code_t err_code;
//  osal_snv_read( ENV_STORE_PWRNUM_ADDR, sizeof(uint32), &PowerOnCount );
// err_code  = sk_flash_access_power_on_cnt(&PowerOnCount, ES_FLASH_ACCESS_READ);
// APP_ERROR_CHECK(err_code);

  if(PowerOnCount> 100000)
  {
    PowerOnCount = 0;
  }
  else
  {
    PowerOnCount++;
  }
//  osal_snv_write( ENV_STORE_PWRNUM_ADDR, sizeof(uint32), &PowerOnCount );
err_code  = sk_flash_access_power_on_cnt(&PowerOnCount, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);

// DubegStringPut((uint8 *)&PowerOnCount, sizeof(PowerOnCount));
 
while(sk_flash_num_pending_ops())
{
;
}
}






//**************************************************************************************************
void FACTORY_MODE(void)
{
 ret_code_t err_code;
    memset(APP_SendData,0,sizeof(APP_SendData));
    APP_SendData[0] = BLE_CMD_FACTORY_MODE;
    APP_SendData[1] = APP_ReceiveData[1];
    
    if(APP_ReceiveData[1] == 0x00)
    {
//        APP_SendData[2] = (FirmwareVersion >> 8) & 0xff;
//        APP_SendData[3] = FirmwareVersion & 0xff;
        uint8 i;
        for(i = 0;i<15;i++)
        {
            APP_SendData[i+2] = FirmwareVersion[i];
        } 
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
    else if(APP_ReceiveData[1] == 0x01)
    {
//        if(SpiFlash_Init())
//        {
//            APP_SendData[2] = 0x00;
//        }
//        else
        {
            APP_SendData[2] = 0x01;
        }
    }
    else if(APP_ReceiveData[1] == 0x02)
    {
//        osal_snv_read( ENV_STORE_PWRNUM_ADDR, sizeof(uint32), &PowerOnCount );
 err_code  = sk_flash_access_power_on_cnt(&PowerOnCount, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
        
        APP_SendData[2] = (PowerOnCount >> 24) & 0xff;
        APP_SendData[3] = (PowerOnCount >> 16) & 0xff;
        APP_SendData[4] = (PowerOnCount >> 8) & 0xff;
        APP_SendData[5] = PowerOnCount & 0xff;
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }    
}










void SetDeviceID(void)
{
uint32  err_code;
 Socket_Id_t dev_id;
    uint8  id_size;
  
 err_code = sk_flash_access_dev_id(&dev_id, ES_FLASH_ACCESS_READ);
 if(err_code == FDS_ERR_NOT_FOUND)
{
id_size = APP_ReceiveData[1];
 if((id_size == 0) || (id_size > DEVICE_ID_MAX_SIZE))
{
memset(APP_SendData,0,sizeof(APP_SendData));
 APP_SendData[0] = BLE_CMD_SET_DEVICE_ID;
     APP_SendData[1] = SET_DEV_ID_FAIL;
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
 return;
}

dev_id.IdSize = id_size;
memcpy(dev_id.IdNum, &APP_ReceiveData[2], dev_id.IdSize);
err_code = sk_flash_access_dev_id(&dev_id, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
memset(APP_SendData,0,sizeof(APP_SendData));
APP_SendData[0] = BLE_CMD_SET_DEVICE_ID;
 APP_SendData[1] = SET_DEV_ID_SUCCESS;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
return;
}
else
{
APP_ERROR_CHECK(err_code);

 memset(APP_SendData,0,sizeof(APP_SendData));
 APP_SendData[0] = BLE_CMD_SET_DEVICE_ID;
 APP_SendData[1] = SET_DEV_ID_FAIL;
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
}






void GetDeviceID(void)
{
uint32  err_code;
 Socket_Id_t dev_id;

 err_code = sk_flash_access_dev_id(&dev_id, ES_FLASH_ACCESS_READ);
 if(err_code == FDS_ERR_NOT_FOUND)
{
memset(APP_SendData,0,sizeof(APP_SendData));
 APP_SendData[0] = BLE_CMD_GET_DEVICE_ID;
 APP_SendData[1] = GET_DEV_ID_FAIL;
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
else
{
APP_ERROR_CHECK(err_code);
 memset(APP_SendData,0,sizeof(APP_SendData));
 APP_SendData[0] = BLE_CMD_GET_DEVICE_ID;
 APP_SendData[1] = dev_id.IdSize;
 memcpy(&APP_SendData[2], dev_id.IdNum, dev_id.IdSize);
 APP_SendData[18] = PRODUCT_ID_HIG_BYTE;
 APP_SendData[19] = PRODUCT_ID_LOW_BYTE;
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}
}


#include "sk_flash.h"
#include "fds.h"
#include "nrf_log.h"
#include "socket_cfg.h"
#include "timer_modif.h"
#include "timer_correct.h"
#include "socket_query.h"
#include "bond.h"
#include "name_evt.h"
#include "app_uart.h"


#if  1
#define FILE_ID_SOCKETS_FLASH   0x1340  
#define RECORD_KEY_SOCKETS      20 


#define FILE_ID_MAC_DATA_FLASH  0x1341
#define RECORD_KEY_MAC_DATA     21


#define FILE_ID_RTC_TIME_FLASH  0x1342
#define RECORD_KEY_RTC_TIME     22


#define FILE_ID_POWER_ON_CNT_FLASH  0x1343
#define RECORD_KEY_POWER_ON_CNT     23


#define FILE_ID_DEVICE_NAME_FLASH   0x1344
#define RECORD_KEY_DEVICE_NAME      24


#define FILE_ID_MAC_FLAG_FLASH      0x1345
#define RECORD_KEY_MAC_FLAG         25


#define FILE_ID_PHONE_MAC_FLASH      0x1346
#define RECORD_KEY_PHONE_MAC         26


#define FILE_ID_MAC_FLAG0_FLASH      0x1347
#define RECORD_KEY_MAC_FLAG0         27


#define FILE_ID_PHONE_MAC0_FLASH      0x1348
#define RECORD_KEY_PHONE_MAC0         28


#define FILE_ID_BOND_INFOR_FLASH      0x1349
#define RECORD_KEY_BOND_INFOR         29


#define FILE_ID_DEV_ID_FLASH       0x134A
#define RECORD_KEY_DEV_ID          30
#endif










#define SIZE_OF_SOCKETS         sizeof(Smart_Socket_t)
#define SIZE_OF_MAC_DATA        PHONE_MAC_LENGTH
#define SIZE_OF_RTC_TIME        sizeof(RTC_Time_t)
#define SIZE_OF_POWER_ON_CNT    sizeof(uint32)
#define SIZE_OF_DEVICE_NAME     31
#define SIZE_OF_BOND_INFOR      sizeof(BondInfo_t)
#define SIZE_OF_DEV_ID        sizeof(Socket_Id_t)


#define SIZE_OF_MAC_FLAG        PHONE_MAC_MAXNUM
#define SIZE_OF_PHONE_MAC       PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE
#define SIZE_OF_MAC_FLAG0 PHONE_MAC_MAXNUM
#define SIZE_OF_PHONE_MAC0 PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE










static volatile uint32_t m_num_pending_ops;


__ALIGN(4)  static  uint8 mac_flag_buf[PHONE_MAC_MAXNUM];
__ALIGN(4)  static  uint8 phone_mac_buf[PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE];
__ALIGN(4)  static  uint8 mac_flag0_buf[PHONE_MAC_MAXNUM];
__ALIGN(4)  static  uint8 phone_mac0_buf[PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE];
__ALIGN(4)  static  uint8 socket_buf[sizeof(Smart_Socket_t)];  
__ALIGN(4)  static  uint8 mac_data_buf[SIZE_OF_MAC_DATA];
__ALIGN(4)  static  uint8 rtc_time_buf[sizeof(RTC_Time_t)];
__ALIGN(4)  static  uint8 power_on_cnt_buf[SIZE_OF_POWER_ON_CNT];
__ALIGN(4)  static  uint8 device_name_buf[SIZE_OF_DEVICE_NAME];
//__ALIGN(4)  static  uint8 bond_infor_buf[sizeof(BondInfo_t)];
__ALIGN(4)  static  uint8 timer_permit_buf[NUMBER_OF_CLOCKS];
__ALIGN(4)  static  uint8 device_id_buf[sizeof(Socket_Id_t)];




#define   MAC_FLAG_DEBUG      0
#define   PHONE_MAC_DEBUG     0
#define   MAC_FLAG0_DEBUG     0
#define   PHONE_MAC0_DEBUG    0
#define   SOCKETS_DEBUG       0
#define   MAC_DATA_DEBUG      0
#define   RTC_TIME_DEBUG      0
#define   POWER_CNT_DEBUG     0
#define   DEVICE_NAME_DEBUG   0


#define   BUSY_WAIT_EN        1


#define   FLASH_UART_EN       0




static  uint8   BlankStrPut[10] = {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff};


static void fds_cb(fds_evt_t const * const p_evt)
{
    ret_code_t err_code;


    switch (p_evt->id)
    {
        case FDS_EVT_INIT:
            m_num_pending_ops = 0;
            break;


        case FDS_EVT_DEL_FILE:
        case FDS_EVT_DEL_RECORD:
            if (m_num_pending_ops > 0)
            {
                m_num_pending_ops--;
            }

err_code = fds_gc();
            if (err_code != FDS_SUCCESS)
APP_ERROR_CHECK_BOOL(NRF_ERROR_INTERNAL);
            m_num_pending_ops++;
   
            break;


        case FDS_EVT_GC:

        case FDS_EVT_UPDATE:
        case FDS_EVT_WRITE:
            if (m_num_pending_ops > 0)
            {
//                m_num_pending_ops--;
   m_num_pending_ops = 0;
            }
            break;
    }
}






ret_code_t access_flash_data(const flash_access_params_t * p_params)
{
    ret_code_t         err_code;
    fds_flash_record_t record = {0};
    fds_record_desc_t  desc   = {0};
    fds_find_token_t   ft     = {0};
    fds_record_t       record_to_write =
    {
        .data.p_data = p_params->p_data_buf,
        .file_id     = p_params->file_id
    };


//    err_code = fds_record_find_by_key(p_params->record_key, &desc, &ft);
    err_code = fds_record_find(p_params->file_id, p_params->record_key, &desc, &ft);
   
    if (p_params->access_type == ES_FLASH_ACCESS_READ)
    {
        RETURN_IF_ERROR(err_code);
    }


    if (p_params->access_type == ES_FLASH_ACCESS_CLEAR && err_code == FDS_ERR_NOT_FOUND)
    {
        return NRF_SUCCESS;
    }


    switch (p_params->access_type)
    {
        case ES_FLASH_ACCESS_READ:
            err_code = fds_record_open(&desc, &record);
            RETURN_IF_ERROR(err_code);


            memcpy(p_params->p_data, record.p_data, p_params->size_bytes);


            err_code = fds_record_close(&desc);
            RETURN_IF_ERROR(err_code);


            break;


        case ES_FLASH_ACCESS_WRITE:
            memcpy(p_params->p_data_buf, p_params->p_data, p_params->size_bytes);


            record_to_write.data.length_words = (p_params->size_bytes +3) / 4;
            record_to_write.key               = p_params->record_key;


            if (err_code == FDS_ERR_NOT_FOUND)
            {
                err_code = fds_record_write(&desc, &record_to_write);
            }


            else
            {
                err_code = fds_record_update(&desc, &record_to_write);
            }


//            RETURN_IF_ERROR(err_code);
//            m_num_pending_ops++;
if(err_code == FDS_ERR_NO_SPACE_IN_FLASH)
{
err_code = fds_gc();
                 if (err_code == FDS_ERR_BUSY || err_code == FDS_ERR_NO_SPACE_IN_QUEUES)
                 {
                      // Retry.
                 }
                 else
                 {
//                      APP_ERROR_CHECK(err_code);
   RETURN_IF_ERROR(err_code);
                 }
}
else
{
RETURN_IF_ERROR(err_code);
}
m_num_pending_ops = 1;
            break;


        case ES_FLASH_ACCESS_CLEAR:
            err_code = fds_record_delete(&desc);
            RETURN_IF_ERROR(err_code);
            m_num_pending_ops++;
            break;


        default:
            break;
    }
    return NRF_SUCCESS;
}






uint32_t sk_flash_num_pending_ops(void)
{
    return m_num_pending_ops;
}






ret_code_t sk_flash_access_dev_id(Socket_Id_t *p_dev_id, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_DEV_ID,
                                    .file_id     = FILE_ID_DEV_ID_FLASH,
                                    .p_data_buf  = device_id_buf,
                                    .p_data      = (uint8_t *)p_dev_id,
                                    .size_bytes  = sizeof(Socket_Id_t),
                                    .access_type = access_type};

return access_flash_data(&params);
}




ret_code_t sk_flash_access_mac_flag(uint8 *p_mac_flag, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_MAC_FLAG,
                                    .file_id     = FILE_ID_MAC_FLAG_FLASH,
                                    .p_data_buf  = mac_flag_buf,
                                    .p_data      = (uint8_t *)p_mac_flag,
                                    .size_bytes  = SIZE_OF_MAC_FLAG,
                                    .access_type = access_type};

return access_flash_data(&params);
}




ret_code_t  sk_flash_access_phone_mac(uint8 *p_phone_mac, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_PHONE_MAC,
                                    .file_id     = FILE_ID_PHONE_MAC_FLASH,
                                    .p_data_buf  = phone_mac_buf,
                                    .p_data      = (uint8_t *)p_phone_mac,
                                    .size_bytes  = PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE,
                                    .access_type = access_type};

return access_flash_data(&params);
}




ret_code_t sk_flash_access_mac_flag0(uint8 *p_mac_flag0, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_MAC_FLAG0,
                                    .file_id     = FILE_ID_MAC_FLAG0_FLASH,
                                    .p_data_buf  = mac_flag0_buf,
                                    .p_data      = (uint8_t *)p_mac_flag0,
                                    .size_bytes  = SIZE_OF_MAC_FLAG0,
                                    .access_type = access_type};

return access_flash_data(&params);
}




ret_code_t  sk_flash_access_phone_mac0(uint8 *p_phone_mac0, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_PHONE_MAC0,
                                    .file_id     = FILE_ID_PHONE_MAC0_FLASH,
                                    .p_data_buf  = phone_mac0_buf,
                                    .p_data      = (uint8_t *)p_phone_mac0,
                                    .size_bytes  = PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE,
                                    .access_type = access_type};

return access_flash_data(&params);
}




ret_code_t sk_flash_access_sockets(Smart_Socket_t *p_sk, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_SOCKETS,
                                    .file_id     = FILE_ID_SOCKETS_FLASH,
                                    .p_data_buf  = socket_buf,
                                    .p_data      = (uint8_t *)p_sk,
                                    .size_bytes  = sizeof(Smart_Socket_t),
                                    .access_type = access_type};

return access_flash_data(&params);
}




ret_code_t sk_flash_access_mac_data(uint8 *p_mac_data, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_MAC_DATA,
                                    .file_id     = FILE_ID_MAC_DATA_FLASH,
                                    .p_data_buf  = mac_data_buf,
                                    .p_data      = (uint8_t *)p_mac_data,
                                    .size_bytes  = SIZE_OF_MAC_DATA,
                                    .access_type = access_type};

return access_flash_data(&params);
}






ret_code_t  sk_flash_access_rtc_time(RTC_Time_t *p_rtc_time, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_RTC_TIME,
                                    .file_id     = FILE_ID_RTC_TIME_FLASH,
                                    .p_data_buf  = rtc_time_buf,
                                    .p_data      = (uint8_t *)p_rtc_time,
                                    .size_bytes  = sizeof(RTC_Time_t),
                                    .access_type = access_type};

return access_flash_data(&params);
}




ret_code_t  sk_flash_access_power_on_cnt(uint32 *p_power_on_cnt, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_POWER_ON_CNT,
                                    .file_id     = FILE_ID_POWER_ON_CNT_FLASH,
                                    .p_data_buf  = power_on_cnt_buf,
                                    .p_data      = (uint8_t *)p_power_on_cnt,
                                    .size_bytes  = SIZE_OF_POWER_ON_CNT,
                                    .access_type = access_type};

return access_flash_data(&params);
}






ret_code_t  sk_flash_access_device_name(uint8 *p_device_name, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_DEVICE_NAME,
                                    .file_id     = FILE_ID_DEVICE_NAME_FLASH,
                                    .p_data_buf  = device_name_buf,
                                    .p_data      = (uint8_t *)p_device_name,
                                    .size_bytes  = SIZE_OF_DEVICE_NAME,
                                    .access_type = access_type};

return access_flash_data(&params);
}


#if  0
ret_code_t  sk_flash_access_bond_infor(BondInfo_t *p_bond_infor, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_BOND_INFOR,
                                    .file_id     = FILE_ID_BOND_INFOR_FLASH,
                                    .p_data_buf  = bond_infor_buf,
                                    .p_data      = (uint8_t *)p_bond_infor,
                                    .size_bytes  = sizeof(BondInfo_t),
                                    .access_type = access_type};

return access_flash_data(&params);
}
#endif


ret_code_t  sk_flash_access_timer_permit(uint8 *p_timer_permit, es_flash_access_t access_type)
{
flash_access_params_t params = {.record_key  = RECORD_KEY_BOND_INFOR,
                                    .file_id     = FILE_ID_BOND_INFOR_FLASH,
                                    .p_data_buf  = timer_permit_buf,
                                    .p_data      = (uint8_t *)p_timer_permit,
                                    .size_bytes  = NUMBER_OF_CLOCKS,
                                    .access_type = access_type};

return access_flash_data(&params);
}




void  timer_permit_flash_init(void)
{
ret_code_t    err_code;
 err_code = sk_flash_access_timer_permit(IsTimerPermit, ES_FLASH_ACCESS_READ);

 if(err_code == FDS_ERR_NOT_FOUND)
{
memset(IsTimerPermit, 1, sizeof(IsTimerPermit));
 
 err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);

 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
}
else
{
APP_ERROR_CHECK(err_code);
}
}




void  mac_data_flash_init(void)
{
ret_code_t    err_code;
 err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_READ);

 if(err_code == FDS_ERR_NOT_FOUND)
{
 STORE_MAC_DATA[ADDCTRL_STORE_INDEX] = AdditionalCtrl;
 STORE_MAC_DATA[RTC_WEEK] = rtcTime.Week;
 STORE_MAC_DATA[RTC_HOUR] = rtcTime.Hour;
 STORE_MAC_DATA[RTC_MINUTE] = rtcTime.Minute;
 STORE_MAC_DATA[PHONE_PASSWORD] = '1';
 STORE_MAC_DATA[PHONE_PASSWORD+1] = '2';
 STORE_MAC_DATA[PHONE_PASSWORD+2] = '3';
 STORE_MAC_DATA[PHONE_PASSWORD+3] = '4';
 STORE_MAC_DATA[PHONE_PASSWORD+4] = '5';
 STORE_MAC_DATA[PHONE_PASSWORD+5] = '6';
 STORE_MAC_DATA[PHONE_FLAG] = 0;
 
 err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);

 #if  BUSY_WAIT_EN
 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
#if  0
memset(STORE_MAC_DATA, 0,  sizeof(STORE_MAC_DATA));
err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#endif
memset(BlankStrPut, 0x99, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
DubegStringPut(STORE_MAC_DATA, sizeof(STORE_MAC_DATA));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
}
else
 {
APP_ERROR_CHECK(err_code);
 #if  FLASH_UART_EN
 DubegStringPut(STORE_MAC_DATA, sizeof(STORE_MAC_DATA));
 #endif
 memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
 #if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
 #endif
}

#if  MAC_DATA_DEBUG
STORE_MAC_DATA[ADDCTRL_STORE_INDEX] = 0x52;
STORE_MAC_DATA[RTC_WEEK] = 0x67;
STORE_MAC_DATA[RTC_HOUR] = 0x34;
 STORE_MAC_DATA[RTC_MINUTE] = 0x90;
STORE_MAC_DATA[PHONE_PASSWORD] = '6';
STORE_MAC_DATA[PHONE_PASSWORD+1] = '4';
STORE_MAC_DATA[PHONE_PASSWORD+2] = '3';
STORE_MAC_DATA[PHONE_PASSWORD+3] = '0';
STORE_MAC_DATA[PHONE_PASSWORD+4] = '8';
STORE_MAC_DATA[PHONE_PASSWORD+5] = '7';
STORE_MAC_DATA[PHONE_FLAG] = 0x82;

err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);

#if  BUSY_WAIT_EN
while (sk_flash_num_pending_ops() > 0)
    {
; // Busy wait while initialization of FDS module completes
    }
#endif

memset(STORE_MAC_DATA, 0,  sizeof(STORE_MAC_DATA));
err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  FLASH_UART_EN
DubegStringPut(STORE_MAC_DATA, sizeof(STORE_MAC_DATA));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
#endif
}


void  device_name_flash_init(void)
{
ret_code_t    err_code;
 err_code = sk_flash_access_device_name(deviceName, ES_FLASH_ACCESS_READ);

 if(err_code == FDS_ERR_NOT_FOUND)
{
 err_code = sk_flash_access_device_name(deviceName, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);
 #if  BUSY_WAIT_EN
 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
#if  0
memset(deviceName, 0,  sizeof(deviceName));
err_code = sk_flash_access_device_name(deviceName, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#endif
memset(BlankStrPut, 0x99, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
DubegStringPut(deviceName, sizeof(deviceName));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif


}
else
 {
APP_ERROR_CHECK(err_code);
 #if  FLASH_UART_EN
 DubegStringPut(deviceName, sizeof(deviceName));
 #endif
 memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
 #if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
 #endif
}
#if  DEVICE_NAME_DEBUG
    memcpy(deviceName+2, "ffsggdgdfgdfgf", sizeof("ffsggdgdfgdfgf"));

err_code = sk_flash_access_device_name(deviceName, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);

#if  BUSY_WAIT_EN
while (sk_flash_num_pending_ops() > 0)
    {
; // Busy wait while initialization of FDS module completes
    }
#endif

memset(deviceName, 0,  sizeof(deviceName));
err_code = sk_flash_access_device_name(deviceName, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  FLASH_UART_EN
DubegStringPut(deviceName, sizeof(deviceName));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
    #endif
}




void  phone_mac_flash_init(void)
{
ret_code_t    err_code;
 err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);

 if(err_code == FDS_ERR_NOT_FOUND)
{
memset(phone_mac, FLASH_MACSTATE_CLEAR, sizeof(phone_mac));
 err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);

 #if  BUSY_WAIT_EN
 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
#if 0
memset(phone_mac, 0,  sizeof(phone_mac));
err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#endif
memset(BlankStrPut, 0x99, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
DubegStringPut(phone_mac, sizeof(phone_mac));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
}
else
 {
APP_ERROR_CHECK(err_code);
 #if  FLASH_UART_EN
 DubegStringPut(phone_mac, sizeof(phone_mac));
 #endif
 memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
 #if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
 #endif
}
#if  PHONE_MAC_DEBUG
memset(phone_mac, 0x38, sizeof(phone_mac));
err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
#if  BUSY_WAIT_EN
while (sk_flash_num_pending_ops() > 0)
    {
; // Busy wait while initialization of FDS module completes
    }
#endif
memset(phone_mac, 0,  sizeof(phone_mac));
err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  FLASH_UART_EN
DubegStringPut(phone_mac, sizeof(phone_mac));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
#endif
}




void  phone_mac0_flash_init(void)
{
ret_code_t    err_code;
 err_code = sk_flash_access_phone_mac0(phone_mac0, ES_FLASH_ACCESS_READ);

 if(err_code == FDS_ERR_NOT_FOUND)
{
memset(phone_mac0, FLASH_MACSTATE_CLEAR, sizeof(phone_mac0));
 err_code = sk_flash_access_phone_mac0(phone_mac0, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);
 #if  BUSY_WAIT_EN
 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
#if 0
memset(phone_mac0, 0,  sizeof(phone_mac0));
err_code = sk_flash_access_phone_mac0(phone_mac0, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#endif
memset(BlankStrPut, 0x99, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
DubegStringPut(phone_mac0, sizeof(phone_mac0));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
}
else
 {
APP_ERROR_CHECK(err_code);
 #if  FLASH_UART_EN
 DubegStringPut(phone_mac0, sizeof(phone_mac0));
 #endif
 memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
 #if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
 #endif
}

#if  PHONE_MAC0_DEBUG
memset(phone_mac0, 0x16, sizeof(phone_mac0));
err_code = sk_flash_access_phone_mac0(phone_mac0, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
#if  BUSY_WAIT_EN
while (sk_flash_num_pending_ops() > 0)
    {
; // Busy wait while initialization of FDS module completes
    }
 #endif
memset(phone_mac0, 0,  sizeof(phone_mac0));
err_code = sk_flash_access_phone_mac0(phone_mac0, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  FLASH_UART_EN
DubegStringPut(phone_mac0, sizeof(phone_mac0));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
#endif
}




void  mac_flag_flash_init(void)
{
ret_code_t    err_code;
 err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);

 if(err_code == FDS_ERR_NOT_FOUND)
{
memset(mac_flag, FLASH_MACSTATE_CLEAR, sizeof(mac_flag));
 err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);
 #if  BUSY_WAIT_EN
 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
#if 0
memset(mac_flag, 0,  sizeof(mac_flag));
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#endif
memset(BlankStrPut, 0x99, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
DubegStringPut(mac_flag, sizeof(mac_flag));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
}
else
 {
APP_ERROR_CHECK(err_code);
 #if  FLASH_UART_EN
 DubegStringPut(mac_flag, sizeof(mac_flag));
 #endif
 memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
 #if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
 #endif
}

#if  MAC_FLAG_DEBUG
memset(mac_flag, 0x97, sizeof(mac_flag));
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
#if  BUSY_WAIT_EN
while (sk_flash_num_pending_ops() > 0)
    {
; // Busy wait while initialization of FDS module completes
    }
#endif
memset(mac_flag, 0,  sizeof(mac_flag));
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  FLASH_UART_EN
DubegStringPut(mac_flag, sizeof(mac_flag));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
#endif
}










void  mac_flag0_flash_init(void)
{
ret_code_t    err_code;
 err_code = sk_flash_access_mac_flag0(mac_flag0, ES_FLASH_ACCESS_READ);

 if(err_code == FDS_ERR_NOT_FOUND)
{
memset(mac_flag0, FLASH_MACSTATE_CLEAR, sizeof(mac_flag0));
 err_code = sk_flash_access_mac_flag0(mac_flag0, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);
 #if  BUSY_WAIT_EN
 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
#if 0
memset(mac_flag0, 0,  sizeof(mac_flag0));
err_code = sk_flash_access_mac_flag0(mac_flag0, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#endif
memset(BlankStrPut, 0x99, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
DubegStringPut(mac_flag0, sizeof(mac_flag0));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
}
else
 {
APP_ERROR_CHECK(err_code);
 #if  FLASH_UART_EN
 DubegStringPut(mac_flag0, sizeof(mac_flag0));
 #endif
 memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
 #if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
 #endif
}

#if  MAC_FLAG0_DEBUG
memset(mac_flag0, 0x33, sizeof(mac_flag0));
err_code = sk_flash_access_mac_flag0(mac_flag0, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
#if  BUSY_WAIT_EN
while (sk_flash_num_pending_ops() > 0)
    {
; // Busy wait while initialization of FDS module completes
    }
#endif
memset(mac_flag0, 0,  sizeof(mac_flag0));
err_code = sk_flash_access_mac_flag0(mac_flag0, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  FLASH_UART_EN
DubegStringPut(mac_flag0, sizeof(mac_flag0));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
#endif
}


void  power_on_cnt_flash_init(void)
{
ret_code_t    err_code;
 err_code = sk_flash_access_power_on_cnt(&PowerOnCount, ES_FLASH_ACCESS_READ);

 if(err_code == FDS_ERR_NOT_FOUND)
{
PowerOnCount = 1;
 err_code = sk_flash_access_power_on_cnt(&PowerOnCount, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);
 #if  BUSY_WAIT_EN
 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
#if 0
PowerOnCount = 0;
err_code = sk_flash_access_power_on_cnt(&PowerOnCount, ES_FLASH_ACCESS_READ);
 APP_ERROR_CHECK(err_code);
#endif
memset(BlankStrPut, 0x99, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
DubegStringPut((uint8 *)&PowerOnCount, sizeof(PowerOnCount));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
}
else
 {
APP_ERROR_CHECK(err_code);
#if  0
 if(PowerOnCount> 100000)
        {
            PowerOnCount = 0;
        }
        else
        {
            PowerOnCount++;
        }

err_code  = sk_flash_access_power_on_cnt(&PowerOnCount, ES_FLASH_ACCESS_WRITE);
     APP_ERROR_CHECK(err_code);

while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
 #if  FLASH_UART_EN
 DubegStringPut((uint8 *)&PowerOnCount, sizeof(PowerOnCount));
 #endif
 memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
 #if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
 #endif
}

#if  POWER_CNT_DEBUG
PowerOnCount = 0x5894;
err_code = sk_flash_access_power_on_cnt(&PowerOnCount, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
#if  BUSY_WAIT_EN
while (sk_flash_num_pending_ops() > 0)
    {
; // Busy wait while initialization of FDS module completes
    }
#endif
PowerOnCount = 0;
err_code = sk_flash_access_power_on_cnt(&PowerOnCount, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  FLASH_UART_EN
DubegStringPut((uint8 *)&PowerOnCount, sizeof(PowerOnCount));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
#endif
}




void  rtc_time_flash_init(void)
{
ret_code_t    err_code;
 err_code = sk_flash_access_rtc_time(&rtcTime, ES_FLASH_ACCESS_READ);

 if(err_code == FDS_ERR_NOT_FOUND)
{
rtcTime.Week = 0x01;
 rtcTime.Hour = 0x08;
 rtcTime.Minute = 0x05;

 err_code = sk_flash_access_rtc_time(&rtcTime, ES_FLASH_ACCESS_WRITE);
        APP_ERROR_CHECK(err_code);
 #if  BUSY_WAIT_EN
 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
#if 0
memset(&rtcTime, 0,  sizeof(rtcTime));
err_code = sk_flash_access_rtc_time(&rtcTime, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#endif
memset(BlankStrPut, 0x99, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
DubegStringPut((uint8 *)&rtcTime, sizeof(rtcTime));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
}
else
 {
APP_ERROR_CHECK(err_code);
 #if  FLASH_UART_EN
 DubegStringPut((uint8 *)&rtcTime, sizeof(rtcTime));
 #endif
 memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
 #if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
 #endif
}

#if  RTC_TIME_DEBUG
rtcTime.Week = 0x75;
rtcTime.Hour = 0x24;
rtcTime.Minute = 0x16;
err_code = sk_flash_access_rtc_time(&rtcTime, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
#if  BUSY_WAIT_EN
while (sk_flash_num_pending_ops() > 0)
    {
; // Busy wait while initialization of FDS module completes
    }
#endif
memset(&rtcTime, 0,  sizeof(rtcTime));
err_code = sk_flash_access_rtc_time(&rtcTime, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  FLASH_UART_EN
DubegStringPut((uint8 *)&rtcTime, sizeof(rtcTime));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
#endif
}




void  sockets_flash_init(void)
{
ret_code_t    err_code;
 
 err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_READ);

 if (err_code == FDS_ERR_NOT_FOUND)
    {
 uint8 i;
 Sockets.Status  = 0;
        for(i=0; i< NUMBER_OF_CLOCKS; i++)
   {
// Sockets.Valid[i] = BOTH_TIME_ON_OFF_GAIN;
 Sockets.Valid[i] = 0;
//  SokActionType[i] = 0;
 Sockets.TimerActionType[i] = 0x01;
}
   
for(i=0; i< NUMBER_OF_CLOCKS; i++)
{
Sockets.IsTimerActive[i] = 0;
}

for(i=0; i< NUMBER_OF_CLOCKS; i++)
{
Sockets.IsRtcSetting[i] = 0;
}

for(i=0; i< NUMBER_OF_CLOCKS; i++)
{
Sockets.Repeat[i] = WEEK_END_REPEAT;
}

for(i= 0; i< NUMBER_OF_CLOCKS; i++)
 {
Sockets.ClockOn[i] = RTC_TIME_GROUP_ON_CFG;
}

for(i= 0; i< NUMBER_OF_CLOCKS; i++)
{
Sockets.ClockOff[i] = RTC_TIME_GROUP_OFF_CFG;
}
   
Sockets.Mode  = MODE_MANUAL;
Sockets.PowerActionType  = 0;

err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
        APP_ERROR_CHECK(err_code);
#if  BUSY_WAIT_EN
while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif
#if 0
memset(&Sockets, 0, sizeof(Smart_Socket_t));

err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#endif

memset(BlankStrPut, 0x99, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
DubegStringPut((uint8 *)&Sockets, sizeof(Smart_Socket_t));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
    }


    else
    {
        APP_ERROR_CHECK(err_code);
 Sockets.Status  = 0;
//  memcpy(SokActionType, Sockets.Valid, sizeof(SokActionType));
 #if  FLASH_UART_EN
 DubegStringPut((uint8 *)&Sockets, sizeof(Smart_Socket_t));
 #endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
 #if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
 #endif
    }

#if  SOCKETS_DEBUG
        uint8 i;
   Sockets.Status  = 1;
        for(i=0; i< NUMBER_OF_CLOCKS; i++)
   {
Sockets.Valid[i] = 5;
}
   
for(i=0; i< NUMBER_OF_CLOCKS; i++)
{
Sockets.Repeat[i] = 8;
}

for(i= 0; i< NUMBER_OF_CLOCKS; i++)
 {
Sockets.ClockOn[i] = 0x0923;
}

for(i= 0; i< NUMBER_OF_CLOCKS; i++)
{
Sockets.ClockOff[i] = 0x2158;
}
   
Sockets.Mode  = 6;

err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
        APP_ERROR_CHECK(err_code);
#if  BUSY_WAIT_EN
 while (sk_flash_num_pending_ops() > 0)
        {
; // Busy wait while initialization of FDS module completes
        }
#endif

        memset(&Sockets, 0, sizeof(Smart_Socket_t));
err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  FLASH_UART_EN
        DubegStringPut((uint8 *)&Sockets, sizeof(Smart_Socket_t));
#endif
memset(BlankStrPut, 0xff, sizeof(BlankStrPut));
#if  FLASH_UART_EN
DubegStringPut(BlankStrPut, sizeof(BlankStrPut));
#endif
#endif


}




ret_code_t socket_flash_on_init(void)
{
    ret_code_t err_code;


    m_num_pending_ops = 1; 


    err_code = fds_register(fds_cb);
    RETURN_IF_ERROR(err_code);


    err_code = fds_init();
    RETURN_IF_ERROR(err_code);

 while (sk_flash_num_pending_ops() > 0)
    {
        ; // Busy wait while initialization of FDS module completes
    }


    return NRF_SUCCESS;
}






void  WaitFlashWriteEnd(void)
{
uint16 TimeOutCnt = 0;
while(sk_flash_num_pending_ops())
{
TimeOutCnt++;
if(TimeOutCnt >= 300)
break;
 }
}






void  DubegStringPut(uint8 *p_data_tx_buf, uint16 size_bytes)
{
 uint32_t err_code;


for (uint32_t i = 0; i < size_bytes; i++)
    {
            do
            {
                err_code = app_uart_put(p_data_tx_buf[i]);
                if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_BUSY))
                {
                    NRF_LOG_ERROR("Failed receiving NUS message. Error 0x%x. ", err_code);
                    APP_ERROR_CHECK(err_code);
                }
            } while (err_code == NRF_ERROR_BUSY);
    }
}



#include "sk_evt.h"
#include "switch_action.h"
#include "timer_correct.h"
#include "bond.h"
#include "timer_modif.h"
#include "ble_nus.h"
#include "timer_task.h"
#include "BleCommand.h"
#include "ble_hci.h"
#include "string.h"
#include "name_evt.h"
#include "adv_evt.h"
#include "nrf_power.h"
#include "nrf_nvic.h"
#include "pwd_evt.h"




#define BOOTLOADER_DFU_START            0xB1        /**< Magic value written to retention register when starting buttonless DFU. */


void LedTimeoutHandle(void * p_context);
void LedFlashHandle(void * p_context);
void StartAdvHandle(void * p_context);
void RtcTimerHandle(void * p_context);
void TerminateHandle(void * p_context);
void SendClocksHandle(void * p_context);
void SendDataHandle(void * p_context);
void DelayCloseHandle(void * p_context);
void TimerDownCntHandle(void * p_context);
void FactorySettingHandle(void *p_context);




static void CountDownAction(int idx);




static uint8 WeekMap[8] = {0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40};
uint8  SocketDiscon = 0;
uint8  IsDevConnect = 0;


sk_timer_down_t  CountDown[NUMBER_OF_SMARTSWITCH];


//
void  sk_event_create(void)
{
uint32_t err_code;


err_code = app_timer_create(&ledTimeoutClock, APP_TIMER_MODE_SINGLE_SHOT, LedTimeoutHandle);
 APP_ERROR_CHECK(err_code);
 
 err_code = app_timer_create(&LedFlashClock, APP_TIMER_MODE_SINGLE_SHOT, LedFlashHandle);
 APP_ERROR_CHECK(err_code);

 err_code = app_timer_create(&StartAdvClock, APP_TIMER_MODE_SINGLE_SHOT, StartAdvHandle);
 APP_ERROR_CHECK(err_code);

 err_code = app_timer_create(&TimerDownCntClock, APP_TIMER_MODE_SINGLE_SHOT, TimerDownCntHandle);
 APP_ERROR_CHECK(err_code);

 err_code = app_timer_create(&RtcTimerClock, APP_TIMER_MODE_SINGLE_SHOT, RtcTimerHandle);
 APP_ERROR_CHECK(err_code);

 err_code = app_timer_create(&TerminateClock, APP_TIMER_MODE_SINGLE_SHOT, TerminateHandle);
 APP_ERROR_CHECK(err_code);

 err_code = app_timer_create(&SendClocksClock, APP_TIMER_MODE_SINGLE_SHOT, SendClocksHandle);
 APP_ERROR_CHECK(err_code);

err_code = app_timer_create(&SendDataClock, APP_TIMER_MODE_SINGLE_SHOT, SendDataHandle);
 APP_ERROR_CHECK(err_code);

err_code = app_timer_create(&DelayCloseClock, APP_TIMER_MODE_SINGLE_SHOT, DelayCloseHandle);
 APP_ERROR_CHECK(err_code);

err_code = app_timer_create(&FactorySetClock, APP_TIMER_MODE_SINGLE_SHOT, FactorySettingHandle);
 APP_ERROR_CHECK(err_code);

}






void  FactorySettingHandle(void * p_context)
{
 static  uint8  DelayActionCnt = 0;
if(!nrf_gpio_pin_read(IO_KEY_CTRL))
{
//    if(IsDevConnect == 0)
{
DelayActionCnt++;
if(DelayActionCnt >= 50)
{
DelayActionCnt  = 0;
 if(IsDevConnect == 0)
{
SocketTaskStop(LED_FLASH);
BSP_LED_SET(IO_LED_CTRL)
   SocketTaskAction(LED_FLASH, 4000);
   PASSWORDRECOVER();
 UpdateAdvData();
}
else if(IsDevConnect == 1)
{
PASSWORDRECOVER();
 if(Sockets.Status == 1)
{
BSP_LED_CLR(IO_LED_CTRL)
}
else if(Sockets.Status == 0)
{
BSP_LED_SET(IO_LED_CTRL)
}
 SocketTaskAction(BLE_DISCON, 4000);
}
}
else
{
SocketTaskAction(FACTORY_SET, 200);
}
}
}
else
{
DelayActionCnt = 0;
}
}




void  TimerDownCntHandle(void * p_context)
{
if(
         CountDown[0].CountDownNum
         
     #if NUMBER_OF_SMARTSWITCH>1
       ||CountDown[1].CountDownNum
     #endif
         
     #if NUMBER_OF_SMARTSWITCH>2
       ||CountDown[2].CountDownNum
     #endif
         
      )
    
  {
 SocketTaskAction(TIMER_DOWN_CNT, 1000);
      for(int i=0;i<NUMBER_OF_SMARTSWITCH;i++) //²éѯÄĸö¿ª¹Ø´æÔÚµ¹¼Æʱ
      {
        if(CountDown[i].CountDownNum>0)        //µ±Ç°´æÔÚµ¹¼Æʱ
        {
          CountDown[i].CountDownNum--;         //¼ÆÊý
          
          if(CountDown[i].CountDownNum == 0)   //¼ÆÊýÍê±Ï
          {
            CountDownAction(i);                //ʱ¼äµ½£¬Ö´Ðж¯×÷
          }
        }
      }
  }

#if  defined(SECOND_COUNT_DOWN)
   SocketTaskAction(TIMER_DOWN_CNT, 1000);
#elif defined(MINUTE_COUNT_DOWN)
SocketTaskAction(TIMER_DOWN_CNT, 60000);
#endif
}






void CountDownAction(int idx)//¿ØÖÆ
{
#if  0
  uint8 ENV_SWITCH_STORE_ADDR;


  switch(idx)
    {
    case 0:
      {
        ENV_SWITCH_STORE_ADDR = ENV_SWITCH1_STORE_ADDR;
      }break;
    case 1:
      {
        ENV_SWITCH_STORE_ADDR = ENV_SWITCH2_STORE_ADDR;
      }break;
    case 2:
      {
        ENV_SWITCH_STORE_ADDR = ENV_SWITCH3_STORE_ADDR;
      }break;
    default:break;
    }
#endif
  
  if(CountDown[idx].Delay_Switch == DELAY_ON)//¶¨Ê±¿ª
  {
        SwitchOnAction(idx);
   if(idx == 0)
{
Sockets.Status = 1;
 UpdateAdvData();
 if(Tx_Rx_Nux.conn_handle != BLE_CONN_HANDLE_INVALID)
            {
//                APP_SendData[0] = 0x20;
                APP_SendData[0] = BLE_CMD_SWITCH;                
                APP_SendData[1] = 1;
                APP_SendData[2] = 1;
 APP_SendData[3] = SWITCH_ACTION_TRIGGER_TYPE_TIME_DELAY_END;
//                ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
            }
}
#if  0
        Switches[idx].Status = 1;

        osal_snv_write( ENV_SWITCH_STORE_ADDR, sizeof(Switches[idx]), &Switches[idx] ); 
    #endif
  }
  else if(CountDown[idx].Delay_Switch == DELAY_OFF)//¶¨Ê±¹Ø
  {
        SwitchOffAction(idx);
   if(idx == 0)
{
Sockets.Status = 0;
 UpdateAdvData();
 if(Tx_Rx_Nux.conn_handle != BLE_CONN_HANDLE_INVALID)
            {
//                APP_SendData[0] = 0x20;
                APP_SendData[0] = BLE_CMD_SWITCH;                
                APP_SendData[1] = 1;
                APP_SendData[2] = 0;
 APP_SendData[3] = SWITCH_ACTION_TRIGGER_TYPE_TIME_DELAY_END;
//                ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
            }
}
#if  0 
        Switches[idx].Status = 0;

        osal_snv_write( ENV_SWITCH_STORE_ADDR, sizeof(Switches[idx]), &Switches[idx] ); 
    #endif
  }
}


















void  LedFlashAction(uint16 TaskDelay)
{
uint32_t err_code;
err_code = app_timer_start(LedFlashClock, APP_TIMER_TICKS(TaskDelay), NULL);
 APP_ERROR_CHECK(err_code);
}






void  ledTimeoutAction(uint16 TaskDelay)
{
uint32_t err_code;
err_code = app_timer_start(ledTimeoutClock, APP_TIMER_TICKS(100), NULL);
 APP_ERROR_CHECK(err_code);
}




void  SocketTaskAction(uint8 TaskId, uint16 TaskDelay)
{
uint32_t err_code;
 switch(TaskId)
{
 case  TIMER_DOWN_CNT:
     err_code = app_timer_start(TimerDownCntClock, APP_TIMER_TICKS(TaskDelay), NULL);
APP_ERROR_CHECK(err_code);
     break;

case  LED_TIME_OUT:
err_code = app_timer_start(ledTimeoutClock, APP_TIMER_TICKS(TaskDelay), NULL);
APP_ERROR_CHECK(err_code);
       break;

case  LED_FLASH:
     err_code = app_timer_start(LedFlashClock, APP_TIMER_TICKS(TaskDelay), NULL);
       if(err_code != NRF_SUCCESS)
{
//  printf("\r\nLedFlash FAIL!\r\n");
APP_ERROR_CHECK(err_code);
}
// printf("\r\nLedFlash OK!\r\n");
     break;

case  START_ADV:
     err_code = app_timer_start(StartAdvClock, APP_TIMER_TICKS(TaskDelay), NULL);
             APP_ERROR_CHECK(err_code);
break;

case  RTC_TIMER:
     err_code = app_timer_start(RtcTimerClock, APP_TIMER_TICKS(TaskDelay), NULL);
             APP_ERROR_CHECK(err_code);
     break;

case  BLE_DISCON:
     err_code = app_timer_start(TerminateClock, APP_TIMER_TICKS(TaskDelay), NULL);
             APP_ERROR_CHECK(err_code);
     break;

case  SEND_CLOCKS:
     err_code = app_timer_start(SendClocksClock, APP_TIMER_TICKS(TaskDelay), NULL);
             APP_ERROR_CHECK(err_code);
     break;

case  SEND_DATA:
     err_code = app_timer_start(SendDataClock, APP_TIMER_TICKS(TaskDelay), NULL);
             APP_ERROR_CHECK(err_code);
     break;

case  DELAY_CLOSE:
     err_code = app_timer_start(DelayCloseClock, APP_TIMER_TICKS(TaskDelay), NULL);
             APP_ERROR_CHECK(err_code);
     break;

case  FACTORY_SET:
     err_code = app_timer_start(FactorySetClock, APP_TIMER_TICKS(TaskDelay), NULL);
             APP_ERROR_CHECK(err_code);
     break;
}
}






void  SocketTaskStop(uint8 TaskId)
{
uint32_t err_code;

 switch(TaskId)
{
 case TIMER_DOWN_CNT:
   err_code = app_timer_stop(TimerDownCntClock);
 APP_ERROR_CHECK(err_code);
   break;

case LED_TIME_OUT:
   err_code = app_timer_stop(ledTimeoutClock);
 APP_ERROR_CHECK(err_code);
   break;

case LED_FLASH:
   err_code = app_timer_stop(LedFlashClock);
 APP_ERROR_CHECK(err_code);
   break;

case START_ADV:
   err_code = app_timer_stop(StartAdvClock);
 APP_ERROR_CHECK(err_code);
break;

case RTC_TIMER:
   err_code = app_timer_stop(RtcTimerClock);
 APP_ERROR_CHECK(err_code);
   break;

case BLE_DISCON:
   err_code = app_timer_stop(TerminateClock);
 APP_ERROR_CHECK(err_code);
   break;

case SEND_CLOCKS:
   err_code = app_timer_stop(SendClocksClock);
 APP_ERROR_CHECK(err_code);
   break;

case SEND_DATA:
   err_code = app_timer_stop(SendDataClock);
           APP_ERROR_CHECK(err_code);
   break;

case DELAY_CLOSE:
   err_code = app_timer_stop(DelayCloseClock);
           APP_ERROR_CHECK(err_code);
   break;

case FACTORY_SET:
   err_code = app_timer_stop(FactorySetClock);
           APP_ERROR_CHECK(err_code);
   break;
}
}




void LedTimeoutHandle(void * p_context)
{
BSP_LED_CLR(IO_LED_CTRL)
}






void LedFlashHandle(void * p_context)
{


static uint8 ledStat = 0;
     if(ledStat == 0)
     {
            ledStat++;
            BSP_LED_SET(IO_LED_CTRL)
//            Util_restartClock(&LedFlashClock,100);
//      app_timer_start(LedFlashClock,APP_TIMER_TICKS(100), NULL);
     SocketTaskAction(LED_FLASH, 100);
     }
     else
     {
            ledStat--;
            BSP_LED_CLR(IO_LED_CTRL)
//            Util_restartClock(&LedFlashClock,100);
//            app_timer_start(LedFlashClock,APP_TIMER_TICKS(2000), NULL);
     #if DFU_TEST_ENABLE
SocketTaskAction(LED_FLASH, 100);
     #else
SocketTaskAction(LED_FLASH, 1000);
     #endif
     }


}




void StartAdvHandle(void * p_context)
{
// GAP_UpdateAdvertisingData(selfEntity,TRUE, sizeof(advertData),advertData);
        
// Set the GAP Role Parameters
        //uint8_t advertising_enable = TRUE;
//        GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), 
//                             &advertising_enable);
//  advertising_start();
  uint32 err_code;
//   err_code = sd_ble_gap_adv_stop();   //Ò»¶¨ÒªÔڹ㲥״̬ÏÂÖ´Ðйع㲥£¬·ñÔò±¨´í

// APP_ERROR_CHECK(err_code);
err_code = sd_ble_gap_adv_data_set(advertData, sk_adv_length, deviceName, sizeof(deviceName));
APP_ERROR_CHECK(err_code);
advertising_start();
}






void  RtcTimerHandle(void * p_context)
{
rtcTime.Minute++;
        if(rtcTime.Minute >= 60)
        {
            rtcTime.Hour++;
            rtcTime.Minute = 0;
            if(rtcTime.Hour >= 24)
            {
                rtcTime.Hour = 0;
                rtcTime.Week++;
                if(rtcTime.Week > 7)
                {
                    rtcTime.Week = 1;
                }
            }
        }

//¿ªÆô¶¨Ê±¹¦ÄÜ£¬²Å½øÈë
        if(AdditionalCtrl & ADDCTRL_OPEN_TIMING)
        {
            //for(Status_Idx = 0; Status_Idx < NUMBER_OF_SMARTSWITCH; Status_Idx++)
            //{
                for(Status_count = 0; Status_count < NUMBER_OF_CLOCKS; Status_count++)
                {
                    if(Sockets.Valid[Status_count] == 0)continue;


                    //µ¥´Î¶¨Ê±£¬ÎÞÐèÆ¥ÅäÐÇÆÚ
                    if(Sockets.Repeat[Status_count] == 0)
                    {
                        ProcessTimerFunc();
                    }
                    //Öظ´µÄ£¬±ØÐëÆ¥ÅäÐÇÆÚ
                    else if(WeekMap[rtcTime.Week] & Sockets.Repeat[Status_count])
                    {
                        ProcessTimerFunc();
                    }
                }
            //}
        }
        SocketTaskAction(RTC_TIMER, 60000);
}








void  TerminateHandle(void * p_context)
{
// GAPRole_TerminateConnection();
   uint32  err_code;
   
   if(Tx_Rx_Nux.conn_handle != BLE_CONN_HANDLE_INVALID)
      {
err_code = sd_ble_gap_disconnect(Tx_Rx_Nux.conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
 SocketDiscon = 1;
}
}




void  SendClocksHandle(void * p_context)
{
   static uint8 idx = 0;
        if(idx < NUMBER_OF_CLOCKS)
        {
#if  0
            if(Sockets.Valid[idx] > 0)
#else
if(Sockets.IsRtcSetting[idx])
#endif
            {
//                APP_SendData[0] = 0x21;
                APP_SendData[0] = BLE_CMD_TIMERGET;
                APP_SendData[1] = SendClocksIndex;
                APP_SendData[2] = idx;
                APP_SendData[3] = (Sockets.ClockOn[idx] >> 8) & 0xff;
                APP_SendData[4] = Sockets.ClockOn[idx] & 0xff;
                APP_SendData[5] = (Sockets.ClockOff[idx] >> 8) & 0xff;
                APP_SendData[6] = Sockets.ClockOff[idx] & 0xff;
                APP_SendData[7] = Sockets.Repeat[idx];
//                APP_SendData[8] = Sockets.Valid[idx];
 APP_SendData[8] = Sockets.TimerActionType[idx];
//  APP_SendData[8] = SokActionType[idx];
 APP_SendData[9] = Sockets.IsTimerActive[idx];


//                ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
            }
            idx++;
//            Util_restartClock(&SendClocksClock,100);
// app_timer_start(SendClocksClock, APP_TIMER_TICKS(100), NULL);
SocketTaskAction(SEND_CLOCKS, 100);
        }
        else
        {
            idx = 0;
//            APP_SendData[0] = 0x22;
            APP_SendData[0] = BLE_CMD_TIMERGET;
            APP_SendData[1] = 0xff;
//            ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
        }
}








void  SendDataHandle(void * p_context)
{
if(Send_Flag==BLE_CMD_SNED2MASTER)
      {
            APP_SendData[0]=Send_Flag;
            control_led();
      }
//      ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}






void  DelayCloseHandle(void * p_context)
{
if(AdditionalCtrl & ADDCTRL_TIMING_NOCLOSE)
      {
            if(AdditionalCtrl & ADDCTRL_NOCLOSE)
            {
                AdditionalCtrl &= ~ADDCTRL_NOCLOSE;
                SwitchOff();
                Sockets.Status = 0;            
}
UpdateAdvData();
      }
}








void  UserConnectOnEvt(void)
{
//´æ´¢macµØÖ·µÄÊý¾ÝµÄ×îºóһλÓÃ×÷É豸¸öÊý¼Ç¼
//          if(AppBonding_CheckPhoneMAC()==0)//;//δ°ó¶¨ÈκÎÉ豸£¬//Lewis- 20170427(Ôö¼ÓÊÖ»ú°ó¶¨ÊýÁ¿)
          {
              //LED³£ÁÁ»òÕß³¤Ãð
//              Util_stopClock(&LedFlashClock);
//  app_timer_stop(LedFlashClock);
 SocketTaskStop(LED_FLASH);
              if(Sockets.Status == 1)
              {
//                  bspLedSet(BSP_LED_1);
   BSP_LED_SET(IO_LED_CTRL)
              }
              else
              {
//                  bspLedClear(BSP_LED_1);
   BSP_LED_CLR(IO_LED_CTRL)
              }
              
              
              if(Sockets.Mode & MODE_AUTO)
              {
                  SwitchOn();
                  Sockets.Status = 1;
              }
              UpdateAdvData();
          }
          
//**********************************************************************************************
          //ÏòAPP·¢ËÍ°æ±¾ºÅ     
//          SpiFlash_Delay(1000000);  //  ÐèÒªÏȸüй㲥°ü
          //                memset(APP_SendData,0,sizeof(APP_SendData));
          uint8 i=0;
          
          //·¢ËÍ°æ±¾ºÅ
          memset(APP_SendData,0,sizeof(APP_SendData));
          APP_SendData[0] = BLE_CMD_VERSION_GET;
          //strcpy(APP_SendData+1,version);
          for(i=0;i<15;i++)
          {
              APP_SendData[i+1] = FirmwareVersion[i];
          }
//          ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);//·¢ËÍ°æ±¾º
     ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength); 




//***************************************************************************************************   
          
          Control_Limit =0;
          Control_Permission =0;
          //¼Æʱ¶Ï¿ªÁ¬½Ó-30Ãë


// SocketTaskAction(BLE_DISCON, 60000);

          
          //Çå³ý¸½¼Ó¹¦ÄܱêÖ¾
          if(AdditionalCtrl & ADDCTRL_TIMING_NOCLOSE)
          {
              AdditionalCtrl &= ~(ADDCTRL_NOCLOSE);
          }
}










void  UserDisconnectEvt(void)
{
if(Control_Permission==1)
     {
         if(Sockets.Mode & MODE_AUTO)
         {
             SwitchOff();
             Sockets.Status = 0;
         }
//         UpdateAdvData();
     }
else
{
  if(SocketDiscon == 0)  //±êʶÊÖ»ú·¢Æð¶ÏÁ´
{
SocketTaskStop(BLE_DISCON);
}
}
SocketDiscon = 0;
UpdateAdvData();
     Control_Permission=0;
//     Util_restartClock(&LedFlashClock,100);
// app_timer_start(LedFlashClock, APP_TIMER_TICKS(100), NULL);
SocketTaskAction(LED_FLASH, 100);
}






void RequireOtaStart(void)
{
nrf_power_gpregret_set(BOOTLOADER_DFU_START);
 (void)sd_nvic_SystemReset();
}


#include "ble_nus.h"
#include "string.h"
#include "bond.h"
#include "BleCommand.h"
#include "sk_flash.h"






//**************************************************************************************************
void PASSWORDRECOVER(void)
{
 ret_code_t err_code;
    memset(APP_SendData,0,sizeof(APP_SendData));
    uint8 i=0;
    for(i=0;i<6;i++)
    {
        STORE_MAC_DATA[PHONE_PASSWORD+i]=48+i+1;
    }
    //ĬÈÏÃÜÂëΪ¡®123456¡¯¶ÔÓ¦49 50 51 52 53 54
    STORE_MAC_DATA[PHONE_FLAG] &= (~0x80);
//    osal_snv_write( ENV_STORE_MAC_ADDR, sizeof(STORE_MAC_DATA), STORE_MAC_DATA );
err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
// while(sk_flash_num_pending_ops())
{
  ;
}


    APP_SendData[0] = BLE_CMD_PASSWORDRECOVER;
    APP_SendData[1] = 0x01;
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
    ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);    
}






//**************************************************************************************************
void PASSWORDMODIFY(void)
{
 ret_code_t err_code;
    memset(APP_SendData,0,sizeof(APP_SendData));
    if(APP_ReceiveData[1]==0x06)
    {
        uint8 i=0;
        for(i=0;i<6;i++)
        {
            STORE_MAC_DATA[PHONE_FLAG] &= (~0x80);
            STORE_MAC_DATA[PHONE_FLAG] |= 0x80;
            STORE_MAC_DATA[PHONE_PASSWORD+i]=APP_ReceiveData[2+i];
        }
//        osal_snv_write( ENV_STORE_MAC_ADDR, sizeof(STORE_MAC_DATA), STORE_MAC_DATA );
err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
// while(sk_flash_num_pending_ops())
{
  ;
}


        APP_SendData[0] = BLE_CMD_PASSWORDMODIFY;
        APP_SendData[1] = 0x01;  
    }
    else
    {


        APP_SendData[0] = BLE_CMD_PASSWORDMODIFY;
        APP_SendData[1] = 0x00;  
    }
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}   








uint8   IsPassWordModify(void)
{
if(STORE_MAC_DATA[PHONE_PASSWORD] != '1')
return  1;

if(STORE_MAC_DATA[PHONE_PASSWORD+1] != '2')
return  1;

if(STORE_MAC_DATA[PHONE_PASSWORD+2] != '3')
return  1;

if(STORE_MAC_DATA[PHONE_PASSWORD+3] != '4')
return  1;

if(STORE_MAC_DATA[PHONE_PASSWORD+4] != '5')
return  1;

if(STORE_MAC_DATA[PHONE_PASSWORD+5] != '6')
return  1;

return  0;
}



#include "ble_nus.h"
#include "socket_cfg.h"
#include "BleCommand.h"
#include "string.h"
#include "sk_flash.h"




static uint8 nameIdx = 0;//ÐÞ¸ÄÅä¶ÔÃûµÄµ±Ç°Ë÷Òý


// GAP GATT Attributes
#if defined (AXA_SMART_BOX)
uint8_t deviceName[31] = {15,0x09,'A','x','a','S','m','a','r','t','L','o','c','k',0}; 
uint8 attDeviceName[GAP_DEVICE_NAME_LEN] = "AxaSmartBox";
#elif defined (AXA_SMART_SOCKET)
uint8_t deviceName[31] = {15,0x09,'A','x','a','S','m','a','r','t','S','o','c','k','e','t',0};
uint8 attDeviceName[GAP_DEVICE_NAME_LEN] = "AxaSmartSocket";
#endif


uint8  devName[31] = {15,0x09,'A','x','a','S','m','a','r','t','S','o','c','k','e','t',0};

//e4babae5b7a5e699bae685a7e68f92e5baa7---ÖÇÄܲå×ù±àÂë

//**************************************************************************************************
void NAMECHANGEA(void)
{
//    static uint8 nameIdx = 0;//ÐÞ¸ÄÅä¶ÔÃûµÄµ±Ç°Ë÷Òý 
    if(APP_ReceiveData[1] <= sizeof(deviceName)-2)
    {
        memset(deviceName, 0, sizeof(deviceName));
        for(nameIdx = 0; nameIdx < APP_ReceiveData[1]; nameIdx++)
        {
            deviceName[2+nameIdx] = APP_ReceiveData[2+nameIdx];
        }
        APP_SendData[0] = BLE_CMD_NAMECHANGEA;
        APP_SendData[1] = 1;
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    } 
    else
    {
        APP_SendData[0] = BLE_CMD_NAMECHANGEA;
        APP_SendData[1] = 0;
 //       ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);  
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
}




//**************************************************************************************************
void NAMECHANGEB(void)
{
 ret_code_t err_code;
//    static uint8 nameIdx = 0;//ÐÞ¸ÄÅä¶ÔÃûµÄµ±Ç°Ë÷Òýzd //10.30
    if(nameIdx+APP_ReceiveData[1] <= sizeof(deviceName)-2)
    {
        if(nameIdx == 0)
        {
            memset(deviceName, 0, sizeof(deviceName));
        }
        uint8 nameIdx2;
        for(nameIdx2 = 0; nameIdx2 < APP_ReceiveData[1]; nameIdx2++)
        {
            deviceName[2+nameIdx+nameIdx2] = APP_ReceiveData[2+nameIdx2];
        }
        
        deviceName[0] = nameIdx + nameIdx2+1;//Ãû³Æ³¤¶È
        deviceName[1] = 0x09;
        
        //дÈëÅä¶ÔÃû
//        osal_snv_write( ENV_NAME_STORE_ADDR, sizeof(deviceName), deviceName );
err_code = sk_flash_access_device_name(deviceName, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
// while(sk_flash_num_pending_ops())
{
     ;
 }
        
        //¸üлØÓ¦°ü
//        GAP_UpdateAdvertisingData(selfEntity,FALSE, sizeof(deviceName),deviceName);

        
        //¸üÐÂÊôÐÔÃû
        for(uint8 i = 0; i < GAP_DEVICE_NAME_LEN; i++)
        {
            attDeviceName[i] = deviceName[i+2];
        }
//        GGS_SetParameter(GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName);

        
        //ÇåÁã
        nameIdx = 0;nameIdx2 = 0;
        APP_SendData[0] = BLE_CMD_NAMECHANGEB;
        APP_SendData[1] = 1;
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    } 
    else
    {
        APP_SendData[0] = BLE_CMD_NAMECHANGEB;
        APP_SendData[1] = 0;
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData); 
        ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    } 
}


#include "ble_nus.h"
#include "BleCommand.h"
#include "switch_action.h"
#include "bond.h"
#include "timer_modif.h"
#include "timer_set.h"
#include "auto_set.h"
#include "timer_correct.h"
#include "name_evt.h"
#include "pwd_evt.h"
#include "string.h"
#include "socket_query.h"
#include "app_timer.h"
#include "sk_evt.h"
#include "timer_task.h"
#include "nrf_log.h"
#include "user_cipher_mgr.h"




void SocketCommandDispatch(void)
{
//    ProxReporter_GetParameter(PROXIMITY_RECEIVE_DATA,APP_ReceiveData);
    
    //¿ØÖÆÉ豸
    if(Control_Permission==1)//zd
    {
        switch(APP_ReceiveData[0])
        {
//**************************************************************************************
        case BLE_CMD_CONNECTBREAK://¶Ï¿ªÁ¬½Ó
//            Util_restartClock(&TerminateClock,500);
//    app_timer_start(TerminateClock,APP_TIMER_TICKS(500), NULL);
   SocketTaskAction(BLE_DISCON, 500);
            break;


//**************************************************************************************
        case BLE_CMD_SWITCH://¿ª¹Ø
/*
            if(APP_ReceiveData[2] == 1)
            {
                SOCKETON();
            }
            else
            {
                SOCKETOFF();
            }
*/
   DoorLockOpen();
            break; 
            
//**************************************************************************************        
//        case BLE_CMD_TIMER_ON_OFF://¶¨Ê±×鿪/¹ØÇл»
//            TIMER_ON_OFF();
//            break;


        case BLE_CMD_SWITCH_STATUS:
            memset(APP_SendData,0,sizeof(APP_SendData));
            APP_SendData[0] = BLE_CMD_SWITCH_STATUS;
            APP_SendData[1] = 1;
            APP_SendData[2] = Sockets.Status;//switch0
          
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData); 
  ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
            break;
            
        case BLE_CMD_AUTO_STATUS:
            memset(APP_SendData,0,sizeof(APP_SendData));
            APP_SendData[0] = BLE_CMD_AUTO_STATUS;
            APP_SendData[1] = 1;
            if(Sockets.Mode & MODE_AUTO)//switch0
                APP_SendData[2] = 1;
            else
                APP_SendData[2] = 0;
            
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData); 
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
            break;             
//**************************************************************************************
        case BLE_CMD_TIMEREDIT://Ôö¼Ó/±à¼­¶¨Ê±×é
//            TIMEREDIT();
   AddNormalUserPassCodeInfor();
            break;


//**************************************************************************************
        case BLE_CMD_TIMERDELETE://È¡Ïû¶¨Ê±×é
//            TIMERDELETE();
   DelNormalUserPassCodeInfor();
            break;
            
//**************************************************************************************
        case BLE_CMD_AUTO_EN_DIS://ʹÄÜ»òÕ߹رÕ×Ô¶¯¿ª¹Ø
            AUTO_EN_DIS();
            break;
            
//**************************************************************************************
         case BLE_CMD_APPTIME://У׼
//            APPTIME();
   NRF_LOG_INFO("lock  exe  ModifyLockRealTime");
   ModifyLockRealTime();
            break;
 
case  0x3c:
 ModifyLockRealTimeBCD();
            break;
            
//**************************************************************************************            
        case BLE_CMD_TIMERGET://»ñÈ¡¶¨Ê±×é
//            TIMERGET();
   GetNormalUserCipherInfor();
            break;

case 0x37:
SetTemporUserPassCodeInfor();
   break;

case 0x38:
CancleTemporUserPassCodeInfor();
   break;

case 0x39:
            GetTemporUserPassCodeInfor();
   break;

case 0x3a:
 GetMasterPassCode();
 break;

case 0x3b:
 UpdataMasterPassCode();
 break;
//**************************************************************************************
        case BLE_CMD_NAMECHANGEA://ÐÞ¸ÄÀ¶ÑÀÅä¶ÔÃûa
            NAMECHANGEA();
            break;
            
//**************************************************************************************  
        case BLE_CMD_NAMECHANGEB://ÐÞ¸ÄÀ¶ÑÀÅä¶ÔÃûb
            NAMECHANGEB();
            break;
            
//**************************************************************************************
        case BLE_CMD_SET_COUNTDOWN://µ¹¼Æʱ¶¯×÷
 ClientSetCountDown(APP_ReceiveData[1]);
            break;

case BLE_CMD_TIMER_DOWN_CANCEL:
 CountDown_Cancel(APP_ReceiveData[1]);
 break;

case BLE_CMD_OBTAIN_COUNT_TIME:
            ClientObtainRemainCountTime(APP_ReceiveData[1]);
   break;
//**************************************************************************************
        case BLE_CMD_TIMERABLE: //¶¨Ê±¹¦ÄÜ¿ªÆô/¹Ø±Õ
            TIMERABLE();
            break;
            
//**************************************************************************************
        case BLE_CMD_TEMERLOSE://Á¬½Óʱ½ûÖ¹¶¨Ê±¹ØµÆ
            TEMERLOSE();
            break;

case BLE_CMD_TIMER_ACTIVE: //¶¨Ê±×鼤»î
 SetTimerActive();
 break;
            
//************************************************************************************** 
//        case BLE_CMD_SWITCH_STATUS://¶Áȡ״̬
//            SOCKET_STATUS();
//            break;
//**************************************************************************************           
        case BLE_CMD_PASSWORDMODIFY: //ÐÞ¸ÄÃÜÂë
            PASSWORDMODIFY();
            break;   
            
//**************************************************************************************
        case BLE_CMD_PASSWORDRECOVER: //»Ö¸´Ä¬ÈÏÃÜÂë
            PASSWORDRECOVER();
            break;   
            
//************************************************************************************** 
        case BLE_CMD_BONDINGLOSE://ʧЧµ±Ç°°ó¶¨µÄÕʺÅ
            BONDINGLOSE();
            break;
            
//**************************************************************************************            
        case BLE_CMD_ALLBONDINGLOSE: //ʧЧËùÓаó¶¨Õ˺źÍÃÜÂë
            ALLBONDINGLOSE();
            break;
            
 //**************************************************************************************            
        case BLE_CMD_FACTORYSETTING://»Ö¸´³ö³§ÉèÖÃ
            break;
            
//**************************************************************************************
        case BLE_CMD_PD_TYPE_GET://»ñÈ¡É豸ÀàÐÍ
            PD_TYPE_GET();
            break;
                     
//**************************************************************************************  
        case BLE_CMD_VERSION_GET://»ñÈ¡°æ±¾ºÅ
            VERSION_GET();
            break; 

case BLE_CMD_GET_DEVICE_ID: //»ñÈ¡ID
 GetDeviceID();
 break;
            
      
//**************************************************************************************            
/**************************************************************************************           
                         ¿ÕÖÐÉý¼¶OTA    
**************************************************************************************/
        case BLE_CMD_OTASTART://ÇëÇó¿ÕÖÐÉý¼¶
//            OTASTART();
   RequireOtaStart();
            break;
            
//**************************************************************************************       
        case BLE_CMD_OTATRANSFER://·¢ËÍÊý¾Ý°ü
//            OTATRANSFER();
            break;
            
//**************************************************************************************
        case BLE_CMD_OTAFINISH://Êý¾Ý°ü·¢ËÍÍê³É
//            OTAFINISH();
            break;
            
//**************************************************************************************
case BLE_CMD_POWER_ACTION_TYPE:
 SetDevicePowerActionType();
 break;

case BLE_CMD_READ_POWER_ON_ACTION:
 ReadDevicePowerActionType();
 break;
        
default:break;
        }
    }
        //»Ø¸´
        switch(APP_ReceiveData[0])
        {


        case BLE_CMD_TIMEREDIT:
        case BLE_CMD_TIMERDELETE:
            
         memset(APP_SendData,0,sizeof(APP_SendData));
         APP_SendData[0] = APP_ReceiveData[0];
         APP_SendData[1] = APP_ReceiveData[1];
         APP_SendData[2] = APP_ReceiveData[2];
            
//            ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
// ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
            break;
        default:break;
        } 
    
        switch(APP_ReceiveData[0])
        {


//        case BLE_CMD_APPTIME:
            //case 0x19:
//        case BLE_CMD_COUNTDOWN:
        case BLE_CMD_TIMERABLE:


//            ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_ReceiveData),APP_ReceiveData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
            break;
        default:break;
        }
    
    //°ó¶¨É豸
    if(Control_Permission==0)
    {
        switch(APP_ReceiveData[0])
        {
//**************************************************************************************
        case BLE_CMD_SUPPER_LIMIT://³¬¼¶È¨ÏÞ
            SUPPER_LIMIT();
            break;
            
//**************************************************************************************
        case BLE_CMD_FACTORY_MODE://¹¤³§Ä£Ê½
            FACTORY_MODE();
            break; 
            
//**************************************************************************************
        case BLE_CMD_BONDINGVERIFY://°ó¶¨É豸
            BONDINGVERIFY();
            break;


        case  BLE_CMD_SET_DEVICE_ID:
 SetDeviceID();
            break;
        default:
            break;
        }
    }
//**************************************************************************************            
//**************************************************************************************
//¼ì²éÊÇ·ñ°ó¶¨µÄÉ豸
    if(Control_Limit ==0)
    {
        switch(APP_ReceiveData[0])
        { 
        case BLE_CMD_MACVERIFY: //»ñÈ¡´Ó»úmacµØÖ·,ÑéÖ¤°ó¶¨µÄÉ豸   
            MACADDR_GET();
            break;
        default:
            break; 
        }
    }
//**************************************************************************************
}


#include  "ble_nus.h"
#include  "bond.h"
#include  "socket_cfg.h"
#include  "string.h"
#include  "BleCommand.h"
#include  "sk_flash.h"
#include  "switch_action.h"
#include  "sk_evt.h"
#include  "fds.h"
#include  "adv_evt.h"


uint8 STORE_MAC_DATA[PHONE_MAC_LENGTH] = {0};
//static uint8 MAC_ADDR[6]={0};
uint8 PD_TYPE[15] = "PC085_A_V1.0.0";


uint8 Control_Permission = 0;
uint8 Control_Limit =0;
uint8 Send_Flag =0;


uint8 AdditionalCtrl = ADDCTRL_OPEN_TIMING;


uint8 mac_flag[PHONE_MAC_MAXNUM];
uint8 phone_mac[PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE];




uint8 mac_flag0[PHONE_MAC_MAXNUM];
uint8 phone_mac0[PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE];




/*******************************************************************************
* Function    : AppBonding_Init
* Description : ³õʼ»¯°ó¶¨Êý¾Ý
* Arguments   :
* Return      :
*******************************************************************************/
#if  0
void AppBonding_Init(void)
{
    BondInfo_t sBondInfo;
    ret_code_t err_code;
//    SpiFlash_ReadData((uint8*)&sBondInfo, BOND_PHONEDATA_START_ADDR, sizeof(sBondInfo));
 err_code = sk_flash_access_bond_infor(&sBondInfo, ES_FLASH_ACCESS_READ);
 
 if(err_code != FDS_ERR_NOT_FOUND)
{
APP_ERROR_CHECK(err_code);
}
 
    if((err_code == FDS_ERR_NOT_FOUND) || (err_code == NRF_SUCCESS))
{
if(sBondInfo.bond[0] == 'B' &&
sBondInfo.bond[1] == 'o' &&
sBondInfo.bond[2] == 'n' &&
sBondInfo.bond[3] == 'd')

}
else
{
//       SpiFlash_EraseSector(BOND_PHONEDATA_START_ADDR);
 
sBondInfo.bond[0] = 'B';
sBondInfo.bond[1] = 'o';
sBondInfo.bond[2] = 'n';
sBondInfo.bond[3] = 'd';
// SpiFlash_WriteData((uint8*)&sBondInfo, BOND_PHONEDATA_START_ADDR, sizeof(sBondInfo));
err_code = sk_flash_access_bond_infor(&sBondInfo, ES_FLASH_ACCESS_WRITE);
        APP_ERROR_CHECK(err_code);
while(sk_flash_num_pending_ops())
{
       ;
    }
 
}

// DubegStringPut(sBondInfo.bond, sizeof(sBondInfo.bond));
}
}
#endif


//**************************************************************************************************
void BONDINGLOSE(void)
{
    //*******************************************************************************
    //Lewis- 20170427(Ôö¼ÓÊÖ»ú°ó¶¨ÊýÁ¿) 
    memset(APP_SendData,0,sizeof(APP_SendData));
    
    uint8 i=0;
    uint8 uiPhoneMAC[6];
    
    for(i=0;i<6;i++)
    {
        uiPhoneMAC[i]=APP_ReceiveData[1+i];
    }
    
    if(AppBonding_LostPhoneMAC(uiPhoneMAC) == 1)
    {
        APP_SendData[0] = BLE_CMD_BONDINGLOSE;
        APP_SendData[1] = 0x01;    
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
        
        Control_Permission=0;     //ʧȥ¿ØÖÆȨÏÞ
//        Util_restartClock(&TerminateClock,200);   //ʧЧ³É¹¦£¬¶Ï¿ªÉ豸
//  app_timer_start(TerminateClock,APP_TIMER_TICKS(200), NULL);
 SocketTaskAction(BLE_DISCON, 200);
    }
    else
    {
APP_SendData[0] = BLE_CMD_BONDINGLOSE;
        APP_SendData[1] = 0x00;  
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
}


//**************************************************************************************************
void ALLBONDINGLOSE(void)
{
    uint8 i=0;
 ret_code_t err_code;
    
//    AppBonding_LostPhoneAll();
    //*******************************************************************************
    memset(APP_SendData,0,sizeof(APP_SendData));
    memset(STORE_MAC_DATA,0,sizeof(STORE_MAC_DATA));
    for(i=0;i<6;i++)
    {
        STORE_MAC_DATA[PHONE_PASSWORD+i]=48+i+1;//³õʼÃÜÂë'123456'
    }
    AdditionalCtrl = ADDCTRL_OPEN_TIMING;
    STORE_MAC_DATA[ADDCTRL_STORE_INDEX] = AdditionalCtrl;                  
//    osal_snv_write( ENV_STORE_MAC_ADDR, sizeof(STORE_MAC_DATA), STORE_MAC_DATA );
err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
// while(sk_flash_num_pending_ops())
{
;
}
    
//    APP_SendData[0] = 0x4D;
//    APP_SendData[1] = 0x01;
    APP_SendData[0] = BLE_CMD_ALLBONDINGLOSE;
    APP_SendData[1] = 0x01;
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    
    //ʧȥ¿ØÖÆȨÏÞ
    Control_Permission=0;
    
    //ʧЧ³É¹¦£¬¶Ï¿ªÉ豸
//    Util_restartClock(&TerminateClock,200);
// app_timer_start(TerminateClock,APP_TIMER_TICKS(200), NULL);
SocketTaskAction(BLE_DISCON, 200);
}


//*********************************************************************




void BONDINGVERIFY(void) //000000
{
//*******************************************************************************
//Lewis- 20170427(Ôö¼ÓÊÖ»ú°ó¶¨ÊýÁ¿)    
    memset(APP_SendData,0,sizeof(APP_SendData));
    
    StrBondState  bondStateStr;
    uint8 i=0,uBondFlag;
    uint8 uiPhoneMAC[6];
#if  1    
    if((STORE_MAC_DATA[PHONE_PASSWORD+0]==APP_ReceiveData[1] &&
       STORE_MAC_DATA[PHONE_PASSWORD+1]==APP_ReceiveData[2] &&
       STORE_MAC_DATA[PHONE_PASSWORD+2]==APP_ReceiveData[3] &&
       STORE_MAC_DATA[PHONE_PASSWORD+3]==APP_ReceiveData[4] &&
       STORE_MAC_DATA[PHONE_PASSWORD+4]==APP_ReceiveData[5] &&
       STORE_MAC_DATA[PHONE_PASSWORD+5]==APP_ReceiveData[6] )||
       (GATEWAY_PASSWORD_0 ==APP_ReceiveData[1] &&
        GATEWAY_PASSWORD_1 ==APP_ReceiveData[2] &&
        GATEWAY_PASSWORD_2 ==APP_ReceiveData[3] &&
        GATEWAY_PASSWORD_3 ==APP_ReceiveData[4] &&
        GATEWAY_PASSWORD_4 ==APP_ReceiveData[5] &&
        GATEWAY_PASSWORD_5 ==APP_ReceiveData[6] ))
#endif
#if  0
if(STORE_MAC_DATA[PHONE_PASSWORD+0]==APP_ReceiveData[1] &&
STORE_MAC_DATA[PHONE_PASSWORD+1]==APP_ReceiveData[2] &&
  STORE_MAC_DATA[PHONE_PASSWORD+2]==APP_ReceiveData[3] &&
  STORE_MAC_DATA[PHONE_PASSWORD+3]==APP_ReceiveData[4] &&
  STORE_MAC_DATA[PHONE_PASSWORD+4]==APP_ReceiveData[5] &&
  STORE_MAC_DATA[PHONE_PASSWORD+5]==APP_ReceiveData[6])
#endif      
    {
        uBondFlag= 1;
    }
    else
    {
        uBondFlag= 0;
    }
    
    for(i=0;i<6;i++)
    {
        uiPhoneMAC[i]=APP_ReceiveData[7+i];
    }
    
    bondStateStr = AppBonding_Phone(uiPhoneMAC,uBondFlag);
    
//    APP_SendData[0] = bondStateStr.SendData[0];
//    APP_SendData[1] = bondStateStr.SendData[1];
    Control_Permission = bondStateStr.Permission;  //bondStateStr·µ»ØÊý¾ÝºÍ²ÎÊý
    
    //ÉêÇëʧ°Ü´¦Àí
    if(bondStateStr.BondResult ==1)
    {
        //Ñé֤ʧ°Ü£¬¶Ï¿ªÉ豸
//        Util_restartClock(&TerminateClock,200);
//  app_timer_start(TerminateClock,APP_TIMER_TICKS(200), NULL);
//    SocketTaskAction(BLE_DISCON, 200);
 SocketTaskAction(BLE_DISCON, 1000);
    }
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
//*******************************************************************************
//ͨ¹ý¿ØÖÆȨÏÞÈ·ÈÏÊDz»ÊÇÉêÇë³É¹¦ 
    if(Control_Permission==1)
    {//ÉêÇë³É¹¦´¦Àí
        
        //˵Ã÷°ó¶¨³É¹¦
//        APP_SendData[0]=0x33;
        memset(APP_SendData,0,sizeof(APP_SendData)); 
        APP_SendData[0]=BLE_CMD_BONDINGVERIFY; 
        APP_SendData[1]=0x01;  
        //Ïòapp˵Ã÷Òª°ó¶¨µÄÉ豸µÄmacµØÖ·
//        for(i=0;i<6;i++)
//        {APP_SendData[i+2]=MAC_ADDR[i];}
 for(i=0;i<6;i++)
        {
  APP_SendData[i+2]=advertData[i+20];
}
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData); 
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
        
       //·¢ËÍ°æ±¾ºÅ
       memset(APP_SendData,0,sizeof(APP_SendData));
       APP_SendData[0] = BLE_CMD_VERSION_GET;
       //strcpy(APP_SendData+1,version);
       for(i=0;i<15;i++)
       {
           APP_SendData[i+1] = FirmwareVersion[i];
       }
//       ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);//·¢ËÍ°æ±¾º
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);   
        
     //·¢ËÍÐͺÅ
       APP_SendData[0] = BLE_CMD_PD_TYPE_GET;//20171017
    //strcpy(APP_SendData+1,version);
       APP_SendData[1] = 10;
       for(i=0;i<15;i++)
       {
           APP_SendData[i+2] = PD_TYPE[i];
       }
 //      ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
       ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);  
     
        //ÑéÖ¤³É¹¦£¬Í£Ö¹¶Ï¿ªÊ¼þ
//        Util_stopClock(&TerminateClock);
SocketTaskStop(BLE_DISCON); 
        //ÑéÖ¤°ó¶¨³É¹¦ºó£¬¾Í²»ÔÚÔÊÐíÔÙÀ´ÑéÖ¤°ó¶¨£¬Ö±ÖÁµ±Ç°Á¬½Ó¶Ï¿ª£¬²Å¿ÉÔÙ´ÎÑéÖ¤
        Control_Limit = 1;
        //¿ØÖÆledµÆ״̬ + ¶Ôapp·¢Ë͸üе±Ç°µÆµÄ״̬ //ÑÓºó400msÔÙ·¢ËÍ״̬˵Ã÷µÄÃüÁî
        Send_Flag=BLE_CMD_SNED2MASTER;
//        Util_restartClock(&SendDataClock,1000);
//  app_timer_start(SendDataClock,APP_TIMER_TICKS(1000), NULL);
 SocketTaskAction(SEND_DATA, 1000);
    }
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);   
    else
    {
        APP_SendData[0] = bondStateStr.SendData[0];
        APP_SendData[1] = bondStateStr.SendData[1];
//        ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    }
}




/*******************************************************************************
* Function    : AppBonding_Phone
* Description : °ó¶¨ÊÖ»ú
* Arguments   :  
* Return      :
*******************************************************************************/
#if   0
StrBondState AppBonding_Phone(uint8 uiPhoneMAC[],uint8 BondFlag)
{
  StrBondState  bondStateStr;
  uint8 i=0,Num=0;
//  uint8 sReadFlag[2];
//  uint8 sReadBuf[BOND_PHONEMAC_SIZE];
uint8 MacFlagBuf[PHONE_MAC_MAXNUM];
uint8 PhoneMacBuf[PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE];
ret_code_t err_code;
  
  bondStateStr.BondResult = 0;
  bondStateStr.Permission = 0;
  bondStateStr.SendData[0] = 0;
  bondStateStr.SendData[1] = 0;
  
  if(BondFlag== 1)       //Èç¹ûÃÜÂëÏàͬ
  {
      Num=0;
 
      err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);

 err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);

 DubegStringPut(mac_flag, sizeof(mac_flag));
 DubegStringPut(phone_mac, sizeof(phone_mac));
 
 for(i=0; i<PHONE_MAC_MAXNUM; i++)
      {
//          SpiFlash_ReadData(sReadFlag, BOND_MACFLAG_START_ADDR + i, 1);
//          SpiFlash_ReadData(sReadBuf, BOND_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* i), BOND_PHONEMAC_SIZE);
          
          if(mac_flag[i] == FLASH_MACSTATE_VALID)
          {
              if(phone_mac[BOND_PHONEMAC_SIZE*i]==uiPhoneMAC[0] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+1]==uiPhoneMAC[1] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+2]==uiPhoneMAC[2] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+3]==uiPhoneMAC[3] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+4]==uiPhoneMAC[4] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+5]==uiPhoneMAC[5] )       //Èç¹ûMACÏàͬ,±íʾÒѾ­°ó¶¨¹ýµÄÊÖ»ú
              {
                  bondStateStr.Permission = 1;      //»ñÈ¡É豸¿ØÖÆȨÏÞ
                  break;
              }
              Num++;  //²éÕÒflashÓÐЧ½‰¶¨ÊÖ»úµØÖ·ÐÅÏ¢(mac_flag[i] == FLASH_MACSTATE_VALID)µÄ¸öÊý
          }
          else if(mac_flag[i] == FLASH_MACSTATE_CLEAR)
          {
              if(phone_mac[BOND_PHONEMAC_SIZE*i]==0xff &&
                phone_mac[BOND_PHONEMAC_SIZE*i+1]==0xff &&
                phone_mac[BOND_PHONEMAC_SIZE*i+2]==0xff &&
                phone_mac[BOND_PHONEMAC_SIZE*i+3]==0xff &&
                phone_mac[BOND_PHONEMAC_SIZE*i+4]==0xff &&
                phone_mac[BOND_PHONEMAC_SIZE*i+5]==0xff )       //Èç¹ûMACΪ¿Õ
              {
                  mac_flag[i]= FLASH_MACSTATE_VALID;
//                  SpiFlash_WriteData(sReadFlag, BOND_MACFLAG_START_ADDR + i, 1);
//                  SpiFlash_WriteData(uiPhoneMAC, BOND_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* i), BOND_PHONEMAC_SIZE);
 phone_mac[BOND_PHONEMAC_SIZE*i] = uiPhoneMAC[0];
 phone_mac[BOND_PHONEMAC_SIZE*i+1] = uiPhoneMAC[1];
 phone_mac[BOND_PHONEMAC_SIZE*i+2] = uiPhoneMAC[2];
 phone_mac[BOND_PHONEMAC_SIZE*i+3] = uiPhoneMAC[3];
 phone_mac[BOND_PHONEMAC_SIZE*i+4] = uiPhoneMAC[4];
 phone_mac[BOND_PHONEMAC_SIZE*i+5] = uiPhoneMAC[5];
// ֮ǰÔÚÕâÀïûÓаÑÓÐЧ°ó¶¨±ê־дÈëFlash£¬µ¼ÖÂÏ´ζÁ³öÀ´µÄ±êÖ¾¶¼Îª FLASH_MACSTATE_CLEAR£¬ÊµÖÊûÓа󶨣¬
        //  ÏÂÃæ¼ÓÉÏÓÐЧÊÖ»ú°ó¶¨±£´æ£¬¼´¿ÉʵÏÖÊÖ»ú°ó¶¨ÊýÁ¿ÏÞÖÆ
            #if   1
 err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_WRITE);
   APP_ERROR_CHECK(err_code);

 uint16 TimeOutCnt = 0;
 while(sk_flash_num_pending_ops())
     {
TimeOutCnt++;
            if(TimeOutCnt >= 100)
break;
           }

   err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_WRITE);
           APP_ERROR_CHECK(err_code);

TimeOutCnt = 0;
while(sk_flash_num_pending_ops())
     {
            TimeOutCnt++;
            if(TimeOutCnt >= 100)
break;
           }
#endif
// ֮ǰÔÚÕâÀïûÓаÑÓÐЧ°ó¶¨±ê־дÈëFlash£¬µ¼ÖÂÏ´ζÁ³öÀ´µÄ±êÖ¾¶¼Îª FLASH_MACSTATE_CLEAR£¬ÊµÖÊûÓа󶨣¬
        //  ÉÏ Ãæ¼ÓÉÏÓÐЧÊÖ»ú°ó¶¨±£´æ  
                  bondStateStr.Permission = 1;      //»ñÈ¡É豸¿ØÖÆȨÏÞ
                  break;
              }
          }

//Num== PHONE_MAC_MAXNUM£¬±íʾȫ²¿´æ·ÅÇøÓò¶¼ÊÇÓÐЧµÄ°ó¶¨Á˵ÄÊÖ»úµØÖ·£¬ÎÞÐèÇå¿Õ
          //Num< PHONE_MAC_MAXNUM£¬±íʾÓнâ°óÁ˵ÄÊÖ»ú£¬Òª°Ñ½â°óÁ˵ÄÊÖ»úµØÖ·ÇøÓòÇå¿Õ£¬Ö´Ðе½ÕâÀïflashÀïÒѾ­Ã»ÓпÕλÖÃFLASH_MACSTATE_CLEAR´æ·ÅÊÖ»úµØÖ·£¬
//È«²¿´æ·ÅÇøÓò°üº¬ÐÅÏ¢Ö»Óаó¶¨Á˵ÄÊÖ»úºÍ½â°óÁ˵ÄÊÖ»ú£¬Òª°Ñ½â°óÁ˵ÄÊÖ»úµØÖ·ÇøÓòÇå¿ÕÈóöÀ´²ÅÄÜ´æ·ÅÖ®ºóÒª°ó¶¨µÄÊÖ»úµØÖ·
          if((i==(PHONE_MAC_MAXNUM-1))&&(Num< PHONE_MAC_MAXNUM)) //×îºó´æ´¢µÄÊÖ»úMAC,°ÑʧЧµÄMACÇå³ý£¬ÓÐЧµÄ±£Áô
          {
              uint8 j=0;

 
              
//              SpiFlash_EraseSector(IMAGE_PHONEDATA_START_ADDR);
/*
#if  0
 memset(MacFlagBuf, 0xFF, sizeof(MacFlagBuf));
 err_code = sk_flash_access_mac_flag0(MacFlagBuf, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 WaitFlashWriteEnd();
 



memset(PhoneMacBuf, 0xFF, sizeof(PhoneMacBuf));
err_code = sk_flash_access_phone_mac0(PhoneMacBuf, ES_FLASH_ACCESS_WRITE);
       APP_ERROR_CHECK(err_code);
WaitFlashWriteEnd();
 #endif


            
              Num =0;

err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#if  0
err_code = sk_flash_access_mac_flag0(mac_flag0, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
err_code = sk_flash_access_phone_mac0(phone_mac0, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
#endif
memset(mac_flag0, 0xFF, sizeof(mac_flag0));
memset(phone_mac0, 0xFF, sizeof(phone_mac0));

              for(j=0; j<PHONE_MAC_MAXNUM; j++)
              {
//                 SpiFlash_ReadData(sReadFlag, BOND_MACFLAG_START_ADDR + j, 1);
                 
  //³ýÁ˽â°óÁ˵ÄÊÖ»úµØÖ·ÇøÓò£¬°ÑµÚÒ»¿éflashÓаó¶¨ÊÖ»úµØÖ·µÄÇøÓò°´Ë³Ðò±£´æµ½µÚ¶þ¿é²Á³ýµÄflashÇøÓò
                  if(mac_flag[j] == FLASH_MACSTATE_VALID)
                  {
//                      SpiFlash_ReadData(sReadBuf, BOND_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* j), BOND_PHONEMAC_SIZE);
 
                      
//                      SpiFlash_WriteData(sReadFlag, IMAGE_MACFLAG_START_ADDR + Num, 1);
 mac_flag0[Num] = FLASH_MACSTATE_VALID;
//                      SpiFlash_WriteData(sReadBuf, IMAGE_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* Num), BOND_PHONEMAC_SIZE);
 phone_mac0[BOND_PHONEMAC_SIZE*Num] = phone_mac[BOND_PHONEMAC_SIZE*j];
 phone_mac0[BOND_PHONEMAC_SIZE*Num+1] = phone_mac[BOND_PHONEMAC_SIZE*j+1];
 phone_mac0[BOND_PHONEMAC_SIZE*Num+2] = phone_mac[BOND_PHONEMAC_SIZE*j+2];
 phone_mac0[BOND_PHONEMAC_SIZE*Num+3] = phone_mac[BOND_PHONEMAC_SIZE*j+3];
 phone_mac0[BOND_PHONEMAC_SIZE*Num+4] = phone_mac[BOND_PHONEMAC_SIZE*j+4];
 phone_mac0[BOND_PHONEMAC_SIZE*Num+5] = phone_mac[BOND_PHONEMAC_SIZE*j+5];
                      Num++;
                  }
              }

 err_code = sk_flash_access_mac_flag0(mac_flag0, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
WaitFlashWriteEnd();
 




err_code = sk_flash_access_phone_mac0(phone_mac0, ES_FLASH_ACCESS_WRITE);
       APP_ERROR_CHECK(err_code);
WaitFlashWriteEnd();

// DubegStringPut(phone_mac0, sizeof(phone_mac0));
// DubegStringPut(mac_flag0, sizeof(mac_flag0));




                  
//              SpiFlash_EraseSector(BOND_PHONEDATA_START_ADDR);
//²Á³ýflashÀïmac_flag±ê¼ÇÇøÓò
#if  0
memset(MacFlagBuf, 0xFF, sizeof(MacFlagBuf));
 err_code = sk_flash_access_mac_flag(MacFlagBuf, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
WaitFlashWriteEnd();
 


//²Á³ýflashÀïphone_macÊÖ»úµØÖ·ÇøÓò
memset(PhoneMacBuf, 0xFF, sizeof(PhoneMacBuf));
err_code = sk_flash_access_phone_mac(PhoneMacBuf, ES_FLASH_ACCESS_WRITE);
       APP_ERROR_CHECK(err_code);
WaitFlashWriteEnd();



#endif
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);


              
for(j=0; j<PHONE_MAC_MAXNUM; j++)
              {
//                 SpiFlash_ReadData(sReadFlag, BOND_MACFLAG_START_ADDR + j, 1);
//                 SpiFlash_WriteData(sReadFlag, IMAGE_MACFLAG_START_ADDR + j, 1);
#if  0
mac_flag0[j] = mac_flag[j];
                 
//                 SpiFlash_ReadData(sReadBuf, BOND_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* j), BOND_PHONEMAC_SIZE);
//                 SpiFlash_WriteData(sReadBuf, IMAGE_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* j), BOND_PHONEMAC_SIZE);
phone_mac0[BOND_PHONEMAC_SIZE*j] = phone_mac[BOND_PHONEMAC_SIZE*j];
phone_mac0[BOND_PHONEMAC_SIZE*j+1] = phone_mac[BOND_PHONEMAC_SIZE*j+1];
phone_mac0[BOND_PHONEMAC_SIZE*j+2] = phone_mac[BOND_PHONEMAC_SIZE*j+2];
phone_mac0[BOND_PHONEMAC_SIZE*j+3] = phone_mac[BOND_PHONEMAC_SIZE*j+3];
phone_mac0[BOND_PHONEMAC_SIZE*j+4] = phone_mac[BOND_PHONEMAC_SIZE*j+4];
phone_mac0[BOND_PHONEMAC_SIZE*j+5] = phone_mac[BOND_PHONEMAC_SIZE*j+5];
#endif
 mac_flag[j] = mac_flag0[j];
 phone_mac[BOND_PHONEMAC_SIZE*j] = phone_mac0[BOND_PHONEMAC_SIZE*j];
 phone_mac[BOND_PHONEMAC_SIZE*j+1] = phone_mac0[BOND_PHONEMAC_SIZE*j+1];
 phone_mac[BOND_PHONEMAC_SIZE*j+2] = phone_mac0[BOND_PHONEMAC_SIZE*j+2];
 phone_mac[BOND_PHONEMAC_SIZE*j+3] = phone_mac0[BOND_PHONEMAC_SIZE*j+3];
 phone_mac[BOND_PHONEMAC_SIZE*j+4] = phone_mac0[BOND_PHONEMAC_SIZE*j+4];
 phone_mac[BOND_PHONEMAC_SIZE*j+5] = phone_mac0[BOND_PHONEMAC_SIZE*j+5];
              } 

DubegStringPut(phone_mac, sizeof(phone_mac));
DubegStringPut(mac_flag, sizeof(mac_flag));
#if  1
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
WaitFlashWriteEnd();

err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_WRITE);
       APP_ERROR_CHECK(err_code);
WaitFlashWriteEnd();
#endif
#if   0
err_code = sk_flash_access_mac_flag0(mac_flag0, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
              err_code = sk_flash_access_phone_mac0(phone_mac0, ES_FLASH_ACCESS_WRITE);
       APP_ERROR_CHECK(err_code);



#endif
              
//              sReadFlag[0]= FLASH_MACSTATE_VALID;


 


//              SpiFlash_WriteData(uiPhoneMAC, BOND_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* Num), BOND_PHONEMAC_SIZE);
phone_mac[BOND_PHONEMAC_SIZE*Num] = uiPhoneMAC[0];
phone_mac[BOND_PHONEMAC_SIZE*Num+1] = uiPhoneMAC[1];
phone_mac[BOND_PHONEMAC_SIZE*Num+2] = uiPhoneMAC[2];
phone_mac[BOND_PHONEMAC_SIZE*Num+3] = uiPhoneMAC[3];
phone_mac[BOND_PHONEMAC_SIZE*Num+4] = uiPhoneMAC[4];
phone_mac[BOND_PHONEMAC_SIZE*Num+5] = uiPhoneMAC[5];



err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_WRITE);
       APP_ERROR_CHECK(err_code);
WaitFlashWriteEnd();

mac_flag[Num] = FLASH_MACSTATE_VALID;
//              SpiFlash_WriteData(sReadFlag, BOND_MACFLAG_START_ADDR + Num, 1);
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
WaitFlashWriteEnd();

err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);

DubegStringPut(phone_mac, sizeof(phone_mac));
DubegStringPut(mac_flag, sizeof(mac_flag));




              bondStateStr.Permission = 1;      //»ñÈ¡É豸¿ØÖÆȨÏÞ
              break;
*/
          }
      }
      if(i>=PHONE_MAC_MAXNUM)
      {
           //¼Ç¼ÇëÇóʧ°Ü£¬ºóÃæÔÚ´¦Àí£¬·ÀÖ¹Êǰ󶨹ýµÄÉ豸
           bondStateStr.BondResult = 1;
           //Ïòapp˵Ã÷°ó¶¨µÄÉ豸ÒѾ­ÂúÁË
           bondStateStr.SendData[0]=BLE_CMD_BONDINGVERIFY;
           bondStateStr.SendData[1]=0x03;
      }
  }
  else
  {
      //¼Ç¼ÇëÇóʧ°Ü£¬ºóÃæÔÚ´¦Àí£¬·ÀÖ¹Êǰ󶨹ýµÄÉ豸
      bondStateStr.BondResult = 1;
      //Ïòapp˵Ã÷°ó¶¨µÄÃÜÂë´íÎó
      bondStateStr.SendData[0]=BLE_CMD_BONDINGVERIFY;
      bondStateStr.SendData[1]=0x02;
  }


err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);

err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
   for(i=0; i<PHONE_MAC_MAXNUM; i++)
   {
     
//       SpiFlash_ReadData(sReadFlag, BOND_MACFLAG_START_ADDR + i, 1);
//       SpiFlash_ReadData(sReadBuf, BOND_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* i), BOND_PHONEMAC_SIZE);
          
          if(mac_flag[i] == FLASH_MACSTATE_VALID)
          {
              if(phone_mac[BOND_PHONEMAC_SIZE*i] == uiPhoneMAC[0] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+1]==uiPhoneMAC[1] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+2]==uiPhoneMAC[2] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+3]==uiPhoneMAC[3] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+4]==uiPhoneMAC[4] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+5]==uiPhoneMAC[5] )       //Èç¹ûMACÏàͬ,±íʾÒѾ­°ó¶¨¹ýµÄÊÖ»ú
              {
                bondStateStr.Permission = 1;      //»ñÈ¡É豸¿ØÖÆȨÏÞ
                break;
              }
          }
   }
   if(i<PHONE_MAC_MAXNUM)
   {
      //»ñÈ¡É豸¿ØÖÆȨÏÞ
      bondStateStr.Permission = 1;
      //Çå³ý¼Ç¼ʧ°ÜµÄ¼Ç¼£¬·ÀÖ¹
      bondStateStr.BondResult = 0;
     
   }
    return bondStateStr;
}
#endif






StrBondState AppBonding_Phone(uint8 uiPhoneMAC[],uint8 BondFlag)
{
  StrBondState  bondStateStr;
  uint8 i=0;
//  uint8 sReadFlag[2];
//  uint8 sReadBuf[BOND_PHONEMAC_SIZE];
// uint8 MacFlagBuf[PHONE_MAC_MAXNUM];
// uint8 PhoneMacBuf[PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE];
ret_code_t err_code;
  
  bondStateStr.BondResult = 0;
  bondStateStr.Permission = 0;
  bondStateStr.SendData[0] = 0;
  bondStateStr.SendData[1] = 0;
  
  if(BondFlag== 1)       //Èç¹ûÃÜÂëÏàͬ
  {
//      Num=0;
 
      err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);

 err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);


#if (PHONE_MAC_MAXNUM == 10)
 DubegStringPut(mac_flag, sizeof(mac_flag));
 DubegStringPut(phone_mac, sizeof(phone_mac));
#elif (PHONE_MAC_MAXNUM == 100)
      int  i;


      for(i=0; i<PHONE_MAC_MAXNUM; i++)
      {
DubegStringPut(mac_flag+i, 1);
}
 
 for(i=0; i<PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE; i++)
 {
DubegStringPut(phone_mac+i, 1);
}


#endif      


      for(i=0; i<PHONE_MAC_MAXNUM; i++)
 {
          if(mac_flag[i] == FLASH_MACSTATE_VALID)
          {
              if(phone_mac[BOND_PHONEMAC_SIZE*i]==uiPhoneMAC[0] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+1]==uiPhoneMAC[1] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+2]==uiPhoneMAC[2] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+3]==uiPhoneMAC[3] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+4]==uiPhoneMAC[4] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+5]==uiPhoneMAC[5] )       //Èç¹ûMACÏàͬ,±íʾÒѾ­°ó¶¨¹ýµÄÊÖ»ú
              {
                  bondStateStr.Permission = 1;      //»ñÈ¡É豸¿ØÖÆȨÏÞ
                  break;
              }
//              Num++;  //²éÕÒflashÓÐЧ½‰¶¨ÊÖ»úµØÖ·ÐÅÏ¢(mac_flag[i] == FLASH_MACSTATE_VALID)µÄ¸öÊý
          }
}

if(i >= PHONE_MAC_MAXNUM)
{
for(i=0; i<PHONE_MAC_MAXNUM; i++)
   {
if(mac_flag[i] == FLASH_MACSTATE_CLEAR)
{
if(phone_mac[BOND_PHONEMAC_SIZE*i]==0xff &&
phone_mac[BOND_PHONEMAC_SIZE*i+1]==0xff &&
phone_mac[BOND_PHONEMAC_SIZE*i+2]==0xff &&
phone_mac[BOND_PHONEMAC_SIZE*i+3]==0xff &&
                      phone_mac[BOND_PHONEMAC_SIZE*i+4]==0xff &&
                      phone_mac[BOND_PHONEMAC_SIZE*i+5]==0xff )       //Èç¹ûMACΪ¿Õ
{
mac_flag[i]= FLASH_MACSTATE_VALID;
   phone_mac[BOND_PHONEMAC_SIZE*i] = uiPhoneMAC[0];
       phone_mac[BOND_PHONEMAC_SIZE*i+1] = uiPhoneMAC[1];
       phone_mac[BOND_PHONEMAC_SIZE*i+2] = uiPhoneMAC[2];
       phone_mac[BOND_PHONEMAC_SIZE*i+3] = uiPhoneMAC[3];
       phone_mac[BOND_PHONEMAC_SIZE*i+4] = uiPhoneMAC[4];
       phone_mac[BOND_PHONEMAC_SIZE*i+5] = uiPhoneMAC[5];
 
   err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_WRITE);
         APP_ERROR_CHECK(err_code);
   WaitFlashWriteEnd();
 
   err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_WRITE);
                 APP_ERROR_CHECK(err_code);
   WaitFlashWriteEnd();
 
   bondStateStr.Permission = 1;      //»ñÈ¡É豸¿ØÖÆȨÏÞ
                        break;
}
}
}
}
          
          


/*
//Num== PHONE_MAC_MAXNUM£¬±íʾȫ²¿´æ·ÅÇøÓò¶¼ÊÇÓÐЧµÄ°ó¶¨Á˵ÄÊÖ»úµØÖ·£¬ÎÞÐèÇå¿Õ
          //Num< PHONE_MAC_MAXNUM£¬±íʾÓнâ°óÁ˵ÄÊÖ»ú£¬Òª°Ñ½â°óÁ˵ÄÊÖ»úµØÖ·ÇøÓòÇå¿Õ£¬Ö´Ðе½ÕâÀïflashÀïÒѾ­Ã»ÓпÕλÖÃFLASH_MACSTATE_CLEAR´æ·ÅÊÖ»úµØÖ·£¬
//È«²¿´æ·ÅÇøÓò°üº¬ÐÅÏ¢Ö»Óаó¶¨Á˵ÄÊÖ»úºÍ½â°óÁ˵ÄÊÖ»ú£¬Òª°Ñ½â°óÁ˵ÄÊÖ»úµØÖ·ÇøÓòÇå¿ÕÈóöÀ´²ÅÄÜ´æ·ÅÖ®ºóÒª°ó¶¨µÄÊÖ»úµØÖ·
          if((i==(PHONE_MAC_MAXNUM-1))&&(Num< PHONE_MAC_MAXNUM)) //×îºó´æ´¢µÄÊÖ»úMAC,°ÑʧЧµÄMACÇå³ý£¬ÓÐЧµÄ±£Áô
          {
              uint8 j=0;

 
              


          }
*/
      
      if(i>=PHONE_MAC_MAXNUM)
      {
#if  0
           //¼Ç¼ÇëÇóʧ°Ü£¬ºóÃæÔÚ´¦Àí£¬·ÀÖ¹Êǰ󶨹ýµÄÉ豸
           bondStateStr.BondResult = 1;
           //Ïòapp˵Ã÷°ó¶¨µÄÉ豸ÒѾ­ÂúÁË
           bondStateStr.SendData[0]=BLE_CMD_BONDINGVERIFY;
           bondStateStr.SendData[1]=0x03;
#else
  bondStateStr.Permission = 1;      //»ñÈ¡É豸¿ØÖÆȨÏÞ
#endif
      }
  }
  else
  {
      //¼Ç¼ÇëÇóʧ°Ü£¬ºóÃæÔÚ´¦Àí£¬·ÀÖ¹Êǰ󶨹ýµÄÉ豸
      bondStateStr.BondResult = 1;
      //Ïòapp˵Ã÷°ó¶¨µÄÃÜÂë´íÎó
      bondStateStr.SendData[0]=BLE_CMD_BONDINGVERIFY;
      bondStateStr.SendData[1]=0x02;
  }
#if  0
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);

err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
   for(i=0; i<PHONE_MAC_MAXNUM; i++)
   {
     
//       SpiFlash_ReadData(sReadFlag, BOND_MACFLAG_START_ADDR + i, 1);
//       SpiFlash_ReadData(sReadBuf, BOND_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* i), BOND_PHONEMAC_SIZE);
          
          if(mac_flag[i] == FLASH_MACSTATE_VALID)
          {
              if(phone_mac[BOND_PHONEMAC_SIZE*i] == uiPhoneMAC[0] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+1]==uiPhoneMAC[1] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+2]==uiPhoneMAC[2] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+3]==uiPhoneMAC[3] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+4]==uiPhoneMAC[4] &&
                phone_mac[BOND_PHONEMAC_SIZE*i+5]==uiPhoneMAC[5] )       //Èç¹ûMACÏàͬ,±íʾÒѾ­°ó¶¨¹ýµÄÊÖ»ú
              {
                bondStateStr.Permission = 1;      //»ñÈ¡É豸¿ØÖÆȨÏÞ
                break;
              }
          }
   }
   if(i<PHONE_MAC_MAXNUM)
   {
      //»ñÈ¡É豸¿ØÖÆȨÏÞ
      bondStateStr.Permission = 1;
      //Çå³ý¼Ç¼ʧ°ÜµÄ¼Ç¼£¬·ÀÖ¹
      bondStateStr.BondResult = 0;
     
   }
#endif
    return bondStateStr;
}




void MACADDR_GET(void)
{
    //*******************************************************************************
    //Lewis- 20170427(Ôö¼ÓÊÖ»ú°ó¶¨ÊýÁ¿)        
    memset(APP_SendData,0,sizeof(APP_SendData));
    uint8 i=0;
    uint8 uiPhoneMAC[6];
    
    for(i=0;i<6;i++)
    {
        uiPhoneMAC[i]=APP_ReceiveData[1+i];
    }
    
    if(AppBonding_Verification(uiPhoneMAC) == 1)
    {
        //*******************************************************************************
        //ÑéÖ¤³É¹¦£¬Í£Ö¹¶Ï¿ªÊ¼þ
//        Util_stopClock(&TerminateClock);
//  app_timer_stop(TerminateClock);
 SocketTaskStop(BLE_DISCON);
 
        //¿ØÖÆledµÆ״̬
        control_led2();
        //ÑéÖ¤°ó¶¨³É¹¦ºó£¬¾Í²»ÔÚÔÊÐíÔÙÀ´ÑéÖ¤°ó¶¨£¬Ö±ÖÁµ±Ç°Á¬½Ó¶Ï¿ª£¬²Å¿ÉÔÙ´ÎÑéÖ¤
        Control_Limit = 1;
        //¿ª·Å¿ØÖÆȨÏÞ£¬ÔÚͨ¹ýÑéÖ¤ºó£¬¾Í¿ÉÒÔÈ¥¿ØÖƲå×ùµÄ״̬ºÍ¹¦ÄÜ
        Control_Permission=1;
        
//        APP_SendData[0]=0x41;
        APP_SendData[0]=BLE_CMD_MACVERIFY;
        APP_SendData[1]=0x01;
    }
    else
    {
        //°ó¶¨Ê§Ð§£¬ÇëÖØаó¶¨
//        APP_SendData[0]=0x42;
        APP_SendData[0]=BLE_CMD_MACVERIFY;
        APP_SendData[1]=0x00;
//        for(i=0;i<6;i++)
//        {APP_SendData[i+2]=MAC_ADDR[i];}

for(i=0;i<6;i++)
        {
APP_SendData[i+2]=advertData[i+20];
}
        
        //Ñé֤ʧ°Ü£¬¿ªÆô¶Ï¿ªÊ¼þ£¬200msºó¶Ï¿ª
//        Util_restartClock(&TerminateClock,200);
// app_timer_start(TerminateClock,APP_TIMER_TICKS(200), NULL);
SocketTaskAction(BLE_DISCON, 200);
    }
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);  
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}




/*******************************************************************************
* Function    : AppBonding_Verification
* Description : ÑéÖ¤°ó¶¨MAC
* Arguments   :
* Return      :
*******************************************************************************/
uint8 AppBonding_Verification(uint8 uiPhoneMAC[])
{
  uint8 i=0;
//  uint8 sReadFlag[2];
//  uint8 sReadBuf[BOND_PHONEMAC_SIZE];
ret_code_t err_code;
  
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);

err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
   for(i=0; i<PHONE_MAC_MAXNUM; i++)
   {
 //      SpiFlash_ReadData(sReadFlag, BOND_MACFLAG_START_ADDR + i, 1);
 //      SpiFlash_ReadData(sReadBuf, BOND_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* i), BOND_PHONEMAC_SIZE);
          
       if(mac_flag[i] == FLASH_MACSTATE_VALID)
       {
          if(phone_mac[BOND_PHONEMAC_SIZE*i]==uiPhoneMAC[0] &&
             phone_mac[BOND_PHONEMAC_SIZE*i+1]==uiPhoneMAC[1] &&
             phone_mac[BOND_PHONEMAC_SIZE*i+2]==uiPhoneMAC[2] &&
             phone_mac[BOND_PHONEMAC_SIZE*i+3]==uiPhoneMAC[3] &&
             phone_mac[BOND_PHONEMAC_SIZE*i+4]==uiPhoneMAC[4] &&
             phone_mac[BOND_PHONEMAC_SIZE*i+5]==uiPhoneMAC[5] )       //Èç¹ûMACÏàͬ,±íʾÒѾ­°ó¶¨¹ýµÄÊÖ»ú
          {
              break;
          }
       }
   }
   if(i<PHONE_MAC_MAXNUM)
   {
        return 1;
   }
   else
   {
        return 0;
   }
}




/*******************************************************************************
* Function    : AppBonding_LostPhoneMAC
* Description : MACʧЧ
* Arguments   :
* Return      :
*******************************************************************************/
uint8 AppBonding_LostPhoneMAC(uint8 uiPhoneMAC[])
{
  uint8 i=0;
//  uint8 sReadFlag[2];
//  uint8 sReadBuf[BOND_PHONEMAC_SIZE];
ret_code_t err_code;
  
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);

err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
  for(i=0; i<PHONE_MAC_MAXNUM; i++)
  {
//      SpiFlash_ReadData(sReadFlag, BOND_MACFLAG_START_ADDR + i, 1);
//      SpiFlash_ReadData(sReadBuf, BOND_PHONEMAC_START_ADDR +( FLASH_MAC_SIZE* i), BOND_PHONEMAC_SIZE);
          
      if(mac_flag[i] == FLASH_MACSTATE_VALID)
      {
          if(phone_mac[BOND_PHONEMAC_SIZE*i]==uiPhoneMAC[0] &&
            phone_mac[BOND_PHONEMAC_SIZE*i+1]==uiPhoneMAC[1] &&
            phone_mac[BOND_PHONEMAC_SIZE*i+2]==uiPhoneMAC[2] &&
            phone_mac[BOND_PHONEMAC_SIZE*i+3]==uiPhoneMAC[3] &&
            phone_mac[BOND_PHONEMAC_SIZE*i+4]==uiPhoneMAC[4] &&
            phone_mac[BOND_PHONEMAC_SIZE*i+5]==uiPhoneMAC[5] )       //Èç¹ûMACÏàͬ,±íʾÒѾ­°ó¶¨¹ýµÄÊÖ»ú
          {
 //             mac_flag[i]= FLASH_MACSTATE_INVALID;
 mac_flag[i] = FLASH_MACSTATE_CLEAR;
 phone_mac[BOND_PHONEMAC_SIZE*i]    = FLASH_MACSTATE_CLEAR;
 phone_mac[BOND_PHONEMAC_SIZE*i+1]  = FLASH_MACSTATE_CLEAR;
 phone_mac[BOND_PHONEMAC_SIZE*i+2]  = FLASH_MACSTATE_CLEAR;
 phone_mac[BOND_PHONEMAC_SIZE*i+3]  = FLASH_MACSTATE_CLEAR;
 phone_mac[BOND_PHONEMAC_SIZE*i+4]  = FLASH_MACSTATE_CLEAR;
 phone_mac[BOND_PHONEMAC_SIZE*i+5]  = FLASH_MACSTATE_CLEAR;
 //             SpiFlash_WriteData(sReadFlag, BOND_MACFLAG_START_ADDR + i, 1);
 err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);

 err_code = sk_flash_access_phone_mac(phone_mac, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
// while(sk_flash_num_pending_ops())
 {
            ;
       }
 
              return 1;
          }
      }
  }
  return 0;
}




/*******************************************************************************
* Function    : AppBonding_LostPhoneAll
* Description : ʧЧËùÓÐMAC
* Arguments   :
* Return      :
*******************************************************************************/
#if  0
void AppBonding_LostPhoneAll(void)
{
    BondInfo_t sBondInfo;
 uint32  err_code;


//    SpiFlash_EraseSector(BOND_PHONEDATA_START_ADDR);
       
    sBondInfo.bond[0] = 'B';
    sBondInfo.bond[1] = 'o';
    sBondInfo.bond[2] = 'n';
    sBondInfo.bond[3] = 'd';
//    SpiFlash_WriteData((uint8*)&sBondInfo, BOND_PHONEDATA_START_ADDR, sizeof(sBondInfo));
 err_code = sk_flash_access_bond_infor(&sBondInfo, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);
// while(sk_flash_num_pending_ops())
{
;
 }
 
}
#endif


/*******************************************************************************
* Function    : AppBonding_LostPhoneAll
* Description : ʧЧËùÓÐMAC
* Arguments   :
* Return      :
*******************************************************************************/
uint8 AppBonding_CheckPhoneMAC(void)
{
  uint8 i=0,Num=0;
//  uint8 sReadFlag[2];
ret_code_t err_code;
  
err_code = sk_flash_access_mac_flag(mac_flag, ES_FLASH_ACCESS_READ);
APP_ERROR_CHECK(err_code);
  for(i=0; i<PHONE_MAC_MAXNUM; i++)
  {
//      SpiFlash_ReadData(sReadFlag, BOND_MACFLAG_START_ADDR + i, 1);
          
      if(mac_flag[i] == FLASH_MACSTATE_VALID)
      {
          Num++;
      }
  }
  return Num;         //°ó¶¨É豸ÊýÁ¿, 0:δ°ó¶¨ÈκÎÉ豸 
}




//**************************************************************************************************
void SUPPER_LIMIT(void)
{
    uint8 i=0;
 ret_code_t err_code;
    memset(APP_SendData,0,sizeof(APP_SendData));
    memset(STORE_MAC_DATA,0,sizeof(STORE_MAC_DATA));
    for(i=0;i<6;i++)
    {
        STORE_MAC_DATA[PHONE_PASSWORD+i]=48+i+1;//³õʼÃÜÂë'123456'
    }
    AdditionalCtrl = ADDCTRL_OPEN_TIMING;
    STORE_MAC_DATA[ADDCTRL_STORE_INDEX] = AdditionalCtrl;
//    osal_snv_write( ENV_STORE_MAC_ADDR, sizeof(STORE_MAC_DATA), STORE_MAC_DATA );
err_code = sk_flash_access_mac_data(STORE_MAC_DATA, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);
 
// while(sk_flash_num_pending_ops())
{
 ;
}
    
//    APP_SendData[0] = 0x4D;
//    APP_SendData[1] = 0x01;
    APP_SendData[0] = BLE_CMD_SUPPER_LIMIT;
    APP_SendData[1] = 0x01;
//    ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
    
    //ʧȥ¿ØÖÆȨÏÞ
    Control_Permission=0;
    
    //ʧЧ³É¹¦£¬¶Ï¿ªÉ豸
//    Util_restartClock(&TerminateClock,200);
// app_timer_start(TerminateClock,APP_TIMER_TICKS(200), NULL);
SocketTaskAction(BLE_DISCON, 200);
}  


#include "ble_nus.h"
#include "socket_cfg.h"
#include "timer_modif.h"
#include "BleCommand.h"
#include "sk_flash.h"
#include "adv_evt.h"












//**************************************************************************************************
void AUTO_EN_DIS(void)
{
 ret_code_t err_code;
    if(APP_ReceiveData[2] == 1)
    {
        if(APP_ReceiveData[1] == 1)
        {
            Sockets.Mode |= MODE_AUTO;
            
//            osal_snv_write( ENV_SOCKET_STORE_ADDR, sizeof(Sockets), &Sockets );
 err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
 APP_SendData[0] = BLE_CMD_AUTO_EN_DIS;
            APP_SendData[1] = APP_ReceiveData[1];
            APP_SendData[2] = Sockets.Mode;
//            ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
        }
        UpdateAdvData(); 
    }
    else
    {
        if(APP_ReceiveData[1] == 1)
        {
            Sockets.Mode &= ~MODE_AUTO;
            
//            osal_snv_write( ENV_SOCKET_STORE_ADDR, sizeof(Sockets), &Sockets );
 err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
APP_ERROR_CHECK(err_code);
 
//  while(sk_flash_num_pending_ops())
{
        ;
     }
            
            APP_SendData[0] = BLE_CMD_AUTO_EN_DIS;
            APP_SendData[1] = APP_ReceiveData[1];
            APP_SendData[2] = Sockets.Mode;
//            ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
        }
        
        UpdateAdvData();
    }
}








void SetDevicePowerActionType(void)
{
   ret_code_t err_code;
uint8  SwitchIndex = APP_ReceiveData[1];
   uint8  SwitchActionType = APP_ReceiveData[2];

   if((SwitchIndex != 1) && (SwitchIndex != 0))
return;

if((SwitchActionType != 0) && (SwitchActionType != 1))
return;

Sockets.PowerActionType  = SwitchActionType;

err_code = sk_flash_access_sockets(&Sockets, ES_FLASH_ACCESS_WRITE);
 APP_ERROR_CHECK(err_code);

 memset(APP_SendData,0,sizeof(APP_SendData));
APP_SendData[0] = BLE_CMD_POWER_ACTION_TYPE;
APP_SendData[1] = SwitchIndex;
APP_SendData[2] = SwitchActionType;
ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}






void ReadDevicePowerActionType(void)
{
memset(APP_SendData,0,sizeof(APP_SendData));
   APP_SendData[0] = BLE_CMD_READ_POWER_ON_ACTION;
   APP_SendData[1] = 1;
   APP_SendData[2] = Sockets.PowerActionType;
   ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength);
}



#include  "ble_advdata.h"
#include  "ble_nus.h"
#include  "adv_evt.h"
#include  "bond.h"
#include  "timer_modif.h"
#include  "name_evt.h"
#include  "sk_evt.h"
#include  "pwd_evt.h"




#define  ADV_ON_STOP     1
#define  ADV_NO_STOP     0




#define  SOCKET_ADV_CUR_OPEN     1
#define  SOCKET_ADV_PRE_OPEN     0






uint8  sk_user_data[] = {1,0,0,0,0,0,0,0,0,0,0,0,0}; 


ble_advdata_service_data_t  SocketServiceData =     
{
     .service_uuid  = BLE_UUID_NUS_SERVICE,
     .data.size = sizeof(sk_user_data)/sizeof(sk_user_data[0]),
.data.p_data  = sk_user_data,
};


uint8  CurDisconPend;
uint8  SocketAdvStopFlag;
//uint8  SocketAdvStartFlag;


#if  0
uint8_t advertData[] =
{
  0x02,               // length of first data structure (2 bytes excluding length byte)
  BLE_GAP_AD_TYPE_FLAGS,   // AD Type = Flags
  BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE,


  //·þÎñUUID
  3,
  BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE,
  LO_UINT16(BLE_UUID_NUS_SERVICE),
  HI_UINT16(BLE_UUID_NUS_SERVICE),
  
  //¿ª¹Ø״̬
  5+7+6,
  BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA,
  LO_UINT16(BLE_UUID_NUS_SERVICE),
  HI_UINT16(BLE_UUID_NUS_SERVICE),
  AXA_FLAG, // 0x5a or 0xa5  0x5a mean bonding by ble-gate. 0xa5 mean not bonding, we can express by this byte
  0x02,// see below type define
  1,          //¿ª¹ØÊýÁ¿
  0x00,0x00,0x00,                 //¿ª¹Ø1/2/3µÄ״̬: 0¹Ø±Õ,1¿ªÆô
  0x00,0x00,0x00,                 //¿ª¹Ø1/2/3µÄģʽ: 0ÊÖ¶¯,1×Ô¶¯


  
  0x00,0x00,0x00,                 //É豸µÄmacµØÖ·//½öΪƻ¹ûÉèÖ㬰²×¿²»ÐèҪʹÓÃ
  0x00,0x00,0x00,
};
#else


uint8_t advertData[] =
{
  0x02,               // length of first data structure (2 bytes excluding length byte)
  BLE_GAP_AD_TYPE_FLAGS,   // AD Type = Flags
  BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE,


  //·þÎñUUID
  3,
  BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE,
  LO_UINT16(BLE_UUID_NUS_SERVICE),
  HI_UINT16(BLE_UUID_NUS_SERVICE),
  
  15,
  BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA,
  
  0x00,0x00,0x00,                 //¿ª¹Ø1/2/3µÄ״̬: 0¹Ø±Õ,1¿ªÆô
  0x00,0x00,0x00,                 //¿ª¹Ø1/2/3µÄģʽ: 0ÊÖ¶¯,1×Ô¶¯
  PRODUCT_ID_HIG_BYTE,
PRODUCT_ID_LOW_BYTE,

0x41, //'A'
0x58, //'X'
0x41, //'A'
0x45, //'E'
0x54, //'T'
//  0x53,
0,
};




#endif




uint16_t  sk_adv_length = sizeof(advertData);       


uint8 updata_flag=0;


//³õʼ»¯¹ã²¥°ü
void InitAdvData(void)
{
    if(Sockets.Mode & MODE_AUTO)
        advertData[14] = 1;
    else
        advertData[14] = Sockets.Status;
    
    if(Sockets.Mode & MODE_AUTO)
        advertData[17] = 1;
    else
        advertData[17] = 0;
}






void advertising_start(void)
{
    ret_code_t           err_code;
    ble_gap_adv_params_t adv_params;


    // Start advertising
    memset(&adv_params, 0, sizeof(adv_params));


    adv_params.type        = BLE_GAP_ADV_TYPE_ADV_IND;
    adv_params.p_peer_addr = NULL;
    adv_params.fp          = BLE_GAP_ADV_FP_ANY;
    adv_params.interval    = APP_ADV_INTERVAL;
    adv_params.timeout     = APP_ADV_TIMEOUT_IN_SECONDS;


    err_code = sd_ble_gap_adv_start(&adv_params, APP_BLE_CONN_CFG_TAG);
    APP_ERROR_CHECK(err_code);

 SocketAdvStopFlag = ADV_NO_STOP;
}






void  SocketAdvStartAccept(uint8 AdvStartEn)
{
if(AdvStartEn == true)
{
// advertising_start();
 SocketTaskAction(START_ADV, 2000);
//  SocketAdvStopFlag = ADV_NO_STOP;
}
}




void  SocketAdvStopAccept(uint8 AdvStopEn)
{
 uint32_t err_code;
if(AdvStopEn == true)
{
err_code = sd_ble_gap_adv_stop();   //Ò»¶¨ÒªÔڹ㲥״̬ÏÂÖ´Ðйع㲥£¬·ñÔò±¨´í
 APP_ERROR_CHECK(err_code);
 SocketAdvStopFlag = ADV_ON_STOP;
}
}




uint8  SocketAdvStaGet(void)
{
 uint8 AdvSta;
if(SocketAdvStopFlag == ADV_ON_STOP)
{
AdvSta = SOCKET_ADV_PRE_OPEN; 
}
    else if(SocketAdvStopFlag == ADV_NO_STOP)
{
AdvSta = SOCKET_ADV_CUR_OPEN;
}

return AdvSta; 
}




//¸üй㲥°ü
void UpdateAdvData(void)
{
#if  0
    advertData[14] = Sockets.Status;
    
    if(Sockets.Mode & MODE_AUTO)
        advertData[17] = 1;
    else
        advertData[17] = 0;
  #endif
// advertData[22] = (IsPassWordModify()) ? 1:0;
#if 1
if(IsPassWordModify())
{
advertData[22] = 0;
}
else
{
advertData[22] = 0;
}
#endif


if(Tx_Rx_Nux.conn_handle == BLE_CONN_HANDLE_INVALID)
{
   uint32_t err_code;
uint16 sk_scrp_length = sizeof(deviceName);
   if(CurDisconPend == 0)
{
#if   1  
err_code = sd_ble_gap_adv_stop();   //Ò»¶¨ÒªÔڹ㲥״̬ÏÂÖ´Ðйع㲥£¬·ñÔò±¨´í

 APP_ERROR_CHECK(err_code);
 err_code = sd_ble_gap_adv_data_set(advertData, sk_adv_length, deviceName, sk_scrp_length);
 APP_ERROR_CHECK(err_code);
 advertising_start();


#endif
#if   0
SocketAdvStopAccept((SocketAdvStaGet() == SOCKET_ADV_CUR_OPEN) ? true : false);
 err_code = sd_ble_gap_adv_data_set(advertData, sk_adv_length, deviceName, sk_scrp_length);
 APP_ERROR_CHECK(err_code);
 SocketAdvStartAccept((SocketAdvStaGet() == SOCKET_ADV_PRE_OPEN) ? true : false);
#endif


}
else
{
CurDisconPend = 0;
#if  0
SocketTaskAction(START_ADV, 100);    //APP·¢Æð¶ÏÁ´»áÒýÆð¸´Î»£¬²å×ùÉ豸·¢Æð¶ÏÁ´²»»á
#else
 //¶Ï¿ªÁ¬½Óºó£¬´¦Óڹ㲥ֹͣ״̬
 err_code = sd_ble_gap_adv_data_set(advertData, sk_adv_length, deviceName, sizeof(deviceName));
         APP_ERROR_CHECK(err_code);
         advertising_start();
#endif
}
}
}


/**
 * Copyright (c) 2014 - 2017, Nordic Semiconductor ASA
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 * 
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 * 
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 * 
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 * 
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */
/** @file
 *
 * @defgroup ble_sdk_uart_over_ble_main main.c
 * @{
 * @ingroup  ble_sdk_app_nus_eval
 * @brief    UART over BLE application main file.
 *
 * This file contains the source code for a sample application that uses the Nordic UART service.
 * This application uses the @ref srvlib_conn_params module.
 */






#include <stdint.h>
#include <string.h>
#include "nordic_common.h"
#include "nrf.h"
#include "ble_hci.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
#include "nrf_ble_gatt.h"
#include "app_timer.h"
#include "ble_nus.h"
#include "app_uart.h"
#include "app_util_platform.h"
#include "bsp_btn_ble.h"
#include "cmd_dispatch.h"
#include "sk_evt.h"
#include "switch_action.h"
#include "timer_modif.h"
#include "BleCommand.h"
#include "sk_flash.h"
#include "name_evt.h"
#include "bond.h"
#include "adv_evt.h"
#include "socket_query.h"
#include "ble_dtm.h"
#include "pwd_evt.h"
#include "dorlock_user_mgr.h"
#include "user_cipher_mgr.h"
#include "rtc_cripht_mgr.h"
#include "dorlock_cmd_rsp.h"
//#include "user_wdt.h"


#if defined (UART_PRESENT)
#include "nrf_uart.h"
#endif
#if defined (UARTE_PRESENT)
#include "nrf_uarte.h"
#endif


#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "app_scheduler.h"
#include "bd_wall_clock_timer.h"








#define APP_SCHED_MAX_EVENT_SIZE    0   /**< Maximum size of scheduler events. */
#define APP_SCHED_QUEUE_SIZE        4   /**< Maximum number of events in the scheduler queue. */




//#define APP_BLE_CONN_CFG_TAG            1                                           /**< A tag identifying the SoftDevice BLE configuration. */


#define APP_FEATURE_NOT_SUPPORTED       BLE_GATT_STATUS_ATTERR_APP_BEGIN + 2        /**< Reply when unsupported features are requested. */


#if  defined (AXA_SMART_BOX)
#define DEVICE_NAME                     "AxaSmartLock"                               /**< Name of device. Will be included in the advertising data. */
#elif defined (AXA_SMART_SOCKET)
#define DEVICE_NAME                     "AxaSmartSocket"
#endif


//#define NUS_SERVICE_UUID_TYPE           BLE_UUID_TYPE_VENDOR_BEGIN                  /**< UUID type for the Nordic UART Service (vendor specific). */


#define APP_BLE_OBSERVER_PRIO           3                                           /**< Application's BLE observer priority. You shouldn't need to modify this value. */


//#define APP_ADV_INTERVAL                64                                          /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
//#define APP_ADV_TIMEOUT_IN_SECONDS      180                                         /**< The advertising timeout (in units of seconds). */




//#define APP_ADV_TIMEOUT_IN_SECONDS      BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED 


#define MIN_CONN_INTERVAL               MSEC_TO_UNITS(20, UNIT_1_25_MS)             /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
#define MAX_CONN_INTERVAL               MSEC_TO_UNITS(75, UNIT_1_25_MS)             /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
#define SLAVE_LATENCY                   0                                           /**< Slave latency. */
#define CONN_SUP_TIMEOUT                MSEC_TO_UNITS(4000, UNIT_10_MS)             /**< Connection supervisory timeout (4 seconds), Supervision Timeout uses 10 ms units. */
#define FIRST_CONN_PARAMS_UPDATE_DELAY  APP_TIMER_TICKS(5000)                       /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY   APP_TIMER_TICKS(30000)                      /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT    3                                           /**< Number of attempts before giving up the connection parameter negotiation. */


#define DEAD_BEEF                       0xDEADBEEF                                  /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */




#define MAX_ITERATIONS_NEEDED_FOR_NEXT_BYTE ((5000 + 2 * UART_POLL_CYCLE) / UART_POLL_CYCLE)


#define MAX_TEST_DATA_BYTES     (15U)                /**< max number of test bytes to be used for tx and rx. */
#define UART_TX_BUF_SIZE                256*4                                         /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE                256                                         /**< UART RX buffer size. */


#define BUTTON_DETECTION_DELAY          APP_TIMER_TICKS(50)


#define  NORMAL_MODE     1
#define  DTM_MODE        0




BLE_NUS_DEF(m_nus);                                                                 /**< BLE NUS service instance. */
NRF_BLE_GATT_DEF(m_gatt);                                                           /**< GATT module instance. */
BLE_ADVERTISING_DEF(m_advertising);                                                 /**< Advertising module instance. */


static uint16_t   m_conn_handle          = BLE_CONN_HANDLE_INVALID;                 /**< Handle of the current connection. */
static 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. */




//static ble_uuid_t m_adv_uuids[]          =                                          /**< Universally unique service identifier. */
//{
//    {BLE_UUID_NUS_SERVICE, NUS_SERVICE_UUID_TYPE}
//};




/**@brief Function for assert macro callback.
 *
 * @details This function will be called in case of an assert in the SoftDevice.
 *
 * @warning This handler is an example only and does not fit a final product. You need to analyse
 *          how your product is supposed to react in case of Assert.
 * @warning On assert from the SoftDevice, the system can only recover on reset.
 *
 * @param[in] line_num    Line number of the failing ASSERT call.
 * @param[in] p_file_name File name of the failing ASSERT call.
 */
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
{
    app_error_handler(DEAD_BEEF, line_num, p_file_name);
}




/**@brief Function for the GAP initialization.
 *
 * @details This function will set up all the necessary GAP (Generic Access Profile) parameters of
 *          the device. It also sets the permissions and appearance.
 */
static void gap_params_init(void)
{
    uint32_t                err_code;
    ble_gap_conn_params_t   gap_conn_params;
    ble_gap_conn_sec_mode_t sec_mode;


    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);


    err_code = sd_ble_gap_device_name_set(&sec_mode,
                                          (const uint8_t *) DEVICE_NAME,
                                          strlen(DEVICE_NAME));
    APP_ERROR_CHECK(err_code);


    memset(&gap_conn_params, 0, sizeof(gap_conn_params));


    gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = CONN_SUP_TIMEOUT;


    err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
    APP_ERROR_CHECK(err_code);
}




/**@brief Function for handling the data from the Nordic UART Service.
 *
 * @details This function will process the data received from the Nordic UART BLE Service and send
 *          it to the UART module.
 *
 * @param[in] p_nus    Nordic UART Service structure.
 * @param[in] p_data   Data to be send to UART module.
 * @param[in] length   Length of the data.
 */
/**@snippet [Handling the data received over BLE] */


/**@snippet [Handling the data received over BLE] */




/**@brief Function for initializing services that will be used by the application.
 */




/**@brief Function for handling an event from the Connection Parameters Module.
 *
 * @details This function will be called for all events in the Connection Parameters Module
 *          which are passed to the application.
 *
 * @note All this function does is to disconnect. This could have been done by simply setting
 *       the disconnect_on_fail config parameter, but instead we use the event handler
 *       mechanism to demonstrate its use.
 *
 * @param[in] p_evt  Event received from the Connection Parameters Module.
 */
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
    uint32_t err_code;


    if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
    {
        err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
        APP_ERROR_CHECK(err_code);
    }
}




/**@brief Function for handling errors from the Connection Parameters module.
 *
 * @param[in] nrf_error  Error code containing information about what went wrong.
 */
static void conn_params_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}




/**@brief Function for initializing the Connection Parameters module.
 */
static void conn_params_init(void)
{
    uint32_t               err_code;
    ble_conn_params_init_t cp_init;


    memset(&cp_init, 0, sizeof(cp_init));


    cp_init.p_conn_params                  = NULL;
    cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
    cp_init.next_conn_params_update_delay  = NEXT_CONN_PARAMS_UPDATE_DELAY;
    cp_init.max_conn_params_update_count   = MAX_CONN_PARAMS_UPDATE_COUNT;
    cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
    cp_init.disconnect_on_fail             = false;
    cp_init.evt_handler                    = on_conn_params_evt;
    cp_init.error_handler                  = conn_params_error_handler;


    err_code = ble_conn_params_init(&cp_init);
    APP_ERROR_CHECK(err_code);
}




/**@brief Function for putting the chip into sleep mode.
 *
 * @note This function will not return.
 */
#if  0
static void sleep_mode_enter(void)
{
    uint32_t err_code = bsp_indication_set(BSP_INDICATE_IDLE);
    APP_ERROR_CHECK(err_code);


    // Prepare wakeup buttons.
    err_code = bsp_btn_ble_sleep_mode_prepare();
    APP_ERROR_CHECK(err_code);


    // Go to system-off mode (this function will not return; wakeup will cause a reset).
    err_code = sd_power_system_off();
    APP_ERROR_CHECK(err_code);
}
#endif




/**@brief Function for handling advertising events.
 *
 * @details This function will be called for advertising events which are passed to the application.
 *
 * @param[in] ble_adv_evt  Advertising event.
 */
#if  0
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
    uint32_t err_code;


    switch (ble_adv_evt)
    {
        case BLE_ADV_EVT_FAST:
//            err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
//            APP_ERROR_CHECK(err_code);
            break;
        case BLE_ADV_EVT_IDLE:
//            sleep_mode_enter();
            break;
        default:
            break;
    }
}
#endif


/**@brief Function for handling BLE events.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 * @param[in]   p_context   Unused.
 */
static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
{
    uint32_t err_code;


    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            NRF_LOG_INFO("Connected");
//            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
//            APP_ERROR_CHECK(err_code);
   IsDevConnect = 1;
            m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
   Tx_Rx_Nux.conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
   UserConnectOnEvt();
            break;


        case BLE_GAP_EVT_DISCONNECTED:
            NRF_LOG_INFO("Disconnected");
            // LED indication will be changed when advertising starts.
   IsDevConnect = 0;
            m_conn_handle = BLE_CONN_HANDLE_INVALID;
   Tx_Rx_Nux.conn_handle = BLE_CONN_HANDLE_INVALID;
   CurDisconPend = 1;
   UserDisconnectEvt();


            break;


#ifndef S140
        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {
            NRF_LOG_DEBUG("PHY update request.");
            ble_gap_phys_t const phys =
            {
                .rx_phys = BLE_GAP_PHY_AUTO,
                .tx_phys = BLE_GAP_PHY_AUTO,
            };
            err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
            APP_ERROR_CHECK(err_code);
        } break;
#endif


        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
            // Pairing not supported
            err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
            APP_ERROR_CHECK(err_code);
            break;
#if !defined (S112)
         case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
        {
            ble_gap_data_length_params_t dl_params;


            // Clearing the struct will effectivly set members to @ref BLE_GAP_DATA_LENGTH_AUTO
            memset(&dl_params, 0, sizeof(ble_gap_data_length_params_t));
            err_code = sd_ble_gap_data_length_update(p_ble_evt->evt.gap_evt.conn_handle, &dl_params, NULL);
            APP_ERROR_CHECK(err_code);
        } break;
#endif //!defined (S112)
        case BLE_GATTS_EVT_SYS_ATTR_MISSING:
            // No system attributes have been stored.
            err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
            APP_ERROR_CHECK(err_code);
            break;


        case BLE_GATTC_EVT_TIMEOUT:
            // Disconnect on GATT Client timeout event.
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
            break;


        case BLE_GATTS_EVT_TIMEOUT:
            // Disconnect on GATT Server timeout event.
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
            break;


        case BLE_EVT_USER_MEM_REQUEST:
            err_code = sd_ble_user_mem_reply(p_ble_evt->evt.gattc_evt.conn_handle, NULL);
            APP_ERROR_CHECK(err_code);
            break;


        case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
        {
            ble_gatts_evt_rw_authorize_request_t  req;
            ble_gatts_rw_authorize_reply_params_t auth_reply;


            req = p_ble_evt->evt.gatts_evt.params.authorize_request;


            if (req.type != BLE_GATTS_AUTHORIZE_TYPE_INVALID)
            {
                if ((req.request.write.op == BLE_GATTS_OP_PREP_WRITE_REQ)     ||
                    (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) ||
                    (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL))
                {
                    if (req.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE)
                    {
                        auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_WRITE;
                    }
                    else
                    {
                        auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_READ;
                    }
                    auth_reply.params.write.gatt_status = APP_FEATURE_NOT_SUPPORTED;
                    err_code = sd_ble_gatts_rw_authorize_reply(p_ble_evt->evt.gatts_evt.conn_handle,
                                                               &auth_reply);
                    APP_ERROR_CHECK(err_code);
                }
            }
        } break; // BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST


        default:
            // No implementation needed.
            break;
    }
}




/**@brief Function for the SoftDevice initialization.
 *
 * @details This function initializes the SoftDevice and the BLE event interrupt.
 */


static void ble_stack_init(void)
{
    ret_code_t err_code;


    err_code = nrf_sdh_enable_request();
    APP_ERROR_CHECK(err_code);


    // Configure the BLE stack using the default settings.
    // Fetch the start address of the application RAM.
    uint32_t ram_start = 0;
    err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
    APP_ERROR_CHECK(err_code);


    // Enable BLE stack.
    err_code = nrf_sdh_ble_enable(&ram_start);
    APP_ERROR_CHECK(err_code);


    // Register a handler for BLE events.
    NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
}








/**@brief Function for handling events from the GATT library. */
void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
{
    if ((m_conn_handle == p_evt->conn_handle) && (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED))
    {
        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
        NRF_LOG_INFO("Data len is set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
    }
    NRF_LOG_DEBUG("ATT MTU exchange completed. central 0x%x peripheral 0x%x",
                  p_gatt->att_mtu_desired_central,
                  p_gatt->att_mtu_desired_periph);
}




/**@brief Function for initializing the GATT library. */
void gatt_init(void)
{
    ret_code_t err_code;


    err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
    APP_ERROR_CHECK(err_code);


    err_code = nrf_ble_gatt_att_mtu_periph_set(&m_gatt, 23);
    APP_ERROR_CHECK(err_code);
}




/**@brief Function for handling events from the BSP module.
 *
 * @param[in]   event   Event generated by button press.
 */
#if  0
void bsp_event_handler(bsp_event_t event)
{
    uint32_t err_code;
    switch (event)
    {
        case BSP_EVENT_SLEEP:
            sleep_mode_enter();
            break;


        case BSP_EVENT_DISCONNECT:
            err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            if (err_code != NRF_ERROR_INVALID_STATE)
            {
                APP_ERROR_CHECK(err_code);
            }
            break;


        case BSP_EVENT_WHITELIST_OFF:
            if (m_conn_handle == BLE_CONN_HANDLE_INVALID)
            {
                err_code = ble_advertising_restart_without_whitelist(&m_advertising);
                if (err_code != NRF_ERROR_INVALID_STATE)
                {
                    APP_ERROR_CHECK(err_code);
                }
            }
            break;


        default:
            break;
    }
}
#endif
#include "dr_lock_cmd.h"
#include "nrf_delay.h"




void ble_send_data(uint8_t *buf, uint8_t len)
{
   uint32_t       err_code;
   uint16_t send_lenth;

send_lenth = len;
   err_code = ble_nus_string_send(&m_nus, buf, &send_lenth);
   if ( (err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_ERROR_BUSY) )
   {
       APP_ERROR_CHECK(err_code);
   }
}


void send_data_to_boad(uint8_t *buf, uint8_t len)
{
   uint32_t err_code;
   app_uart_put(0);
   app_uart_put(0);
   app_uart_put(0);


nrf_delay_ms(15);
   app_uart_put(0xff);
nrf_delay_ms(150);


   for (uint32_t i = 0; i < len; i++)
   {
       do
       {
          err_code = app_uart_put(buf[i]);
          if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_BUSY))
          {
              NRF_LOG_ERROR("Failed receiving NUS message. Error 0x%x. ", err_code);
              APP_ERROR_CHECK(err_code);
          }
        } while (err_code == NRF_ERROR_BUSY);
   }
}


static void nus_data_handler(ble_nus_evt_t * p_evt)
{
// uint8_t i = 0x00;


    if (p_evt->type == BLE_NUS_EVT_RX_DATA)
    {
        
        
// NRF_LOG_DEBUG("Received data from BLE NUS. Writing data on UART.");

// NRF_LOG_INFO("rx_data: %x" ,p_evt->params.rx_data.p_data[0]);
//for(i = 0; i <p_evt->params.rx_data.length; i++)
// {NRF_LOG_DEBUG("%x", p_evt->params.rx_data.p_data[i]);}
   // NRF_LOG_INFO("\r\n");



    //    NRF_LOG_HEXDUMP_DEBUG(p_evt->params.rx_data.p_data, p_evt->params.rx_data.length);


        if(p_evt->params.rx_data.p_data[0] == 0xf5)
  send_data_to_boad((uint8_t *)p_evt->params.rx_data.p_data,p_evt->params.rx_data.length);
        else
{
SocketCommandDispatch();
//  DorLockCommandDispatch();
}
    }


}


void uart_event_handle(app_uart_evt_t * p_event)
{


    switch (p_event->evt_type)
    {
        case APP_UART_DATA_READY:
 uart_recv();


            break;


        case APP_UART_COMMUNICATION_ERROR:
            //APP_ERROR_HANDLER(p_event->data.error_communication);
            break;


        case APP_UART_FIFO_ERROR:
            //APP_ERROR_HANDLER(p_event->data.error_code);
            break;


        default:
            break;
    }
}




static void services_init(void)
{
    uint32_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);

 Tx_Rx_Nux = m_nus;
 
    APP_ERROR_CHECK(err_code);
}




/**@snippet [Handling the data received over UART] */


#if   0
uint8  GetWorkMode(void)
{
uint8 ModeAck;


#if  MODE_ACTIVE_LEVEL
 if(nrf_gpio_pin_read(IO_MODE_TEST))
{
ModeAck = NORMAL_MODE;
}
else
{
ModeAck = DTM_MODE;
}
#else
if(nrf_gpio_pin_read(IO_MODE_TEST))
{
ModeAck = DTM_MODE;
}
else
{
ModeAck = NORMAL_MODE;
}
#endif

return ModeAck;
}
#endif


// Error handler for UART
void uart_error_handle(app_uart_evt_t * p_event)
{
    if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_communication);
    }
    else if (p_event->evt_type == APP_UART_FIFO_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_code);
    }
}




/**@brief  Function for initializing the UART module.
 */
/**@snippet [UART Initialization] */
#if  1
static void uart_init(void)
{
    uint32_t                     err_code;
    app_uart_comm_params_t const comm_params =
    {
#if  0
        .rx_pin_no    = RX_PIN_NUMBER1,
        .tx_pin_no    = TX_PIN_NUMBER1,
#else
 .rx_pin_no    = RX_PIN_NUMBER,
        .tx_pin_no    = TX_PIN_NUMBER,
      #endif
        .rts_pin_no   = RTS_PIN_NUMBER,
        .cts_pin_no   = CTS_PIN_NUMBER,
        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
        .use_parity   = false,
        .baud_rate    = NRF_UART_BAUDRATE_9600
    };
#if  0
if(GetWorkMode() == NORMAL_MODE)
#endif
{
APP_UART_FIFO_INIT(&comm_params,
UART_RX_BUF_SIZE,
UART_TX_BUF_SIZE,
uart_event_handle,
APP_IRQ_PRIORITY_LOWEST,
err_code);
}
#if  0
else
{
APP_UART_FIFO_INIT(&comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_error_handle,
                       APP_IRQ_PRIORITY_LOWEST,
                       err_code);
}
#endif
    APP_ERROR_CHECK(err_code);
}
#endif
/**@snippet [UART Initialization] */




static void advertising_init(void)
{
ret_code_t    err_code;
 ble_gap_addr_t device_addr;
 uint8 i;
//  InitAdvData();
 err_code = sd_ble_gap_addr_get(&device_addr);
 APP_ERROR_CHECK(err_code);
 
 for(i=0; i< BLE_GAP_ADDR_LEN; i++)
 {
advertData[14-i] = device_addr.addr[i];
}

// advertData[22] = (IsPassWordModify()) ? 1:0;
#if 1
if(IsPassWordModify())
{
advertData[22] = 1;
}
else
{
advertData[22] = 0;
}
#endif
 uint16 sk_scrp_length = sizeof(deviceName);
 err_code = sd_ble_gap_adv_data_set(advertData, sk_adv_length, deviceName, sk_scrp_length);
 APP_ERROR_CHECK(err_code);


}


/**@brief Function for initializing the Advertising functionality.
 */










/**@brief Function for initializing buttons and leds.
 *
 * @param[out] p_erase_bonds  Will be true if the clear bonding button was pressed to wake the application up.
 */
#if  0
static void buttons_leds_init(bool * p_erase_bonds)
{
    bsp_event_t startup_event;


    uint32_t err_code = bsp_init(BSP_INIT_LED | BSP_INIT_BUTTONS, bsp_event_handler);
    APP_ERROR_CHECK(err_code);


    err_code = bsp_btn_ble_init(NULL, &startup_event);
    APP_ERROR_CHECK(err_code);


    *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
}
#endif




/**@brief Function for initializing the nrf log module.
 */
static void log_init(void)
{
    ret_code_t err_code = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(err_code);


    NRF_LOG_DEFAULT_BACKENDS_INIT();
}




/**@brief Function for placing the application in low power state while waiting for events.
 */
#if  1
static void power_manage(void)
{
    uint32_t err_code = sd_app_evt_wait();
    APP_ERROR_CHECK(err_code);
}
#endif


static void leds_init(void)
{
   nrf_gpio_cfg_output(IO_LED_CTRL);
BSP_LED_CLR(IO_LED_CTRL)
}


static void  relay_init(void)
{
nrf_gpio_cfg_output(IO_RELAY_CTRL);
BSP_RELAY_CLR(IO_RELAY_CTRL)
}




static void timers_init(void)
{
uint32_t err_code;
err_code = app_timer_init();
   APP_ERROR_CHECK(err_code);
}




static void button_event_handler(uint8_t pin_no, uint8_t button_action)
{
// ret_code_t err_code;


 if(button_action != APP_BUTTON_PUSH)
{
//  SocketTaskAction(FACTORY_SET, 200);
 return;
}

SocketTaskAction(FACTORY_SET, 200);
    
switch (pin_no)
    {
        case IO_KEY_CTRL:
           
             if(Sockets.Status == 0)
            {
                if(Tx_Rx_Nux.conn_handle != BLE_CONN_HANDLE_INVALID)
                {
//                    Util_stopClock(&LedFlashClock);
//    err_code = app_timer_stop(LedFlashClock);
//    APP_ERROR_CHECK(err_code);
   SocketTaskStop(LED_FLASH);
                }
                SwitchOn();
                Sockets.Status = 1;
            }
            else
            {
                if(Tx_Rx_Nux.conn_handle != BLE_CONN_HANDLE_INVALID)
                {}
                else
                {
// Util_restartClock(&LedFlashClock,100);
//    err_code = app_timer_start(LedFlashClock, APP_TIMER_TICKS(100), NULL);
//    APP_ERROR_CHECK(err_code);
   SocketTaskAction(LED_FLASH, 100);
}
                
                SwitchOff();
                Sockets.Status = 0;
            }
            
            if(Tx_Rx_Nux.conn_handle != BLE_CONN_HANDLE_INVALID)
            {
 APP_SendData[0] = BLE_CMD_SWITCH;
                APP_SendData[1] = 1;
                APP_SendData[2] = Sockets.Status;
 APP_SendData[3] = SWITCH_ACTION_TRIGGER_TYPE_DEVICE_TOUCH;
 //               ProxReporter_SetParameter(PROXIMITY_SEND_DATA,sizeof(APP_SendData),APP_SendData);
 ProxReporter_SetParameter(&Tx_Rx_Nux, APP_SendData, &SocketReplyLength); 
            }
            UpdateAdvData();
            break;


        default:
            APP_ERROR_HANDLER(pin_no);
            break;
    }
}


/**@brief Function for initializing the button handler module.
 */
static void buttons_init(void)
{
    ret_code_t err_code;


    //The array must be static because a pointer to it will be saved in the button handler module.
    static app_button_cfg_t buttons[] =
    {
        {IO_KEY_CTRL, APP_BUTTON_ACTIVE_LOW, BUTTON_PULL, button_event_handler}
//    {IO_KEY_CTRL, APP_BUTTON_PUSH, BUTTON_PULL, button_event_handler}
    };


    err_code = app_button_init(buttons, sizeof(buttons) / sizeof(buttons[0]),
                               BUTTON_DETECTION_DELAY);
    APP_ERROR_CHECK(err_code);

err_code = app_button_enable();
    APP_ERROR_CHECK(err_code);
}




#define  SOCKET_INIT_EN            1
#define  DEVICE_NAME_INIT_EN       1
#define  RTC_TIME_INIT_EN          1
#define  MAC_DATA_INIT_EN          1
#define  PM_INIT_EN                1
#define  PM0_INIT_EN               1
#define  MF_INIT_EN 1
#define  MF0_INIT_EN 1
#define  POWER_CNT_INIT_EN         1


void  socket_information_init(void)
{
 
#if DEVICE_NAME_INIT_EN
 device_name_flash_init();
 for(uint8 i = 0; i < GAP_DEVICE_NAME_LEN; i++)
{
attDeviceName[i] = deviceName[i+2];
}
#endif
#if RTC_TIME_INIT_EN
rtc_time_flash_init();
#endif
#if MAC_DATA_INIT_EN
mac_data_flash_init();
if( (STORE_MAC_DATA[PHONE_FLAG] & 0x80) == 0)//ÃÜÂëδÐ޸Ĺý
    {
        uint8 i=0;
for(i=0;i<6;i++)
{
STORE_MAC_DATA[PHONE_PASSWORD+i]=48+i+1;//³õʼÃÜÂë'123456'
}
    }
#endif
#if PM_INIT_EN
phone_mac_flash_init();
#endif
#if PM0_INIT_EN
phone_mac0_flash_init();
#endif
#if MF_INIT_EN
mac_flag_flash_init();
#endif
#if MF0_INIT_EN
mac_flag0_flash_init();
#endif
#if POWER_CNT_INIT_EN
power_on_cnt_flash_init();
#endif
#if SOCKET_INIT_EN
sockets_flash_init();
 #endif

UserMgrPowerOnInit();
SystemUserMgrConfig();
}




void  flash_init(void)
{
 ret_code_t err_code;
err_code = socket_flash_on_init();
   APP_ERROR_CHECK(err_code);
}








void  SocketEvtStart(void)
{
//  uint32_t err_code;
// err_code = app_timer_start(LedFlashClock, APP_TIMER_TICKS(100), NULL);
//  APP_ERROR_CHECK(err_code);
 
//  err_code = app_timer_start(RtcTimerClock, APP_TIMER_TICKS(100), NULL);
//  APP_ERROR_CHECK(err_code);
//    LedFlashAction(100);
   SocketTaskAction(LED_FLASH, 2000);

#if  defined(SECOND_COUNT_DOWN)
   SocketTaskAction(TIMER_DOWN_CNT, 1000);
#elif defined(MINUTE_COUNT_DOWN)
SocketTaskAction(TIMER_DOWN_CNT, 60000);
#endif
}




/**@snippet [UART Initialization] */


/**@brief Function for splitting UART command bit fields into separate command parameters for the DTM library.
 *
 * @param[in]   command   The packed UART command.
 * @return      result status from dtmlib.
 */
#if  0
static uint32_t dtm_cmd_put(uint16_t command)
{
    dtm_cmd_t      command_code = (command >> 14) & 0x03;
    dtm_freq_t     freq         = (command >> 8) & 0x3F;
    uint32_t       length       = (command >> 2) & 0x3F;
    dtm_pkt_type_t payload      = command & 0x03;


    return dtm_cmd(command_code, freq, length, payload);
}
#endif


#if  0
void  test_pin_init(void)
{
nrf_gpio_cfg_input(IO_MODE_TEST, NRF_GPIO_PIN_PULLUP);
}
#endif


#if  0
void  DtmHandler(void)
{
uint32_t    current_time;
    uint32_t    dtm_error_code;
    uint32_t    msb_time          = 0;     // Time when MSB of the DTM command was read. Used to catch stray bytes from "misbehaving" testers.
    bool        is_msb_read       = false; // True when MSB of the DTM command has been read and the application is waiting for LSB.
    uint16_t    dtm_cmd_from_uart = 0;     // Packed command containing command_code:freqency:length:payload in 2:6:6:2 bits.
    uint8_t     rx_byte;                   // Last byte read from UART.
    dtm_event_t result;                    // Result of a DTM operation.


    bsp_board_leds_init();
    
    uart_init();
 printf("DTM BOOTING");


    dtm_error_code = dtm_init();
    if (dtm_error_code != DTM_SUCCESS)
    {
        // If DTM cannot be correctly initialized, then we just return.
//        return -1;
 APP_ERROR_CHECK(dtm_error_code);
    }


    for (;;)
    {
 if(GetWorkMode() == NORMAL_MODE)
{
(void)sd_nvic_SystemReset();
}
        // Will return every timeout, 625 us.
        current_time = dtm_wait();


        if (app_uart_get(&rx_byte) != NRF_SUCCESS)
        {
            // Nothing read from the UART.
            continue;
        }


        if (!is_msb_read)
        {
            // This is first byte of two-byte command.
            is_msb_read       = true;
            dtm_cmd_from_uart = ((dtm_cmd_t)rx_byte) << 8;
            msb_time          = current_time;


            // Go back and wait for 2nd byte of command word.
            continue;
        }


        // This is the second byte read; combine it with the first and process command
        if (current_time > (msb_time + MAX_ITERATIONS_NEEDED_FOR_NEXT_BYTE))
        {
            // More than ~5mS after msb: Drop old byte, take the new byte as MSB.
            // The variable is_msb_read will remains true.
            // Go back and wait for 2nd byte of the command word.
            dtm_cmd_from_uart = ((dtm_cmd_t)rx_byte) << 8;
            msb_time          = current_time;
            continue;
        }


        // 2-byte UART command received.
        is_msb_read        = false;
        dtm_cmd_from_uart |= (dtm_cmd_t)rx_byte;


        if (dtm_cmd_put(dtm_cmd_from_uart) != DTM_SUCCESS)
        {
            // Extended error handling may be put here.
            // Default behavior is to return the event on the UART (see below);
            // the event report will reflect any lack of success.
        }


        // Retrieve result of the operation. This implementation will busy-loop
        // for the duration of the byte transmissions on the UART.
        if (dtm_event_get(&result))
        {
            // Report command status on the UART.
            // Transmit MSB of the result.
            while (app_uart_put((result >> 8) & 0xFF));
            // Transmit LSB of the result.
            while (app_uart_put(result & 0xFF));
        }
    }
}
#endif


void SocketOnPowerAction(void)
{
if(Sockets.PowerActionType)
{
SwitchOn();
 Sockets.Status = 1;
}
else
{
SwitchOff();
 Sockets.Status = 0;
}
}




void DorLockEvtCreate(void)
{
CreatCipherMgrEvt();
 CreatNorUserCipherEvt();
 CreatUartCmdRspMgrEvt();
 CreatUartCmdTestEvt();
 CreatAddCipherTestEvt();
 CreatDelCipherTestEvt();
}




/**@brief Application main function.
 */
int main(void)
{
//uint8_t data_buf[100];
//  pm_store_token_t token;
//    pm_peer_data_flash_t peer_data;
#if  0
 test_pin_init();
 if(GetWorkMode() == DTM_MODE)
{
DtmHandler();
}
else if(GetWorkMode() == NORMAL_MODE)
#endif
{
timers_init();
sk_event_create();
 DorLockEvtCreate();
     leds_init();
relay_init();
     buttons_init();
log_init();
ble_stack_init();
gap_params_init();
gatt_init();
services_init();
 system_clock_init();
        wdt_init();
flash_init();
socket_information_init();
advertising_init();
conn_params_init();
advertising_start();
//      AppBonding_Init();
Accumulative_PowerOn();
 SocketOnPowerAction();
SocketEvtStart();
uart_init();
// printf("\r\nSmart Socket Booting!\r\n");
APP_SCHED_INIT(APP_SCHED_MAX_EVENT_SIZE, APP_SCHED_QUEUE_SIZE);
NRF_LOG_INFO("lock  exe start");
// Enter main loop.
for (;;)
{
app_sched_execute();
 NRF_LOG_PROCESS();
 wdt_feed();
//            power_manage();
}
}
}




/**
 * @}

 */


/**
 * Copyright (c) 2012 - 2017, Nordic Semiconductor ASA
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 * 
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 * 
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 * 
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 * 
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */
#include "sdk_common.h"
#if NRF_MODULE_ENABLED(BLE_NUS)
#include "ble.h"
#include "ble_nus.h"


#include "ble_srv_common.h"
#include "nrf_log.h"








#define BLE_UUID_NUS_TX_CHARACTERISTIC 0xFFF2                      /**< The UUID of the TX Characteristic. */
#define BLE_UUID_NUS_RX_CHARACTERISTIC 0xFFF1                      /**< The UUID of the RX Characteristic. */
//#define BLE_UUID_NUS_TX_CHARACTERISTIC 0x0003                      /**< The UUID of the TX Characteristic. */
//#define BLE_UUID_NUS_RX_CHARACTERISTIC 0x0002                      /**< The UUID of the RX Characteristic. */


#define BLE_NUS_MAX_RX_CHAR_LEN        BLE_NUS_MAX_DATA_LEN        /**< Maximum length of the RX Characteristic (in bytes). */
#define BLE_NUS_MAX_TX_CHAR_LEN        BLE_NUS_MAX_DATA_LEN        /**< Maximum length of the TX Characteristic (in bytes). */


//#define NUS_BASE_UUID                  {{0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0x00, 0x00, 0x40, 0x6E}} /**< Used vendor specific UUID. */


#define NUS_BASE_UUID                  {{0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}} 
//#define NUS_BASE_UUID                  {{0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0x00, 0x00, 0x40, 0x6E}} /**< Used vendor specific UUID. */


//0000fff0-0000-1000-8000-00805f9b34fb


uint8_t APP_ReceiveData[20] = {0};
uint8_t APP_SendData[20] = {0};
uint16_t SocketReplyLength = sizeof(APP_SendData)/sizeof(APP_SendData[0]);


ble_nus_t  Tx_Rx_Nux; 




/**@brief Function for handling the @ref BLE_GAP_EVT_CONNECTED event from the SoftDevice.
 *
 * @param[in] p_nus     Nordic UART Service structure.
 * @param[in] p_ble_evt Pointer to the event received from BLE stack.
 */
static void on_connect(ble_nus_t * p_nus, ble_evt_t const * p_ble_evt)
{
    p_nus->conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
 Tx_Rx_Nux.conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
}




/**@brief Function for handling the @ref BLE_GAP_EVT_DISCONNECTED event from the SoftDevice.
 *
 * @param[in] p_nus     Nordic UART Service structure.
 * @param[in] p_ble_evt Pointer to the event received from BLE stack.
 */
static void on_disconnect(ble_nus_t * p_nus, ble_evt_t const * p_ble_evt)
{
    UNUSED_PARAMETER(p_ble_evt);
    p_nus->conn_handle = BLE_CONN_HANDLE_INVALID;
 Tx_Rx_Nux.conn_handle = BLE_CONN_HANDLE_INVALID;
}




/**@brief Function for handling the @ref BLE_GATTS_EVT_WRITE event from the SoftDevice.
 *
 * @param[in] p_nus     Nordic UART Service structure.
 * @param[in] p_ble_evt Pointer to the event received from BLE stack.
 */
static void on_write(ble_nus_t * p_nus, ble_evt_t const * p_ble_evt)
{
//  uint16_t  i;
 //NRF_LOG_INFO("on_write\r\n");
    ble_gatts_evt_write_t const * p_evt_write = &p_ble_evt->evt.gatts_evt.params.write;
    ble_nus_evt_t evt;
    evt.p_nus = p_nus;




if (   (p_evt_write->handle == p_nus->tx_handles.cccd_handle)
        && (p_evt_write->len == 2))
    {
        if (ble_srv_is_notification_enabled(p_evt_write->data))
        {
            p_nus->is_notification_enabled = true;
 Tx_Rx_Nux.is_notification_enabled  = true;
 evt.type = BLE_NUS_EVT_COMM_STARTED;
        }
        else
        {
            p_nus->is_notification_enabled = false;
 Tx_Rx_Nux.is_notification_enabled = false;
            evt.type = BLE_NUS_EVT_COMM_STOPPED;
        }
        p_nus->data_handler(&evt);
    }
    else if (   (p_evt_write->handle == p_nus->rx_handles.value_handle)
             && (p_nus->data_handler != NULL))
    {
        evt.params.rx_data.p_data = p_evt_write->data;
        evt.params.rx_data.length = p_evt_write->len;
        evt.type = BLE_NUS_EVT_RX_DATA;
//NRF_LOG_INFO("rx_data:");
//for(i = 0; i <evt.params.rx_data.length; i++)
// {NRF_LOG_DEBUG("%x", evt.params.rx_data.p_data[i]);}
//NRF_LOG_INFO("\r\n");

memset(APP_ReceiveData,0,sizeof(APP_ReceiveData));
if(p_evt_write->len<=sizeof(APP_ReceiveData))
{
memcpy(APP_ReceiveData, p_evt_write->data, sizeof(APP_ReceiveData));
}
else
{
return ;
}
 p_nus->data_handler(&evt);
    }
    else
    {
        // Do Nothing. This event is not relevant for this service.
    }
}




/**@brief Function for adding TX characteristic.
 *
 * @param[in] p_nus       Nordic UART Service structure.
 * @param[in] p_nus_init  Information needed to initialize the service.
 *
 * @return NRF_SUCCESS on success, otherwise an error code.
 */
static uint32_t tx_char_add(ble_nus_t * p_nus, ble_nus_init_t const * p_nus_init)
{
    /**@snippet [Adding proprietary characteristic to the SoftDevice] */
    ble_gatts_char_md_t char_md;
    ble_gatts_attr_md_t cccd_md;
    ble_gatts_attr_t    attr_char_value;
    ble_uuid_t          ble_uuid;
    ble_gatts_attr_md_t attr_md;


    memset(&cccd_md, 0, sizeof(cccd_md));


    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm);


    cccd_md.vloc = BLE_GATTS_VLOC_STACK;


    memset(&char_md, 0, sizeof(char_md));


    char_md.char_props.notify = 1;
    char_md.p_char_user_desc  = NULL;
    char_md.p_char_pf         = NULL;
    char_md.p_user_desc_md    = NULL;
    char_md.p_cccd_md         = &cccd_md;
    char_md.p_sccd_md         = NULL;


    ble_uuid.type = p_nus->uuid_type;
    ble_uuid.uuid = BLE_UUID_NUS_TX_CHARACTERISTIC;


    memset(&attr_md, 0, sizeof(attr_md));


    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);


    attr_md.vloc    = BLE_GATTS_VLOC_STACK;
    attr_md.rd_auth = 0;
    attr_md.wr_auth = 0;
    attr_md.vlen    = 1;


    memset(&attr_char_value, 0, sizeof(attr_char_value));


    attr_char_value.p_uuid    = &ble_uuid;
    attr_char_value.p_attr_md = &attr_md;
    attr_char_value.init_len  = sizeof(uint8_t);
    attr_char_value.init_offs = 0;
    attr_char_value.max_len   = BLE_NUS_MAX_TX_CHAR_LEN;


    return sd_ble_gatts_characteristic_add(p_nus->service_handle,
                                           &char_md,
                                           &attr_char_value,
                                           &p_nus->tx_handles);
    /**@snippet [Adding proprietary characteristic to the SoftDevice] */
}




/**@brief Function for adding RX characteristic.
 *
 * @param[in] p_nus       Nordic UART Service structure.
 * @param[in] p_nus_init  Information needed to initialize the service.
 *
 * @return NRF_SUCCESS on success, otherwise an error code.
 */
static uint32_t rx_char_add(ble_nus_t * p_nus, const ble_nus_init_t * p_nus_init)
{
    ble_gatts_char_md_t char_md;
    ble_gatts_attr_t    attr_char_value;
    ble_uuid_t          ble_uuid;
    ble_gatts_attr_md_t attr_md;


    memset(&char_md, 0, sizeof(char_md));


    char_md.char_props.write         = 1;
    char_md.char_props.write_wo_resp = 1;
    char_md.p_char_user_desc         = NULL;
    char_md.p_char_pf                = NULL;
    char_md.p_user_desc_md           = NULL;
    char_md.p_cccd_md                = NULL;
    char_md.p_sccd_md                = NULL;


    ble_uuid.type = p_nus->uuid_type;
    ble_uuid.uuid = BLE_UUID_NUS_RX_CHARACTERISTIC;


    memset(&attr_md, 0, sizeof(attr_md));

//  char_md.char_props.read  = 1;     //¼ÓÉÏÈ¥µÄ
//        BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);


    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);


    attr_md.vloc    = BLE_GATTS_VLOC_STACK;
    attr_md.rd_auth = 0;
    attr_md.wr_auth = 0;
    attr_md.vlen    = 1;


    memset(&attr_char_value, 0, sizeof(attr_char_value));


    attr_char_value.p_uuid    = &ble_uuid;
    attr_char_value.p_attr_md = &attr_md;
    attr_char_value.init_len  = 1;
    attr_char_value.init_offs = 0;
    attr_char_value.max_len   = BLE_NUS_MAX_RX_CHAR_LEN;


    return sd_ble_gatts_characteristic_add(p_nus->service_handle,
                                           &char_md,
                                           &attr_char_value,
                                           &p_nus->rx_handles);
}




void ble_nus_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_context)
{
// NRF_LOG_INFO("ble_nus_on_ble_evt  bb\r\n");
    if ((p_context == NULL) || (p_ble_evt == NULL))
    {
        return;
    }


    ble_nus_t * p_nus = (ble_nus_t *)p_context;
  //  NRF_LOG_INFO("ble_nus_on_ble_evt  aa\r\n");
    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
  NRF_LOG_INFO("on_connect\r\n");
            on_connect(p_nus, p_ble_evt);
            break;


        case BLE_GAP_EVT_DISCONNECTED:
 NRF_LOG_INFO("on_disconnect\r\n");
            on_disconnect(p_nus, p_ble_evt);
            break;


        case BLE_GATTS_EVT_WRITE:
            on_write(p_nus, p_ble_evt);
            break;


        case BLE_GATTS_EVT_HVN_TX_COMPLETE:
        {
            //notify with empty data that some tx was completed.
           ble_nus_evt_t evt = {
                    .type = BLE_NUS_EVT_TX_RDY,
                    .p_nus = p_nus
            };
            p_nus->data_handler(&evt);
            break;
        }
        default:
            // No implementation needed.
            break;
    }
}




uint32_t ble_nus_init(ble_nus_t * p_nus, ble_nus_init_t const * p_nus_init)
{
    uint32_t      err_code;
    ble_uuid_t    ble_uuid;
    ble_uuid128_t nus_base_uuid = NUS_BASE_UUID;


    VERIFY_PARAM_NOT_NULL(p_nus);
    VERIFY_PARAM_NOT_NULL(p_nus_init);


    // Initialize the service structure.
    p_nus->conn_handle             = BLE_CONN_HANDLE_INVALID;
    p_nus->data_handler            = p_nus_init->data_handler;
    p_nus->is_notification_enabled = false;


    /**@snippet [Adding proprietary Service to the SoftDevice] */
    // Add a custom base UUID.
    err_code = sd_ble_uuid_vs_add(&nus_base_uuid, &p_nus->uuid_type);
    VERIFY_SUCCESS(err_code);


    ble_uuid.type = p_nus->uuid_type;
    ble_uuid.uuid = BLE_UUID_NUS_SERVICE;


    // Add the service.
    err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY,
                                        &ble_uuid,
                                        &p_nus->service_handle);
    /**@snippet [Adding proprietary Service to the SoftDevice] */
    VERIFY_SUCCESS(err_code);


    // Add the RX Characteristic.
    err_code = rx_char_add(p_nus, p_nus_init);
    VERIFY_SUCCESS(err_code);


    // Add the TX Characteristic.
    err_code = tx_char_add(p_nus, p_nus_init);
    VERIFY_SUCCESS(err_code);


    return NRF_SUCCESS;
}




void  ProxReporter_SetParameter(ble_nus_t * p_nus, uint8_t * p_string, uint16_t * p_length)
{
 uint32_t       err_code;
do
    {
       err_code = ble_nus_string_send(p_nus, p_string, p_length);
  
    } while (err_code == NRF_ERROR_BUSY);


}



uint32_t ble_nus_string_send(ble_nus_t * p_nus, uint8_t * p_string, uint16_t * p_length)
{
    ble_gatts_hvx_params_t hvx_params;


    VERIFY_PARAM_NOT_NULL(p_nus);


/*
    if ((p_nus->conn_handle == BLE_CONN_HANDLE_INVALID) || (!p_nus->is_notification_enabled))
    {
        return NRF_ERROR_INVALID_STATE;
    }
*/
 if (p_nus->conn_handle == BLE_CONN_HANDLE_INVALID)
{
return NRF_ERROR_INVALID_STATE;
}


    if (*p_length > BLE_NUS_MAX_DATA_LEN)
    {
        return NRF_ERROR_INVALID_PARAM;
    }


    memset(&hvx_params, 0, sizeof(hvx_params));


    hvx_params.handle = p_nus->tx_handles.value_handle;
    hvx_params.p_data = p_string;
    hvx_params.p_len  = p_length;
    hvx_params.type   = BLE_GATT_HVX_NOTIFICATION;


    return sd_ble_gatts_hvx(p_nus->conn_handle, &hvx_params);
}


#endif // NRF_MODULE_ENABLED(BLE_NUS)


#include "nrf_drv_wdt.h"
#include "nrf_wdt.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"




static nrf_drv_wdt_channel_id m_channel_id;


static void wdt_event_handler(void)
{
  NRF_LOG_INFO("WDT TIMEOUT\r\n");     
}




void wdt_feed(void)
{
nrf_drv_wdt_channel_feed(m_channel_id);
}


void wdt_init(void)
{
uint32_t err_code = NRF_SUCCESS;
    //Configure WDT.
    nrf_drv_wdt_config_t config = NRF_DRV_WDT_DEAFULT_CONFIG;
    err_code = nrf_drv_wdt_init(&config, wdt_event_handler);
    APP_ERROR_CHECK(err_code);
    err_code = nrf_drv_wdt_channel_alloc(&m_channel_id);
    APP_ERROR_CHECK(err_code);
    nrf_drv_wdt_enable();
}


/**
 * Copyright (c) 2014 - 2017, Nordic Semiconductor ASA
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 * 
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 * 
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 * 
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 * 
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */
/** @file
 *
 * @defgroup app_error Common application error handler
 * @{
 * @ingroup app_common
 *
 * @brief Common application error handler.
 */


#include "nrf.h"
#include <stdio.h>
#include "app_error.h"
#include "nordic_common.h"
#include "sdk_errors.h"


#include "nrf_log.h"
/**@brief Function for error handling, which is called when an error has occurred.
 *
 * @warning This handler is an example only and does not fit a final product. You need to analyze
 *          how your product is supposed to react in case of error.
 *
 * @param[in] error_code  Error code supplied to the handler.
 * @param[in] line_num    Line number where the handler is called.
 * @param[in] p_file_name Pointer to the file name.
 */




#define  PRINTF_ERROR_INFO  
/*lint -save -e14 */
void app_error_handler(ret_code_t error_code, uint32_t line_num, const uint8_t * p_file_name)
{
    error_info_t error_info =
    {
        .line_num    = line_num,
        .p_file_name = p_file_name,
        .err_code    = error_code,
    };

#ifdef PRINTF_ERROR_INFO  


             NRF_LOG_ERROR("error_code: 0x%08x",error_code);


             NRF_LOG_ERROR("line_num: %d",line_num);


             NRF_LOG_ERROR("p_file_name: %s",p_file_name);


    #endif
    app_error_fault_handler(NRF_FAULT_ID_SDK_ERROR, 0, (uint32_t)(&error_info));


    UNUSED_VARIABLE(error_info);
}


/*lint -save -e14 */
void app_error_handler_bare(ret_code_t error_code)
{
    error_info_t error_info =
    {
        .line_num    = 0,
        .p_file_name = NULL,
        .err_code    = error_code,
    };


    app_error_fault_handler(NRF_FAULT_ID_SDK_ERROR, 0, (uint32_t)(&error_info));


    UNUSED_VARIABLE(error_info);
}




void app_error_save_and_stop(uint32_t id, uint32_t pc, uint32_t info)
{
    /* static error variables - in order to prevent removal by optimizers */
    static volatile struct
    {
        uint32_t        fault_id;
        uint32_t        pc;
        uint32_t        error_info;
        assert_info_t * p_assert_info;
        error_info_t  * p_error_info;
        ret_code_t      err_code;
        uint32_t        line_num;
        const uint8_t * p_file_name;
    } m_error_data = {0};


    // The following variable helps Keil keep the call stack visible, in addition, it can be set to
    // 0 in the debugger to continue executing code after the error check.
    volatile bool loop = true;
    UNUSED_VARIABLE(loop);


    m_error_data.fault_id   = id;
    m_error_data.pc         = pc;
    m_error_data.error_info = info;


    switch (id)
    {
        case NRF_FAULT_ID_SDK_ASSERT:
            m_error_data.p_assert_info = (assert_info_t *)info;
            m_error_data.line_num      = m_error_data.p_assert_info->line_num;
            m_error_data.p_file_name   = m_error_data.p_assert_info->p_file_name;
            break;


        case NRF_FAULT_ID_SDK_ERROR:
            m_error_data.p_error_info = (error_info_t *)info;
            m_error_data.err_code     = m_error_data.p_error_info->err_code;
            m_error_data.line_num     = m_error_data.p_error_info->line_num;
            m_error_data.p_file_name  = m_error_data.p_error_info->p_file_name;
            break;
    }


    UNUSED_VARIABLE(m_error_data);


    // If printing is disrupted, remove the irq calls, or set the loop variable to 0 in the debugger.
    __disable_irq();
    while (loop);


    __enable_irq();
}


/*lint -restore */

/**
 * Copyright (c) 2016 - 2017, Nordic Semiconductor ASA
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 * 
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 * 
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 * 
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 * 
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */
#include "app_error.h"


#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_strerror.h"


#if defined(SOFTDEVICE_PRESENT) && SOFTDEVICE_PRESENT
#include "nrf_sdm.h"
#endif


/*lint -save -e14 */


/**
 * Function is implemented as weak so that it can be overwritten by custom application error handler
 * when needed.
 */
// #define DEBUG
__WEAK void app_error_fault_handler(uint32_t id, uint32_t pc, uint32_t info)
{
    NRF_LOG_FINAL_FLUSH();


#ifndef DEBUG
    NRF_LOG_ERROR("Fatal  error");
#else
    switch (id)
    {
#if defined(SOFTDEVICE_PRESENT) && SOFTDEVICE_PRESENT
        case NRF_FAULT_ID_SD_ASSERT:
            NRF_LOG_ERROR("SOFTDEVICE: ASSERTION FAILED");
            break;
        case NRF_FAULT_ID_APP_MEMACC:
            NRF_LOG_ERROR("SOFTDEVICE: INVALID MEMORY ACCESS");
            break;
#endif
        case NRF_FAULT_ID_SDK_ASSERT:
        {
            assert_info_t * p_info = (assert_info_t *)info;
            NRF_LOG_ERROR("ASSERTION FAILED at %s:%u",
                          p_info->p_file_name,
                          p_info->line_num);
            break;
        }
        case NRF_FAULT_ID_SDK_ERROR:
        {
            error_info_t * p_info = (error_info_t *)info;
            NRF_LOG_ERROR("ERROR %u [%s] at %s:%u",
                          p_info->err_code,
                          nrf_strerror_get(p_info->err_code),
                          p_info->p_file_name,
                          p_info->line_num);
            break;
        }
        default:
            NRF_LOG_ERROR("UNKNOWN FAULT at 0x%08X", pc);
            break;
    }
#endif


    NRF_BREAKPOINT_COND;
    // On assert, the system can only recover with a reset.


#ifndef DEBUG
    NRF_LOG_WARNING("System reset");
    NVIC_SystemReset();
#else
    app_error_save_and_stop(id, pc, info);
#endif // DEBUG
}


/*lint -restore */


/**
 * Copyright (c) 2017 - 2017, Nordic Semiconductor ASA
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 * 
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 * 
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 * 
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 * 
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */






#ifndef SDK_CONFIG_H
#define SDK_CONFIG_H
// <<< Use Configuration Wizard in Context Menu >>>\n
#ifdef USE_APP_CONFIG
#include "app_config.h"
#endif
// <h> Board Support 


//==========================================================
// <q> BSP_BTN_BLE_ENABLED  - bsp_btn_ble - Button Control for BLE
 


#ifndef BSP_BTN_BLE_ENABLED
#define BSP_BTN_BLE_ENABLED 1
#endif


// </h> 
//==========================================================


// <h> nRF_BLE 


//==========================================================
// <q> BLE_ADVERTISING_ENABLED  - ble_advertising - Advertising module
 


#ifndef BLE_ADVERTISING_ENABLED
#define BLE_ADVERTISING_ENABLED 1
#endif


// <q> BLE_DTM_ENABLED  - ble_dtm - Module for testing RF/PHY using DTM commands
 


#ifndef BLE_DTM_ENABLED
#define BLE_DTM_ENABLED 1
#endif


// <q> BLE_RACP_ENABLED  - ble_racp - Record Access Control Point library
 


#ifndef BLE_RACP_ENABLED
#define BLE_RACP_ENABLED 0
#endif


// <e> NRF_BLE_CONN_PARAMS_ENABLED - ble_conn_params - Initiating and executing a connection parameters negotiation procedure
//==========================================================
#ifndef NRF_BLE_CONN_PARAMS_ENABLED
#define NRF_BLE_CONN_PARAMS_ENABLED 1
#endif
// <o> NRF_BLE_CONN_PARAMS_MAX_SLAVE_LATENCY_DEVIATION - The largest acceptable deviation in slave latency. 
// <i> The largest deviation (+ or -) from the requested slave latency that will not be renegotiated.


#ifndef NRF_BLE_CONN_PARAMS_MAX_SLAVE_LATENCY_DEVIATION
#define NRF_BLE_CONN_PARAMS_MAX_SLAVE_LATENCY_DEVIATION 499
#endif


// <o> NRF_BLE_CONN_PARAMS_MAX_SUPERVISION_TIMEOUT_DEVIATION - The largest acceptable deviation (in 10 ms units) in supervision timeout. 
// <i> The largest deviation (+ or -, in 10 ms units) from the requested supervision timeout that will not be renegotiated.


#ifndef NRF_BLE_CONN_PARAMS_MAX_SUPERVISION_TIMEOUT_DEVIATION
#define NRF_BLE_CONN_PARAMS_MAX_SUPERVISION_TIMEOUT_DEVIATION 65535
#endif


// </e>


// <q> NRF_BLE_GATT_ENABLED  - nrf_ble_gatt - GATT module
 


#ifndef NRF_BLE_GATT_ENABLED
#define NRF_BLE_GATT_ENABLED 1
#endif


// <q> NRF_BLE_QWR_ENABLED  - nrf_ble_qwr - Queued writes support module (prepare/execute write)
 


#ifndef NRF_BLE_QWR_ENABLED
#define NRF_BLE_QWR_ENABLED 0
#endif


// <e> PEER_MANAGER_ENABLED - peer_manager - Peer Manager
//==========================================================
#ifndef PEER_MANAGER_ENABLED
#define PEER_MANAGER_ENABLED 0
#endif
// <o> PM_MAX_REGISTRANTS - Number of event handlers that can be registered. 
#ifndef PM_MAX_REGISTRANTS
#define PM_MAX_REGISTRANTS 3
#endif


// <o> PM_FLASH_BUFFERS - Number of internal buffers for flash operations. 
// <i> Decrease this value to lower RAM usage.


#ifndef PM_FLASH_BUFFERS
#define PM_FLASH_BUFFERS 2
#endif


// <q> PM_CENTRAL_ENABLED  - Enable/disable central-specific Peer Manager functionality.
 


// <i> Enable/disable central-specific Peer Manager functionality.


#ifndef PM_CENTRAL_ENABLED
#define PM_CENTRAL_ENABLED 1
#endif


// </e>


// </h> 
//==========================================================


// <h> nRF_BLE_Services 


//==========================================================
// <q> BLE_ANCS_C_ENABLED  - ble_ancs_c - Apple Notification Service Client
 


#ifndef BLE_ANCS_C_ENABLED
#define BLE_ANCS_C_ENABLED 0
#endif


// <q> BLE_ANS_C_ENABLED  - ble_ans_c - Alert Notification Service Client
 


#ifndef BLE_ANS_C_ENABLED
#define BLE_ANS_C_ENABLED 0
#endif


// <q> BLE_BAS_C_ENABLED  - ble_bas_c - Battery Service Client
 


#ifndef BLE_BAS_C_ENABLED
#define BLE_BAS_C_ENABLED 0
#endif


// <q> BLE_BAS_ENABLED  - ble_bas - Battery Service
 


#ifndef BLE_BAS_ENABLED
#define BLE_BAS_ENABLED 0
#endif


// <q> BLE_CSCS_ENABLED  - ble_cscs - Cycling Speed and Cadence Service
 


#ifndef BLE_CSCS_ENABLED
#define BLE_CSCS_ENABLED 0
#endif


// <q> BLE_CTS_C_ENABLED  - ble_cts_c - Current Time Service Client
 


#ifndef BLE_CTS_C_ENABLED
#define BLE_CTS_C_ENABLED 0
#endif


// <q> BLE_DIS_ENABLED  - ble_dis - Device Information Service
 


#ifndef BLE_DIS_ENABLED
#define BLE_DIS_ENABLED 0
#endif


// <q> BLE_GLS_ENABLED  - ble_gls - Glucose Service
 


#ifndef BLE_GLS_ENABLED
#define BLE_GLS_ENABLED 0
#endif


// <q> BLE_HIDS_ENABLED  - ble_hids - Human Interface Device Service
 


#ifndef BLE_HIDS_ENABLED
#define BLE_HIDS_ENABLED 0
#endif


// <q> BLE_HRS_C_ENABLED  - ble_hrs_c - Heart Rate Service Client
 


#ifndef BLE_HRS_C_ENABLED
#define BLE_HRS_C_ENABLED 0
#endif


// <q> BLE_HRS_ENABLED  - ble_hrs - Heart Rate Service
 


#ifndef BLE_HRS_ENABLED
#define BLE_HRS_ENABLED 0
#endif


// <q> BLE_HTS_ENABLED  - ble_hts - Health Thermometer Service
 


#ifndef BLE_HTS_ENABLED
#define BLE_HTS_ENABLED 0
#endif


// <q> BLE_IAS_C_ENABLED  - ble_ias_c - Immediate Alert Service Client
 


#ifndef BLE_IAS_C_ENABLED
#define BLE_IAS_C_ENABLED 0
#endif


// <q> BLE_IAS_ENABLED  - ble_ias - Immediate Alert Service
 


#ifndef BLE_IAS_ENABLED
#define BLE_IAS_ENABLED 0
#endif


// <q> BLE_LBS_C_ENABLED  - ble_lbs_c - Nordic LED Button Service Client
 


#ifndef BLE_LBS_C_ENABLED
#define BLE_LBS_C_ENABLED 0
#endif


// <q> BLE_LBS_ENABLED  - ble_lbs - LED Button Service
 


#ifndef BLE_LBS_ENABLED
#define BLE_LBS_ENABLED 0
#endif


// <q> BLE_LLS_ENABLED  - ble_lls - Link Loss Service
 


#ifndef BLE_LLS_ENABLED
#define BLE_LLS_ENABLED 0
#endif


// <q> BLE_NUS_C_ENABLED  - ble_nus_c - Nordic UART Central Service
 


#ifndef BLE_NUS_C_ENABLED
#define BLE_NUS_C_ENABLED 0
#endif


// <q> BLE_NUS_ENABLED  - ble_nus - Nordic UART Service
 


#ifndef BLE_NUS_ENABLED
#define BLE_NUS_ENABLED 1
#endif


// <q> BLE_RSCS_C_ENABLED  - ble_rscs_c - Running Speed and Cadence Client
 


#ifndef BLE_RSCS_C_ENABLED
#define BLE_RSCS_C_ENABLED 0
#endif


// <q> BLE_RSCS_ENABLED  - ble_rscs - Running Speed and Cadence Service
 


#ifndef BLE_RSCS_ENABLED
#define BLE_RSCS_ENABLED 0
#endif


// <q> BLE_TPS_ENABLED  - ble_tps - TX Power Service
 


#ifndef BLE_TPS_ENABLED
#define BLE_TPS_ENABLED 0
#endif


// </h> 
//==========================================================


// <h> nRF_DFU 


//==========================================================
// <h> ble_dfu - Device Firmware Update


//==========================================================
// <q> BLE_DFU_ENABLED  - Enable DFU Service.
 


#ifndef BLE_DFU_ENABLED
#define BLE_DFU_ENABLED 0
#endif


// <q> NRF_DFU_BLE_BUTTONLESS_SUPPORTS_BONDS  - Buttonless DFU supports bonds.
 


#ifndef NRF_DFU_BLE_BUTTONLESS_SUPPORTS_BONDS
#define NRF_DFU_BLE_BUTTONLESS_SUPPORTS_BONDS 0
#endif


// </h> 
//==========================================================


// </h> 
//==========================================================


// <h> nRF_Drivers 


//==========================================================
// <e> APP_USBD_ENABLED - app_usbd - USB Device library
//==========================================================
#ifndef APP_USBD_ENABLED
#define APP_USBD_ENABLED 0
#endif
// <o> APP_USBD_VID - Vendor ID  <0x0000-0xFFFF> 




// <i> Vendor ID ordered from USB IF: http://www.usb.org/developers/vendor/


#ifndef APP_USBD_VID
#define APP_USBD_VID 0
#endif


// <o> APP_USBD_PID - Product ID  <0x0000-0xFFFF> 




// <i> Selected Product ID


#ifndef APP_USBD_PID
#define APP_USBD_PID 0
#endif


// <o> APP_USBD_DEVICE_VER_MAJOR - Device version, major part  <0-99> 




// <i> Device version, will be converted automatically to BCD notation. Use just decimal values.


#ifndef APP_USBD_DEVICE_VER_MAJOR
#define APP_USBD_DEVICE_VER_MAJOR 1
#endif


// <o> APP_USBD_DEVICE_VER_MINOR - Device version, minor part  <0-99> 




// <i> Device version, will be converted automatically to BCD notation. Use just decimal values.


#ifndef APP_USBD_DEVICE_VER_MINOR
#define APP_USBD_DEVICE_VER_MINOR 0
#endif


// <e> APP_USBD_EVENT_QUEUE_ENABLE - Enable event queue


// <i> This is the default configuration when all the events are placed into internal queue.
// <i> Disable it when external queue is used like app_scheduler or if you wish to process all events inside interrupts.
// <i> Processing all events from the interrupt level adds requirement not to call any functions that modifies the USBD library state from the context higher than USB interrupt context.
// <i> Functions that modify USBD state are functions for sleep, wakeup, start, stop, enable and disable.
//==========================================================
#ifndef APP_USBD_EVENT_QUEUE_ENABLE
#define APP_USBD_EVENT_QUEUE_ENABLE 1
#endif
// <o> APP_USBD_EVENT_QUEUE_SIZE - The size of event queue  <16-64> 




// <i> The size of the queue for the events that would be processed in the main loop.


#ifndef APP_USBD_EVENT_QUEUE_SIZE
#define APP_USBD_EVENT_QUEUE_SIZE 32
#endif


// </e>


// <q> APP_USBD_CONFIG_PROVIDE_SOF_TIMESTAMP  - Provide a function that generates timestamps for logs based on the current SOF
 


// <i> The function app_usbd_sof_timestamp_get will be implemented if the logger is enabled. 
// <i> Use it when initializing the logger. 
// <i> SOF processing will be always enabled when this configuration parameter is active. 
// <i> Notice that this option is configured outside of APP_USBD_CONFIG_LOG_ENABLED. 
// <i> This means that it will work even if the logging in this very module is disabled. 


#ifndef APP_USBD_CONFIG_PROVIDE_SOF_TIMESTAMP
#define APP_USBD_CONFIG_PROVIDE_SOF_TIMESTAMP 0
#endif


// <e> APP_USBD_CONFIG_LOG_ENABLED - Enable logging in the module
//==========================================================
#ifndef APP_USBD_CONFIG_LOG_ENABLED
#define APP_USBD_CONFIG_LOG_ENABLED 0
#endif
// <o> APP_USBD_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef APP_USBD_CONFIG_LOG_LEVEL
#define APP_USBD_CONFIG_LOG_LEVEL 3
#endif


// <o> APP_USBD_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef APP_USBD_CONFIG_INFO_COLOR
#define APP_USBD_CONFIG_INFO_COLOR 0
#endif


// <o> APP_USBD_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef APP_USBD_CONFIG_DEBUG_COLOR
#define APP_USBD_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// </e>


// <e> CLOCK_ENABLED - nrf_drv_clock - CLOCK peripheral driver
//==========================================================
#ifndef CLOCK_ENABLED
#define CLOCK_ENABLED 1
#endif
// <o> CLOCK_CONFIG_XTAL_FREQ  - HF XTAL Frequency
 
// <0=> Default (64 MHz) 


#ifndef CLOCK_CONFIG_XTAL_FREQ
#define CLOCK_CONFIG_XTAL_FREQ 0
#endif


// <o> CLOCK_CONFIG_LF_SRC  - LF Clock Source
 
// <0=> RC 
// <1=> XTAL 
// <2=> Synth 


#ifndef CLOCK_CONFIG_LF_SRC
#define CLOCK_CONFIG_LF_SRC 1
#endif


// <o> CLOCK_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef CLOCK_CONFIG_IRQ_PRIORITY
#define CLOCK_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// <e> COMP_ENABLED - nrf_drv_comp - COMP peripheral driver
//==========================================================
#ifndef COMP_ENABLED
#define COMP_ENABLED 0
#endif
// <o> COMP_CONFIG_REF  - Reference voltage
 
// <0=> Internal 1.2V 
// <1=> Internal 1.8V 
// <2=> Internal 2.4V 
// <4=> VDD 
// <7=> ARef 


#ifndef COMP_CONFIG_REF
#define COMP_CONFIG_REF 1
#endif


// <o> COMP_CONFIG_MAIN_MODE  - Main mode
 
// <0=> Single ended 
// <1=> Differential 


#ifndef COMP_CONFIG_MAIN_MODE
#define COMP_CONFIG_MAIN_MODE 0
#endif


// <o> COMP_CONFIG_SPEED_MODE  - Speed mode
 
// <0=> Low power 
// <1=> Normal 
// <2=> High speed 


#ifndef COMP_CONFIG_SPEED_MODE
#define COMP_CONFIG_SPEED_MODE 2
#endif


// <o> COMP_CONFIG_HYST  - Hystheresis
 
// <0=> No 
// <1=> 50mV 


#ifndef COMP_CONFIG_HYST
#define COMP_CONFIG_HYST 0
#endif


// <o> COMP_CONFIG_ISOURCE  - Current Source
 
// <0=> Off 
// <1=> 2.5 uA 
// <2=> 5 uA 
// <3=> 10 uA 


#ifndef COMP_CONFIG_ISOURCE
#define COMP_CONFIG_ISOURCE 0
#endif


// <o> COMP_CONFIG_INPUT  - Analog input
 
// <0=> 0 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef COMP_CONFIG_INPUT
#define COMP_CONFIG_INPUT 0
#endif


// <o> COMP_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef COMP_CONFIG_IRQ_PRIORITY
#define COMP_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// <q> EGU_ENABLED  - nrf_drv_swi - SWI(EGU) peripheral driver
 


#ifndef EGU_ENABLED
#define EGU_ENABLED 0
#endif


// <e> GPIOTE_ENABLED - nrf_drv_gpiote - GPIOTE peripheral driver
//==========================================================
#ifndef GPIOTE_ENABLED
#define GPIOTE_ENABLED 1
#endif
// <o> GPIOTE_CONFIG_NUM_OF_LOW_POWER_EVENTS - Number of lower power input pins 
#ifndef GPIOTE_CONFIG_NUM_OF_LOW_POWER_EVENTS
#define GPIOTE_CONFIG_NUM_OF_LOW_POWER_EVENTS 4
#endif


// <o> GPIOTE_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef GPIOTE_CONFIG_IRQ_PRIORITY
#define GPIOTE_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// <e> I2S_ENABLED - nrf_drv_i2s - I2S peripheral driver
//==========================================================
#ifndef I2S_ENABLED
#define I2S_ENABLED 0
#endif
// <o> I2S_CONFIG_SCK_PIN - SCK pin  <0-31> 




#ifndef I2S_CONFIG_SCK_PIN
#define I2S_CONFIG_SCK_PIN 31
#endif


// <o> I2S_CONFIG_LRCK_PIN - LRCK pin  <1-31> 




#ifndef I2S_CONFIG_LRCK_PIN
#define I2S_CONFIG_LRCK_PIN 30
#endif


// <o> I2S_CONFIG_MCK_PIN - MCK pin 
#ifndef I2S_CONFIG_MCK_PIN
#define I2S_CONFIG_MCK_PIN 255
#endif


// <o> I2S_CONFIG_SDOUT_PIN - SDOUT pin  <0-31> 




#ifndef I2S_CONFIG_SDOUT_PIN
#define I2S_CONFIG_SDOUT_PIN 29
#endif


// <o> I2S_CONFIG_SDIN_PIN - SDIN pin  <0-31> 




#ifndef I2S_CONFIG_SDIN_PIN
#define I2S_CONFIG_SDIN_PIN 28
#endif


// <o> I2S_CONFIG_MASTER  - Mode
 
// <0=> Master 
// <1=> Slave 


#ifndef I2S_CONFIG_MASTER
#define I2S_CONFIG_MASTER 0
#endif


// <o> I2S_CONFIG_FORMAT  - Format
 
// <0=> I2S 
// <1=> Aligned 


#ifndef I2S_CONFIG_FORMAT
#define I2S_CONFIG_FORMAT 0
#endif


// <o> I2S_CONFIG_ALIGN  - Alignment
 
// <0=> Left 
// <1=> Right 


#ifndef I2S_CONFIG_ALIGN
#define I2S_CONFIG_ALIGN 0
#endif


// <o> I2S_CONFIG_SWIDTH  - Sample width (bits)
 
// <0=> 8 
// <1=> 16 
// <2=> 24 


#ifndef I2S_CONFIG_SWIDTH
#define I2S_CONFIG_SWIDTH 1
#endif


// <o> I2S_CONFIG_CHANNELS  - Channels
 
// <0=> Stereo 
// <1=> Left 
// <2=> Right 


#ifndef I2S_CONFIG_CHANNELS
#define I2S_CONFIG_CHANNELS 1
#endif


// <o> I2S_CONFIG_MCK_SETUP  - MCK behavior
 
// <0=> Disabled 
// <2147483648=> 32MHz/2 
// <1342177280=> 32MHz/3 
// <1073741824=> 32MHz/4 
// <805306368=> 32MHz/5 
// <671088640=> 32MHz/6 
// <536870912=> 32MHz/8 
// <402653184=> 32MHz/10 
// <369098752=> 32MHz/11 
// <285212672=> 32MHz/15 
// <268435456=> 32MHz/16 
// <201326592=> 32MHz/21 
// <184549376=> 32MHz/23 
// <142606336=> 32MHz/30 
// <138412032=> 32MHz/31 
// <134217728=> 32MHz/32 
// <100663296=> 32MHz/42 
// <68157440=> 32MHz/63 
// <34340864=> 32MHz/125 


#ifndef I2S_CONFIG_MCK_SETUP
#define I2S_CONFIG_MCK_SETUP 536870912
#endif


// <o> I2S_CONFIG_RATIO  - MCK/LRCK ratio
 
// <0=> 32x 
// <1=> 48x 
// <2=> 64x 
// <3=> 96x 
// <4=> 128x 
// <5=> 192x 
// <6=> 256x 
// <7=> 384x 
// <8=> 512x 


#ifndef I2S_CONFIG_RATIO
#define I2S_CONFIG_RATIO 2000
#endif


// <o> I2S_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef I2S_CONFIG_IRQ_PRIORITY
#define I2S_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// <e> LPCOMP_ENABLED - nrf_drv_lpcomp - LPCOMP peripheral driver
//==========================================================
#ifndef LPCOMP_ENABLED
#define LPCOMP_ENABLED 0
#endif
// <o> LPCOMP_CONFIG_REFERENCE  - Reference voltage
 
// <0=> Supply 1/8 
// <1=> Supply 2/8 
// <2=> Supply 3/8 
// <3=> Supply 4/8 
// <4=> Supply 5/8 
// <5=> Supply 6/8 
// <6=> Supply 7/8 
// <8=> Supply 1/16 (nRF52) 
// <9=> Supply 3/16 (nRF52) 
// <10=> Supply 5/16 (nRF52) 
// <11=> Supply 7/16 (nRF52) 
// <12=> Supply 9/16 (nRF52) 
// <13=> Supply 11/16 (nRF52) 
// <14=> Supply 13/16 (nRF52) 
// <15=> Supply 15/16 (nRF52) 
// <7=> External Ref 0 
// <65543=> External Ref 1 


#ifndef LPCOMP_CONFIG_REFERENCE
#define LPCOMP_CONFIG_REFERENCE 3
#endif


// <o> LPCOMP_CONFIG_DETECTION  - Detection
 
// <0=> Crossing 
// <1=> Up 
// <2=> Down 


#ifndef LPCOMP_CONFIG_DETECTION
#define LPCOMP_CONFIG_DETECTION 2
#endif


// <o> LPCOMP_CONFIG_INPUT  - Analog input
 
// <0=> 0 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef LPCOMP_CONFIG_INPUT
#define LPCOMP_CONFIG_INPUT 0
#endif


// <q> LPCOMP_CONFIG_HYST  - Hysteresis
 


#ifndef LPCOMP_CONFIG_HYST
#define LPCOMP_CONFIG_HYST 0
#endif


// <o> LPCOMP_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef LPCOMP_CONFIG_IRQ_PRIORITY
#define LPCOMP_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// <e> PDM_ENABLED - nrf_drv_pdm - PDM peripheral driver
//==========================================================
#ifndef PDM_ENABLED
#define PDM_ENABLED 0
#endif
// <o> PDM_CONFIG_MODE  - Mode
 
// <0=> Stereo 
// <1=> Mono 


#ifndef PDM_CONFIG_MODE
#define PDM_CONFIG_MODE 1
#endif


// <o> PDM_CONFIG_EDGE  - Edge
 
// <0=> Left falling 
// <1=> Left rising 


#ifndef PDM_CONFIG_EDGE
#define PDM_CONFIG_EDGE 0
#endif


// <o> PDM_CONFIG_CLOCK_FREQ  - Clock frequency
 
// <134217728=> 1000k 
// <138412032=> 1032k (default) 
// <142606336=> 1067k 


#ifndef PDM_CONFIG_CLOCK_FREQ
#define PDM_CONFIG_CLOCK_FREQ 138412032
#endif


// <o> PDM_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef PDM_CONFIG_IRQ_PRIORITY
#define PDM_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// <q> PERIPHERAL_RESOURCE_SHARING_ENABLED  - nrf_drv_common - Peripheral drivers common module
 


#ifndef PERIPHERAL_RESOURCE_SHARING_ENABLED
#define PERIPHERAL_RESOURCE_SHARING_ENABLED 0
#endif


// <e> POWER_ENABLED - nrf_drv_power - POWER peripheral driver
//==========================================================
#ifndef POWER_ENABLED
#define POWER_ENABLED 0
#endif
// <o> POWER_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef POWER_CONFIG_IRQ_PRIORITY
#define POWER_CONFIG_IRQ_PRIORITY 7
#endif


// <q> POWER_CONFIG_DEFAULT_DCDCEN  - The default configuration of main DCDC regulator
 


// <i> This settings means only that components for DCDC regulator are installed and it can be enabled.


#ifndef POWER_CONFIG_DEFAULT_DCDCEN
#define POWER_CONFIG_DEFAULT_DCDCEN 0
#endif


// <q> POWER_CONFIG_DEFAULT_DCDCENHV  - The default configuration of High Voltage DCDC regulator
 


// <i> This settings means only that components for DCDC regulator are installed and it can be enabled.


#ifndef POWER_CONFIG_DEFAULT_DCDCENHV
#define POWER_CONFIG_DEFAULT_DCDCENHV 0
#endif


// </e>


// <q> PPI_ENABLED  - nrf_drv_ppi - PPI peripheral driver
 


#ifndef PPI_ENABLED
#define PPI_ENABLED 0
#endif


// <e> PWM_ENABLED - nrf_drv_pwm - PWM peripheral driver
//==========================================================
#ifndef PWM_ENABLED
#define PWM_ENABLED 0
#endif
// <o> PWM_DEFAULT_CONFIG_OUT0_PIN - Out0 pin  <0-31> 




#ifndef PWM_DEFAULT_CONFIG_OUT0_PIN
#define PWM_DEFAULT_CONFIG_OUT0_PIN 31
#endif


// <o> PWM_DEFAULT_CONFIG_OUT1_PIN - Out1 pin  <0-31> 




#ifndef PWM_DEFAULT_CONFIG_OUT1_PIN
#define PWM_DEFAULT_CONFIG_OUT1_PIN 31
#endif


// <o> PWM_DEFAULT_CONFIG_OUT2_PIN - Out2 pin  <0-31> 




#ifndef PWM_DEFAULT_CONFIG_OUT2_PIN
#define PWM_DEFAULT_CONFIG_OUT2_PIN 31
#endif


// <o> PWM_DEFAULT_CONFIG_OUT3_PIN - Out3 pin  <0-31> 




#ifndef PWM_DEFAULT_CONFIG_OUT3_PIN
#define PWM_DEFAULT_CONFIG_OUT3_PIN 31
#endif


// <o> PWM_DEFAULT_CONFIG_BASE_CLOCK  - Base clock
 
// <0=> 16 MHz 
// <1=> 8 MHz 
// <2=> 4 MHz 
// <3=> 2 MHz 
// <4=> 1 MHz 
// <5=> 500 kHz 
// <6=> 250 kHz 
// <7=> 125 kHz 


#ifndef PWM_DEFAULT_CONFIG_BASE_CLOCK
#define PWM_DEFAULT_CONFIG_BASE_CLOCK 4
#endif


// <o> PWM_DEFAULT_CONFIG_COUNT_MODE  - Count mode
 
// <0=> Up 
// <1=> Up and Down 


#ifndef PWM_DEFAULT_CONFIG_COUNT_MODE
#define PWM_DEFAULT_CONFIG_COUNT_MODE 0
#endif


// <o> PWM_DEFAULT_CONFIG_TOP_VALUE - Top value 
#ifndef PWM_DEFAULT_CONFIG_TOP_VALUE
#define PWM_DEFAULT_CONFIG_TOP_VALUE 1000
#endif


// <o> PWM_DEFAULT_CONFIG_LOAD_MODE  - Load mode
 
// <0=> Common 
// <1=> Grouped 
// <2=> Individual 
// <3=> Waveform 


#ifndef PWM_DEFAULT_CONFIG_LOAD_MODE
#define PWM_DEFAULT_CONFIG_LOAD_MODE 0
#endif


// <o> PWM_DEFAULT_CONFIG_STEP_MODE  - Step mode
 
// <0=> Auto 
// <1=> Triggered 


#ifndef PWM_DEFAULT_CONFIG_STEP_MODE
#define PWM_DEFAULT_CONFIG_STEP_MODE 0
#endif


// <o> PWM_DEFAULT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef PWM_DEFAULT_CONFIG_IRQ_PRIORITY
#define PWM_DEFAULT_CONFIG_IRQ_PRIORITY 7
#endif


// <q> PWM0_ENABLED  - Enable PWM0 instance
 


#ifndef PWM0_ENABLED
#define PWM0_ENABLED 0
#endif


// <q> PWM1_ENABLED  - Enable PWM1 instance
 


#ifndef PWM1_ENABLED
#define PWM1_ENABLED 0
#endif


// <q> PWM2_ENABLED  - Enable PWM2 instance
 


#ifndef PWM2_ENABLED
#define PWM2_ENABLED 0
#endif


// </e>


// <e> QDEC_ENABLED - nrf_drv_qdec - QDEC peripheral driver
//==========================================================
#ifndef QDEC_ENABLED
#define QDEC_ENABLED 0
#endif
// <o> QDEC_CONFIG_REPORTPER  - Report period
 
// <0=> 10 Samples 
// <1=> 40 Samples 
// <2=> 80 Samples 
// <3=> 120 Samples 
// <4=> 160 Samples 
// <5=> 200 Samples 
// <6=> 240 Samples 
// <7=> 280 Samples 


#ifndef QDEC_CONFIG_REPORTPER
#define QDEC_CONFIG_REPORTPER 0
#endif


// <o> QDEC_CONFIG_SAMPLEPER  - Sample period
 
// <0=> 128 us 
// <1=> 256 us 
// <2=> 512 us 
// <3=> 1024 us 
// <4=> 2048 us 
// <5=> 4096 us 
// <6=> 8192 us 
// <7=> 16384 us 


#ifndef QDEC_CONFIG_SAMPLEPER
#define QDEC_CONFIG_SAMPLEPER 7
#endif


// <o> QDEC_CONFIG_PIO_A - A pin  <0-31> 




#ifndef QDEC_CONFIG_PIO_A
#define QDEC_CONFIG_PIO_A 31
#endif


// <o> QDEC_CONFIG_PIO_B - B pin  <0-31> 




#ifndef QDEC_CONFIG_PIO_B
#define QDEC_CONFIG_PIO_B 31
#endif


// <o> QDEC_CONFIG_PIO_LED - LED pin  <0-31> 




#ifndef QDEC_CONFIG_PIO_LED
#define QDEC_CONFIG_PIO_LED 31
#endif


// <o> QDEC_CONFIG_LEDPRE - LED pre 
#ifndef QDEC_CONFIG_LEDPRE
#define QDEC_CONFIG_LEDPRE 511
#endif


// <o> QDEC_CONFIG_LEDPOL  - LED polarity
 
// <0=> Active low 
// <1=> Active high 


#ifndef QDEC_CONFIG_LEDPOL
#define QDEC_CONFIG_LEDPOL 1
#endif


// <q> QDEC_CONFIG_DBFEN  - Debouncing enable
 


#ifndef QDEC_CONFIG_DBFEN
#define QDEC_CONFIG_DBFEN 0
#endif


// <q> QDEC_CONFIG_SAMPLE_INTEN  - Sample ready interrupt enable
 


#ifndef QDEC_CONFIG_SAMPLE_INTEN
#define QDEC_CONFIG_SAMPLE_INTEN 0
#endif


// <o> QDEC_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef QDEC_CONFIG_IRQ_PRIORITY
#define QDEC_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// <e> RNG_ENABLED - nrf_drv_rng - RNG peripheral driver
//==========================================================
#ifndef RNG_ENABLED
#define RNG_ENABLED 0
#endif
// <q> RNG_CONFIG_ERROR_CORRECTION  - Error correction
 


#ifndef RNG_CONFIG_ERROR_CORRECTION
#define RNG_CONFIG_ERROR_CORRECTION 0
#endif


// <o> RNG_CONFIG_POOL_SIZE - Pool size 
#ifndef RNG_CONFIG_POOL_SIZE
#define RNG_CONFIG_POOL_SIZE 32
#endif


// <o> RNG_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef RNG_CONFIG_IRQ_PRIORITY
#define RNG_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// <e> RTC_ENABLED - nrf_drv_rtc - RTC peripheral driver
//==========================================================
#ifndef RTC_ENABLED
#define RTC_ENABLED 0
#endif
// <o> RTC_DEFAULT_CONFIG_FREQUENCY - Frequency  <16-32768> 




#ifndef RTC_DEFAULT_CONFIG_FREQUENCY
#define RTC_DEFAULT_CONFIG_FREQUENCY 32768
#endif


// <q> RTC_DEFAULT_CONFIG_RELIABLE  - Ensures safe compare event triggering
 


#ifndef RTC_DEFAULT_CONFIG_RELIABLE
#define RTC_DEFAULT_CONFIG_RELIABLE 0
#endif


// <o> RTC_DEFAULT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef RTC_DEFAULT_CONFIG_IRQ_PRIORITY
#define RTC_DEFAULT_CONFIG_IRQ_PRIORITY 7
#endif


// <q> RTC0_ENABLED  - Enable RTC0 instance
 


#ifndef RTC0_ENABLED
#define RTC0_ENABLED 0
#endif


// <q> RTC1_ENABLED  - Enable RTC1 instance
 


#ifndef RTC1_ENABLED
#define RTC1_ENABLED 0
#endif


// <q> RTC2_ENABLED  - Enable RTC2 instance
 


#ifndef RTC2_ENABLED
#define RTC2_ENABLED 0
#endif


// <o> NRF_MAXIMUM_LATENCY_US - Maximum possible time[us] in highest priority interrupt 
#ifndef NRF_MAXIMUM_LATENCY_US
#define NRF_MAXIMUM_LATENCY_US 2000
#endif


// </e>


// <e> SAADC_ENABLED - nrf_drv_saadc - SAADC peripheral driver
//==========================================================
#ifndef SAADC_ENABLED
#define SAADC_ENABLED 0
#endif
// <o> SAADC_CONFIG_RESOLUTION  - Resolution
 
// <0=> 8 bit 
// <1=> 10 bit 
// <2=> 12 bit 
// <3=> 14 bit 


#ifndef SAADC_CONFIG_RESOLUTION
#define SAADC_CONFIG_RESOLUTION 1
#endif


// <o> SAADC_CONFIG_OVERSAMPLE  - Sample period
 
// <0=> Disabled 
// <1=> 2x 
// <2=> 4x 
// <3=> 8x 
// <4=> 16x 
// <5=> 32x 
// <6=> 64x 
// <7=> 128x 
// <8=> 256x 


#ifndef SAADC_CONFIG_OVERSAMPLE
#define SAADC_CONFIG_OVERSAMPLE 0
#endif


// <q> SAADC_CONFIG_LP_MODE  - Enabling low power mode
 


#ifndef SAADC_CONFIG_LP_MODE
#define SAADC_CONFIG_LP_MODE 0
#endif


// <o> SAADC_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef SAADC_CONFIG_IRQ_PRIORITY
#define SAADC_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// <e> SPIS_ENABLED - nrf_drv_spis - SPI Slave driver
//==========================================================
#ifndef SPIS_ENABLED
#define SPIS_ENABLED 0
#endif
// <o> SPIS_DEFAULT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef SPIS_DEFAULT_CONFIG_IRQ_PRIORITY
#define SPIS_DEFAULT_CONFIG_IRQ_PRIORITY 7
#endif


// <o> SPIS_DEFAULT_MODE  - Mode
 
// <0=> MODE_0 
// <1=> MODE_1 
// <2=> MODE_2 
// <3=> MODE_3 


#ifndef SPIS_DEFAULT_MODE
#define SPIS_DEFAULT_MODE 0
#endif


// <o> SPIS_DEFAULT_BIT_ORDER  - SPIS default bit order
 
// <0=> MSB first 
// <1=> LSB first 


#ifndef SPIS_DEFAULT_BIT_ORDER
#define SPIS_DEFAULT_BIT_ORDER 0
#endif


// <o> SPIS_DEFAULT_DEF - SPIS default DEF character  <0-255> 




#ifndef SPIS_DEFAULT_DEF
#define SPIS_DEFAULT_DEF 255
#endif


// <o> SPIS_DEFAULT_ORC - SPIS default ORC character  <0-255> 




#ifndef SPIS_DEFAULT_ORC
#define SPIS_DEFAULT_ORC 255
#endif


// <q> SPIS0_ENABLED  - Enable SPIS0 instance
 


#ifndef SPIS0_ENABLED
#define SPIS0_ENABLED 0
#endif


// </e>


// <e> SPI_ENABLED - nrf_drv_spi - SPI/SPIM peripheral driver
//==========================================================
#ifndef SPI_ENABLED
#define SPI_ENABLED 0
#endif
// <o> SPI_DEFAULT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef SPI_DEFAULT_CONFIG_IRQ_PRIORITY
#define SPI_DEFAULT_CONFIG_IRQ_PRIORITY 7
#endif


// <o> SPI_DEFAULT_FREQUENCY  - SPI frequency
 
// <33554432=> 125 kHz 
// <67108864=> 250 kHz 
// <134217728=> 500 kHz 
// <268435456=> 1 MHz 
// <536870912=> 2 MHz 
// <1073741824=> 4 MHz 
// <2147483648=> 8 MHz 


#ifndef SPI_DEFAULT_FREQUENCY
#define SPI_DEFAULT_FREQUENCY 1073741824
#endif


// <o> NRF_SPI_DRV_MISO_PULLUP_CFG  - MISO PIN pull-up configuration.
 
// <0=> NRF_GPIO_PIN_NOPULL 
// <1=> NRF_GPIO_PIN_PULLDOWN 
// <3=> NRF_GPIO_PIN_PULLUP 


#ifndef NRF_SPI_DRV_MISO_PULLUP_CFG
#define NRF_SPI_DRV_MISO_PULLUP_CFG 1
#endif


// <e> SPI0_ENABLED - Enable SPI0 instance
//==========================================================
#ifndef SPI0_ENABLED
#define SPI0_ENABLED 0
#endif
// </e>


// </e>


// <e> TIMER_ENABLED - nrf_drv_timer - TIMER periperal driver
//==========================================================
#ifndef TIMER_ENABLED
#define TIMER_ENABLED 0
#endif
// <o> TIMER_DEFAULT_CONFIG_FREQUENCY  - Timer frequency if in Timer mode
 
// <0=> 16 MHz 
// <1=> 8 MHz 
// <2=> 4 MHz 
// <3=> 2 MHz 
// <4=> 1 MHz 
// <5=> 500 kHz 
// <6=> 250 kHz 
// <7=> 125 kHz 
// <8=> 62.5 kHz 
// <9=> 31.25 kHz 


#ifndef TIMER_DEFAULT_CONFIG_FREQUENCY
#define TIMER_DEFAULT_CONFIG_FREQUENCY 0
#endif


// <o> TIMER_DEFAULT_CONFIG_MODE  - Timer mode or operation
 
// <0=> Timer 
// <1=> Counter 


#ifndef TIMER_DEFAULT_CONFIG_MODE
#define TIMER_DEFAULT_CONFIG_MODE 0
#endif


// <o> TIMER_DEFAULT_CONFIG_BIT_WIDTH  - Timer counter bit width
 
// <0=> 16 bit 
// <1=> 8 bit 
// <2=> 24 bit 
// <3=> 32 bit 


#ifndef TIMER_DEFAULT_CONFIG_BIT_WIDTH
#define TIMER_DEFAULT_CONFIG_BIT_WIDTH 0
#endif


// <o> TIMER_DEFAULT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef TIMER_DEFAULT_CONFIG_IRQ_PRIORITY
#define TIMER_DEFAULT_CONFIG_IRQ_PRIORITY 7
#endif


// <q> TIMER0_ENABLED  - Enable TIMER0 instance
 


#ifndef TIMER0_ENABLED
#define TIMER0_ENABLED 0
#endif


// <q> TIMER1_ENABLED  - Enable TIMER1 instance
 


#ifndef TIMER1_ENABLED
#define TIMER1_ENABLED 0
#endif


// <q> TIMER2_ENABLED  - Enable TIMER2 instance
 


#ifndef TIMER2_ENABLED
#define TIMER2_ENABLED 0
#endif


// <q> TIMER3_ENABLED  - Enable TIMER3 instance
 


#ifndef TIMER3_ENABLED
#define TIMER3_ENABLED 0
#endif


// <q> TIMER4_ENABLED  - Enable TIMER4 instance
 


#ifndef TIMER4_ENABLED
#define TIMER4_ENABLED 0
#endif


// </e>


// <e> TWIS_ENABLED - nrf_drv_twis - TWIS peripheral driver
//==========================================================
#ifndef TWIS_ENABLED
#define TWIS_ENABLED 0
#endif
// <o> TWIS_DEFAULT_CONFIG_ADDR0 - Address0 
#ifndef TWIS_DEFAULT_CONFIG_ADDR0
#define TWIS_DEFAULT_CONFIG_ADDR0 0
#endif


// <o> TWIS_DEFAULT_CONFIG_ADDR1 - Address1 
#ifndef TWIS_DEFAULT_CONFIG_ADDR1
#define TWIS_DEFAULT_CONFIG_ADDR1 0
#endif


// <o> TWIS_DEFAULT_CONFIG_SCL_PULL  - SCL pin pull configuration
 
// <0=> Disabled 
// <1=> Pull down 
// <3=> Pull up 


#ifndef TWIS_DEFAULT_CONFIG_SCL_PULL
#define TWIS_DEFAULT_CONFIG_SCL_PULL 0
#endif


// <o> TWIS_DEFAULT_CONFIG_SDA_PULL  - SDA pin pull configuration
 
// <0=> Disabled 
// <1=> Pull down 
// <3=> Pull up 


#ifndef TWIS_DEFAULT_CONFIG_SDA_PULL
#define TWIS_DEFAULT_CONFIG_SDA_PULL 0
#endif


// <o> TWIS_DEFAULT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef TWIS_DEFAULT_CONFIG_IRQ_PRIORITY
#define TWIS_DEFAULT_CONFIG_IRQ_PRIORITY 7
#endif


// <q> TWIS0_ENABLED  - Enable TWIS0 instance
 


#ifndef TWIS0_ENABLED
#define TWIS0_ENABLED 0
#endif


// <q> TWIS1_ENABLED  - Enable TWIS1 instance
 


#ifndef TWIS1_ENABLED
#define TWIS1_ENABLED 0
#endif


// <q> TWIS_ASSUME_INIT_AFTER_RESET_ONLY  - Assume that any instance would be initialized only once
 


// <i> Optimization flag. Registers used by TWIS are shared by other peripherals. Normally, during initialization driver tries to clear all registers to known state before doing the initialization itself. This gives initialization safe procedure, no matter when it would be called. If you activate TWIS only once and do never uninitialize it - set this flag to 1 what gives more optimal code.


#ifndef TWIS_ASSUME_INIT_AFTER_RESET_ONLY
#define TWIS_ASSUME_INIT_AFTER_RESET_ONLY 0
#endif


// <q> TWIS_NO_SYNC_MODE  - Remove support for synchronous mode
 


// <i> Synchronous mode would be used in specific situations. And it uses some additional code and data memory to safely process state machine by polling it in status functions. If this functionality is not required it may be disabled to free some resources.


#ifndef TWIS_NO_SYNC_MODE
#define TWIS_NO_SYNC_MODE 0
#endif


// </e>


// <e> TWI_ENABLED - nrf_drv_twi - TWI/TWIM peripheral driver
//==========================================================
#ifndef TWI_ENABLED
#define TWI_ENABLED 0
#endif
// <o> TWI_DEFAULT_CONFIG_FREQUENCY  - Frequency
 
// <26738688=> 100k 
// <67108864=> 250k 
// <104857600=> 400k 


#ifndef TWI_DEFAULT_CONFIG_FREQUENCY
#define TWI_DEFAULT_CONFIG_FREQUENCY 26738688
#endif


// <q> TWI_DEFAULT_CONFIG_CLR_BUS_INIT  - Enables bus clearing procedure during init
 


#ifndef TWI_DEFAULT_CONFIG_CLR_BUS_INIT
#define TWI_DEFAULT_CONFIG_CLR_BUS_INIT 0
#endif


// <q> TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT  - Enables bus holding after uninit
 


#ifndef TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT
#define TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT 0
#endif


// <o> TWI_DEFAULT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef TWI_DEFAULT_CONFIG_IRQ_PRIORITY
#define TWI_DEFAULT_CONFIG_IRQ_PRIORITY 7
#endif


// <e> TWI0_ENABLED - Enable TWI0 instance
//==========================================================
#ifndef TWI0_ENABLED
#define TWI0_ENABLED 0
#endif
// </e>


// </e>


// <e> UART_ENABLED - nrf_drv_uart - UART/UARTE peripheral driver
//==========================================================
#ifndef UART_ENABLED
#define UART_ENABLED 1
#endif
// <o> UART_DEFAULT_CONFIG_HWFC  - Hardware Flow Control
 
// <0=> Disabled 
// <1=> Enabled 


#ifndef UART_DEFAULT_CONFIG_HWFC
#define UART_DEFAULT_CONFIG_HWFC 0
#endif


// <o> UART_DEFAULT_CONFIG_PARITY  - Parity
 
// <0=> Excluded 
// <14=> Included 


#ifndef UART_DEFAULT_CONFIG_PARITY
#define UART_DEFAULT_CONFIG_PARITY 0
#endif


// <o> UART_DEFAULT_CONFIG_BAUDRATE  - Default Baudrate
 
// <323584=> 1200 baud 
// <643072=> 2400 baud 
// <1290240=> 4800 baud 
// <2576384=> 9600 baud 
// <3862528=> 14400 baud 
// <5152768=> 19200 baud 
// <7716864=> 28800 baud 
// <10289152=> 38400 baud 
// <15400960=> 57600 baud 
// <20615168=> 76800 baud 
// <30801920=> 115200 baud 
// <61865984=> 230400 baud 
// <67108864=> 250000 baud 
// <121634816=> 460800 baud 
// <251658240=> 921600 baud 
// <268435456=> 1000000 baud 


#ifndef UART_DEFAULT_CONFIG_BAUDRATE
#define UART_DEFAULT_CONFIG_BAUDRATE 30801920
#endif


// <o> UART_DEFAULT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef UART_DEFAULT_CONFIG_IRQ_PRIORITY
#define UART_DEFAULT_CONFIG_IRQ_PRIORITY 7
#endif


// <q> UART_EASY_DMA_SUPPORT  - Driver supporting EasyDMA
 


#ifndef UART_EASY_DMA_SUPPORT
#define UART_EASY_DMA_SUPPORT 1
#endif


// <q> UART_LEGACY_SUPPORT  - Driver supporting Legacy mode
 


#ifndef UART_LEGACY_SUPPORT
#define UART_LEGACY_SUPPORT 1
#endif


// <e> UART0_ENABLED - Enable UART0 instance
//==========================================================
#ifndef UART0_ENABLED
#define UART0_ENABLED 1
#endif
// <q> UART0_CONFIG_USE_EASY_DMA  - Default setting for using EasyDMA
 


#ifndef UART0_CONFIG_USE_EASY_DMA
#define UART0_CONFIG_USE_EASY_DMA 1
#endif


// </e>


// </e>


// <e> USBD_ENABLED - nrf_drv_usbd - USB driver
//==========================================================
#ifndef USBD_ENABLED
#define USBD_ENABLED 0
#endif
// <o> USBD_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef USBD_CONFIG_IRQ_PRIORITY
#define USBD_CONFIG_IRQ_PRIORITY 7
#endif


// <o> NRF_DRV_USBD_DMASCHEDULER_MODE  - USBD SMA scheduler working scheme
 
// <0=> Prioritized access 
// <1=> Round Robin 


#ifndef NRF_DRV_USBD_DMASCHEDULER_MODE
#define NRF_DRV_USBD_DMASCHEDULER_MODE 0
#endif


// </e>


// <e> WDT_ENABLED - nrf_drv_wdt - WDT peripheral driver
//==========================================================
#ifndef WDT_ENABLED
#define WDT_ENABLED 1
#endif
// <o> WDT_CONFIG_BEHAVIOUR  - WDT behavior in CPU SLEEP or HALT mode
 
// <1=> Run in SLEEP, Pause in HALT 
// <8=> Pause in SLEEP, Run in HALT 
// <9=> Run in SLEEP and HALT 
// <0=> Pause in SLEEP and HALT 


#ifndef WDT_CONFIG_BEHAVIOUR
#define WDT_CONFIG_BEHAVIOUR 1
#endif


// <o> WDT_CONFIG_RELOAD_VALUE - Reload value  <15-4294967295> 




#ifndef WDT_CONFIG_RELOAD_VALUE
#define WDT_CONFIG_RELOAD_VALUE 30000
#endif


// <o> WDT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef WDT_CONFIG_IRQ_PRIORITY
#define WDT_CONFIG_IRQ_PRIORITY 7
#endif


// </e>


// </h> 
//==========================================================


// <h> nRF_Libraries 


//==========================================================
// <q> APP_FIFO_ENABLED  - app_fifo - Software FIFO implementation
 


#ifndef APP_FIFO_ENABLED
#define APP_FIFO_ENABLED 1
#endif


// <q> APP_GPIOTE_ENABLED  - app_gpiote - GPIOTE events dispatcher
 


#ifndef APP_GPIOTE_ENABLED
#define APP_GPIOTE_ENABLED 0
#endif


// <q> APP_PWM_ENABLED  - app_pwm - PWM functionality
 


#ifndef APP_PWM_ENABLED
#define APP_PWM_ENABLED 0
#endif


// <e> APP_SCHEDULER_ENABLED - app_scheduler - Events scheduler
//==========================================================
#ifndef APP_SCHEDULER_ENABLED
#define APP_SCHEDULER_ENABLED 1
#endif
// <q> APP_SCHEDULER_WITH_PAUSE  - Enabling pause feature
 


#ifndef APP_SCHEDULER_WITH_PAUSE
#define APP_SCHEDULER_WITH_PAUSE 0
#endif


// <q> APP_SCHEDULER_WITH_PROFILER  - Enabling scheduler profiling
 


#ifndef APP_SCHEDULER_WITH_PROFILER
#define APP_SCHEDULER_WITH_PROFILER 0
#endif


// </e>


// <e> APP_TIMER_ENABLED - app_timer - Application timer functionality
//==========================================================
#ifndef APP_TIMER_ENABLED
#define APP_TIMER_ENABLED 1
#endif
// <o> APP_TIMER_CONFIG_RTC_FREQUENCY  - Configure RTC prescaler.
 
// <0=> 32768 Hz 
// <1=> 16384 Hz 
// <3=> 8192 Hz 
// <7=> 4096 Hz 
// <15=> 2048 Hz 
// <31=> 1024 Hz 


#ifndef APP_TIMER_CONFIG_RTC_FREQUENCY
#define APP_TIMER_CONFIG_RTC_FREQUENCY 0
#endif


// <o> APP_TIMER_CONFIG_IRQ_PRIORITY  - Interrupt priority
 


// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 


#ifndef APP_TIMER_CONFIG_IRQ_PRIORITY
#define APP_TIMER_CONFIG_IRQ_PRIORITY 7
#endif


// <o> APP_TIMER_CONFIG_OP_QUEUE_SIZE - Capacity of timer requests queue. 
// <i> Size of the queue depends on how many timers are used
// <i> in the system, how often timers are started and overall
// <i> system latency. If queue size is too small app_timer calls
// <i> will fail.


#ifndef APP_TIMER_CONFIG_OP_QUEUE_SIZE
#define APP_TIMER_CONFIG_OP_QUEUE_SIZE 10
#endif


// <q> APP_TIMER_CONFIG_USE_SCHEDULER  - Enable scheduling app_timer events to app_scheduler
 


#ifndef APP_TIMER_CONFIG_USE_SCHEDULER
#define APP_TIMER_CONFIG_USE_SCHEDULER 0
#endif


// <q> APP_TIMER_WITH_PROFILER  - Enable app_timer profiling
 


#ifndef APP_TIMER_WITH_PROFILER
#define APP_TIMER_WITH_PROFILER 0
#endif


// <q> APP_TIMER_KEEPS_RTC_ACTIVE  - Enable RTC always on
 


// <i> If option is enabled RTC is kept running even if there is no active timers.
// <i> This option can be used when app_timer is used for timestamping.


#ifndef APP_TIMER_KEEPS_RTC_ACTIVE
#define APP_TIMER_KEEPS_RTC_ACTIVE 0
#endif


// <o> APP_TIMER_CONFIG_SWI_NUMBER  - Configure SWI instance used.
 
// <0=> 0 
// <1=> 1 


#ifndef APP_TIMER_CONFIG_SWI_NUMBER
#define APP_TIMER_CONFIG_SWI_NUMBER 0
#endif


// </e>


// <q> APP_TWI_ENABLED  - app_twi - TWI transaction manager wrapper. Switch to nrf_twi_mngr usage.
 


#ifndef APP_TWI_ENABLED
#define APP_TWI_ENABLED 0
#endif


// <e> APP_UART_ENABLED - app_uart - UART driver
//==========================================================
#ifndef APP_UART_ENABLED
#define APP_UART_ENABLED 1
#endif
// <o> APP_UART_DRIVER_INSTANCE  - UART instance used
 
// <0=> 0 


#ifndef APP_UART_DRIVER_INSTANCE
#define APP_UART_DRIVER_INSTANCE 0
#endif


// </e>


// <q> APP_USBD_CLASS_AUDIO_ENABLED  - app_usbd_audio - USB AUDIO class
 


#ifndef APP_USBD_CLASS_AUDIO_ENABLED
#define APP_USBD_CLASS_AUDIO_ENABLED 0
#endif


// <q> APP_USBD_CLASS_CDC_ACM_ENABLED  - app_usbd_cdc_acm - USB CDC ACM class
 


#ifndef APP_USBD_CLASS_CDC_ACM_ENABLED
#define APP_USBD_CLASS_CDC_ACM_ENABLED 0
#endif


// <q> APP_USBD_CLASS_HID_ENABLED  - app_usbd_hid - USB HID class
 


#ifndef APP_USBD_CLASS_HID_ENABLED
#define APP_USBD_CLASS_HID_ENABLED 0
#endif


// <q> APP_USBD_HID_GENERIC_ENABLED  - app_usbd_hid_generic - USB HID generic
 


#ifndef APP_USBD_HID_GENERIC_ENABLED
#define APP_USBD_HID_GENERIC_ENABLED 0
#endif


// <q> APP_USBD_HID_KBD_ENABLED  - app_usbd_hid_kbd - USB HID keyboard
 


#ifndef APP_USBD_HID_KBD_ENABLED
#define APP_USBD_HID_KBD_ENABLED 0
#endif


// <q> APP_USBD_HID_MOUSE_ENABLED  - app_usbd_hid_mouse - USB HID mouse
 


#ifndef APP_USBD_HID_MOUSE_ENABLED
#define APP_USBD_HID_MOUSE_ENABLED 0
#endif


// <q> APP_USBD_MSC_ENABLED  - app_usbd_msc - USB MSC class
 


#ifndef APP_USBD_MSC_ENABLED
#define APP_USBD_MSC_ENABLED 0
#endif


// <q> BUTTON_ENABLED  - app_button - buttons handling module
 


#ifndef BUTTON_ENABLED
#define BUTTON_ENABLED 1
#endif


// <q> CRC16_ENABLED  - crc16 - CRC16 calculation routines
 


#ifndef CRC16_ENABLED
#define CRC16_ENABLED 0
#endif


// <q> CRC32_ENABLED  - crc32 - CRC32 calculation routines
 


#ifndef CRC32_ENABLED
#define CRC32_ENABLED 0
#endif


// <q> ECC_ENABLED  - ecc - Elliptic Curve Cryptography Library
 


#ifndef ECC_ENABLED
#define ECC_ENABLED 0
#endif


// <e> FDS_ENABLED - fds - Flash data storage module
//==========================================================
#ifndef FDS_ENABLED
#define FDS_ENABLED 1
#endif
// <h> Pages - Virtual page settings


// <i> Configure the number of virtual pages to use and their size.
//==========================================================
// <o> FDS_VIRTUAL_PAGES - Number of virtual flash pages to use. 
// <i> One of the virtual pages is reserved by the system for garbage collection.
// <i> Therefore, the minimum is two virtual pages: one page to store data and one page to be used by the system for garbage collection.
// <i> The total amount of flash memory that is used by FDS amounts to @ref FDS_VIRTUAL_PAGES * @ref FDS_VIRTUAL_PAGE_SIZE * 4 bytes.


#ifndef FDS_VIRTUAL_PAGES
#define FDS_VIRTUAL_PAGES 6
#endif


// <o> FDS_VIRTUAL_PAGE_SIZE  - The size of a virtual flash page.
 


// <i> Expressed in number of 4-byte words.
// <i> By default, a virtual page is the same size as a physical page.
// <i> The size of a virtual page must be a multiple of the size of a physical page.
// <1024=> 1024 
// <2048=> 2048 


#ifndef FDS_VIRTUAL_PAGE_SIZE
#define FDS_VIRTUAL_PAGE_SIZE 1024
//#define FDS_VIRTUAL_PAGE_SIZE  2048 
#endif


// </h> 
//==========================================================


// <h> Backend - Backend configuration


// <i> Configure which nrf_fstorage backend is used by FDS to write to flash.
//==========================================================
// <o> FDS_BACKEND  - FDS flash backend.
 


// <i> NRF_FSTORAGE_SD uses the nrf_fstorage_sd backend implementation using the SoftDevice API. Use this if you have a SoftDevice present.
// <i> NRF_FSTORAGE_NVMC uses the nrf_fstorage_nvmc implementation. Use this setting if you don't use the SoftDevice.
// <1=> NRF_FSTORAGE_NVMC 
// <2=> NRF_FSTORAGE_SD 


#ifndef FDS_BACKEND
#define FDS_BACKEND 2
#endif


// </h> 
//==========================================================


// <h> Queue - Queue settings


//==========================================================
// <o> FDS_OP_QUEUE_SIZE - Size of the internal queue. 
// <i> Increase this value if you frequently get synchronous FDS_ERR_NO_SPACE_IN_QUEUES errors.


#ifndef FDS_OP_QUEUE_SIZE
//#define FDS_OP_QUEUE_SIZE 4
#define FDS_OP_QUEUE_SIZE 32
#endif


// </h> 
//==========================================================


// <h> CRC - CRC functionality


//==========================================================
// <e> FDS_CRC_CHECK_ON_READ - Enable CRC checks.


// <i> Save a record's CRC when it is written to flash and check it when the record is opened.
// <i> Records with an incorrect CRC can still be 'seen' by the user using FDS functions, but they cannot be opened.
// <i> Additionally, they will not be garbage collected until they are deleted.
//==========================================================
#ifndef FDS_CRC_CHECK_ON_READ
#define FDS_CRC_CHECK_ON_READ 0
#endif
// <o> FDS_CRC_CHECK_ON_WRITE  - Perform a CRC check on newly written records.
 


// <i> Perform a CRC check on newly written records.
// <i> This setting can be used to make sure that the record data was not altered while being written to flash.
// <1=> Enabled 
// <0=> Disabled 


#ifndef FDS_CRC_CHECK_ON_WRITE
#define FDS_CRC_CHECK_ON_WRITE 0
#endif


// </e>


// </h> 
//==========================================================


// <h> Users - Number of users


//==========================================================
// <o> FDS_MAX_USERS - Maximum number of callbacks that can be registered. 
#ifndef FDS_MAX_USERS
#define FDS_MAX_USERS 4
#endif


// </h> 
//==========================================================


// </e>


// <e> HARDFAULT_HANDLER_ENABLED - hardfault_default - HardFault default handler for debugging and release
//==========================================================
#ifndef HARDFAULT_HANDLER_ENABLED
#define HARDFAULT_HANDLER_ENABLED 0
#endif
// <q> HARDFAULT_HANDLER_GDB_PSP_BACKTRACE  - Bypass the GDB problem with multiple stack pointers backtrace
 


// <i> There is a known bug in GDB which causes it to incorrectly backtrace the code
// <i> when multiple stack pointers are used (main and process stack pointers).
// <i> This option enables the fix for that problem and allows to see the proper backtrace info.
// <i> It makes it possible to trace the code to the exact point where a HardFault appeared.
// <i> This option requires additional commands and may temporarily switch MSP stack to store data on PSP space.
// <i> This is an optional parameter - enable it while debugging.
// <i> Before a HardFault handler exits, the stack will be reverted to its previous value.


#ifndef HARDFAULT_HANDLER_GDB_PSP_BACKTRACE
#define HARDFAULT_HANDLER_GDB_PSP_BACKTRACE 1
#endif


// </e>


// <e> HCI_MEM_POOL_ENABLED - hci_mem_pool - memory pool implementation used by HCI
//==========================================================
#ifndef HCI_MEM_POOL_ENABLED
#define HCI_MEM_POOL_ENABLED 0
#endif
// <o> HCI_TX_BUF_SIZE - TX buffer size in bytes. 
#ifndef HCI_TX_BUF_SIZE
#define HCI_TX_BUF_SIZE 600
#endif


// <o> HCI_RX_BUF_SIZE - RX buffer size in bytes. 
#ifndef HCI_RX_BUF_SIZE
#define HCI_RX_BUF_SIZE 600
#endif


// <o> HCI_RX_BUF_QUEUE_SIZE - RX buffer queue size. 
#ifndef HCI_RX_BUF_QUEUE_SIZE
#define HCI_RX_BUF_QUEUE_SIZE 4
#endif


// </e>


// <e> HCI_SLIP_ENABLED - hci_slip - SLIP protocol implementation used by HCI
//==========================================================
#ifndef HCI_SLIP_ENABLED
#define HCI_SLIP_ENABLED 0
#endif
// <o> HCI_UART_BAUDRATE  - Default Baudrate
 
// <323584=> 1200 baud 
// <643072=> 2400 baud 
// <1290240=> 4800 baud 
// <2576384=> 9600 baud 
// <3862528=> 14400 baud 
// <5152768=> 19200 baud 
// <7716864=> 28800 baud 
// <10289152=> 38400 baud 
// <15400960=> 57600 baud 
// <20615168=> 76800 baud 
// <30801920=> 115200 baud 
// <61865984=> 230400 baud 
// <67108864=> 250000 baud 
// <121634816=> 460800 baud 
// <251658240=> 921600 baud 
// <268435456=> 1000000 baud 


#ifndef HCI_UART_BAUDRATE
#define HCI_UART_BAUDRATE 30801920
#endif


// <o> HCI_UART_FLOW_CONTROL  - Hardware Flow Control
 
// <0=> Disabled 
// <1=> Enabled 


#ifndef HCI_UART_FLOW_CONTROL
#define HCI_UART_FLOW_CONTROL 0
#endif


// <o> HCI_UART_RX_PIN - UART RX pin 
#ifndef HCI_UART_RX_PIN
#define HCI_UART_RX_PIN 8
#endif


// <o> HCI_UART_TX_PIN - UART TX pin 
#ifndef HCI_UART_TX_PIN
#define HCI_UART_TX_PIN 6
#endif


// <o> HCI_UART_RTS_PIN - UART RTS pin 
#ifndef HCI_UART_RTS_PIN
#define HCI_UART_RTS_PIN 5
#endif


// <o> HCI_UART_CTS_PIN - UART CTS pin 
#ifndef HCI_UART_CTS_PIN
#define HCI_UART_CTS_PIN 7
#endif


// </e>


// <e> HCI_TRANSPORT_ENABLED - hci_transport - HCI transport
//==========================================================
#ifndef HCI_TRANSPORT_ENABLED
#define HCI_TRANSPORT_ENABLED 0
#endif
// <o> HCI_MAX_PACKET_SIZE_IN_BITS - Maximum size of a single application packet in bits. 
#ifndef HCI_MAX_PACKET_SIZE_IN_BITS
#define HCI_MAX_PACKET_SIZE_IN_BITS 8000
#endif


// </e>


// <q> LED_SOFTBLINK_ENABLED  - led_softblink - led_softblink module
 


#ifndef LED_SOFTBLINK_ENABLED
#define LED_SOFTBLINK_ENABLED 0
#endif


// <q> LOW_POWER_PWM_ENABLED  - low_power_pwm - low_power_pwm module
 


#ifndef LOW_POWER_PWM_ENABLED
#define LOW_POWER_PWM_ENABLED 0
#endif


// <e> MEM_MANAGER_ENABLED - mem_manager - Dynamic memory allocator
//==========================================================
#ifndef MEM_MANAGER_ENABLED
#define MEM_MANAGER_ENABLED 0
#endif
// <o> MEMORY_MANAGER_SMALL_BLOCK_COUNT - Size of each memory blocks identified as 'small' block.  <0-255> 




#ifndef MEMORY_MANAGER_SMALL_BLOCK_COUNT
#define MEMORY_MANAGER_SMALL_BLOCK_COUNT 1
#endif


// <o> MEMORY_MANAGER_SMALL_BLOCK_SIZE -  Size of each memory blocks identified as 'small' block. 
// <i>  Size of each memory blocks identified as 'small' block. Memory block are recommended to be word-sized.


#ifndef MEMORY_MANAGER_SMALL_BLOCK_SIZE
#define MEMORY_MANAGER_SMALL_BLOCK_SIZE 32
#endif


// <o> MEMORY_MANAGER_MEDIUM_BLOCK_COUNT - Size of each memory blocks identified as 'medium' block.  <0-255> 




#ifndef MEMORY_MANAGER_MEDIUM_BLOCK_COUNT
#define MEMORY_MANAGER_MEDIUM_BLOCK_COUNT 0
#endif


// <o> MEMORY_MANAGER_MEDIUM_BLOCK_SIZE -  Size of each memory blocks identified as 'medium' block. 
// <i>  Size of each memory blocks identified as 'medium' block. Memory block are recommended to be word-sized.


#ifndef MEMORY_MANAGER_MEDIUM_BLOCK_SIZE
#define MEMORY_MANAGER_MEDIUM_BLOCK_SIZE 256
#endif


// <o> MEMORY_MANAGER_LARGE_BLOCK_COUNT - Size of each memory blocks identified as 'large' block.  <0-255> 




#ifndef MEMORY_MANAGER_LARGE_BLOCK_COUNT
#define MEMORY_MANAGER_LARGE_BLOCK_COUNT 0
#endif


// <o> MEMORY_MANAGER_LARGE_BLOCK_SIZE -  Size of each memory blocks identified as 'large' block. 
// <i>  Size of each memory blocks identified as 'large' block. Memory block are recommended to be word-sized.


#ifndef MEMORY_MANAGER_LARGE_BLOCK_SIZE
#define MEMORY_MANAGER_LARGE_BLOCK_SIZE 256
#endif


// <o> MEMORY_MANAGER_XLARGE_BLOCK_COUNT - Size of each memory blocks identified as 'extra large' block.  <0-255> 




#ifndef MEMORY_MANAGER_XLARGE_BLOCK_COUNT
#define MEMORY_MANAGER_XLARGE_BLOCK_COUNT 0
#endif


// <o> MEMORY_MANAGER_XLARGE_BLOCK_SIZE -  Size of each memory blocks identified as 'extra large' block. 
// <i>  Size of each memory blocks identified as 'extra large' block. Memory block are recommended to be word-sized.


#ifndef MEMORY_MANAGER_XLARGE_BLOCK_SIZE
#define MEMORY_MANAGER_XLARGE_BLOCK_SIZE 1320
#endif


// <o> MEMORY_MANAGER_XXLARGE_BLOCK_COUNT - Size of each memory blocks identified as 'extra extra large' block.  <0-255> 




#ifndef MEMORY_MANAGER_XXLARGE_BLOCK_COUNT
#define MEMORY_MANAGER_XXLARGE_BLOCK_COUNT 0
#endif


// <o> MEMORY_MANAGER_XXLARGE_BLOCK_SIZE -  Size of each memory blocks identified as 'extra extra large' block. 
// <i>  Size of each memory blocks identified as 'extra extra large' block. Memory block are recommended to be word-sized.


#ifndef MEMORY_MANAGER_XXLARGE_BLOCK_SIZE
#define MEMORY_MANAGER_XXLARGE_BLOCK_SIZE 3444
#endif


// <o> MEMORY_MANAGER_XSMALL_BLOCK_COUNT - Size of each memory blocks identified as 'extra small' block.  <0-255> 




#ifndef MEMORY_MANAGER_XSMALL_BLOCK_COUNT
#define MEMORY_MANAGER_XSMALL_BLOCK_COUNT 0
#endif


// <o> MEMORY_MANAGER_XSMALL_BLOCK_SIZE -  Size of each memory blocks identified as 'extra small' block. 
// <i>  Size of each memory blocks identified as 'extra large' block. Memory block are recommended to be word-sized.


#ifndef MEMORY_MANAGER_XSMALL_BLOCK_SIZE
#define MEMORY_MANAGER_XSMALL_BLOCK_SIZE 64
#endif


// <o> MEMORY_MANAGER_XXSMALL_BLOCK_COUNT - Size of each memory blocks identified as 'extra extra small' block.  <0-255> 




#ifndef MEMORY_MANAGER_XXSMALL_BLOCK_COUNT
#define MEMORY_MANAGER_XXSMALL_BLOCK_COUNT 0
#endif


// <o> MEMORY_MANAGER_XXSMALL_BLOCK_SIZE -  Size of each memory blocks identified as 'extra extra small' block. 
// <i>  Size of each memory blocks identified as 'extra extra small' block. Memory block are recommended to be word-sized.


#ifndef MEMORY_MANAGER_XXSMALL_BLOCK_SIZE
#define MEMORY_MANAGER_XXSMALL_BLOCK_SIZE 32
#endif


// <e> MEM_MANAGER_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef MEM_MANAGER_CONFIG_LOG_ENABLED
#define MEM_MANAGER_CONFIG_LOG_ENABLED 0
#endif
// <o> MEM_MANAGER_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef MEM_MANAGER_CONFIG_LOG_LEVEL
#define MEM_MANAGER_CONFIG_LOG_LEVEL 3
#endif


// <o> MEM_MANAGER_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef MEM_MANAGER_CONFIG_INFO_COLOR
#define MEM_MANAGER_CONFIG_INFO_COLOR 0
#endif


// <o> MEM_MANAGER_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef MEM_MANAGER_CONFIG_DEBUG_COLOR
#define MEM_MANAGER_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <q> MEM_MANAGER_DISABLE_API_PARAM_CHECK  - Disable API parameter checks in the module.
 


#ifndef MEM_MANAGER_DISABLE_API_PARAM_CHECK
#define MEM_MANAGER_DISABLE_API_PARAM_CHECK 0
#endif


// </e>


// <e> NRF_BALLOC_ENABLED - nrf_balloc - Block allocator module
//==========================================================
#ifndef NRF_BALLOC_ENABLED
#define NRF_BALLOC_ENABLED 1
#endif
// <e> NRF_BALLOC_CONFIG_DEBUG_ENABLED - Enables debug mode in the module.
//==========================================================
#ifndef NRF_BALLOC_CONFIG_DEBUG_ENABLED
#define NRF_BALLOC_CONFIG_DEBUG_ENABLED 0
#endif
// <o> NRF_BALLOC_CONFIG_HEAD_GUARD_WORDS - Number of words used as head guard.  <0-255> 




#ifndef NRF_BALLOC_CONFIG_HEAD_GUARD_WORDS
#define NRF_BALLOC_CONFIG_HEAD_GUARD_WORDS 1
#endif


// <o> NRF_BALLOC_CONFIG_TAIL_GUARD_WORDS - Number of words used as tail guard.  <0-255> 




#ifndef NRF_BALLOC_CONFIG_TAIL_GUARD_WORDS
#define NRF_BALLOC_CONFIG_TAIL_GUARD_WORDS 1
#endif


// <q> NRF_BALLOC_CONFIG_BASIC_CHECKS_ENABLED  - Enables basic checks in this module.
 


#ifndef NRF_BALLOC_CONFIG_BASIC_CHECKS_ENABLED
#define NRF_BALLOC_CONFIG_BASIC_CHECKS_ENABLED 0
#endif


// <q> NRF_BALLOC_CONFIG_DOUBLE_FREE_CHECK_ENABLED  - Enables double memory free check in this module.
 


#ifndef NRF_BALLOC_CONFIG_DOUBLE_FREE_CHECK_ENABLED
#define NRF_BALLOC_CONFIG_DOUBLE_FREE_CHECK_ENABLED 0
#endif


// <q> NRF_BALLOC_CONFIG_DATA_TRASHING_CHECK_ENABLED  - Enables free memory corruption check in this module.
 


#ifndef NRF_BALLOC_CONFIG_DATA_TRASHING_CHECK_ENABLED
#define NRF_BALLOC_CONFIG_DATA_TRASHING_CHECK_ENABLED 0
#endif


// </e>


// </e>


// <e> NRF_CSENSE_ENABLED - nrf_csense - Capacitive sensor module
//==========================================================
#ifndef NRF_CSENSE_ENABLED
#define NRF_CSENSE_ENABLED 0
#endif
// <o> NRF_CSENSE_PAD_HYSTERESIS - Minimum value of change required to determine that a pad was touched. 
#ifndef NRF_CSENSE_PAD_HYSTERESIS
#define NRF_CSENSE_PAD_HYSTERESIS 15
#endif


// <o> NRF_CSENSE_PAD_DEVIATION - Minimum value measured on a pad required to take it into account while calculating the step. 
#ifndef NRF_CSENSE_PAD_DEVIATION
#define NRF_CSENSE_PAD_DEVIATION 70
#endif


// <o> NRF_CSENSE_MIN_PAD_VALUE - Minimum normalized value on a pad required to take its value into account. 
#ifndef NRF_CSENSE_MIN_PAD_VALUE
#define NRF_CSENSE_MIN_PAD_VALUE 20
#endif


// <o> NRF_CSENSE_MAX_PADS_NUMBER - Maximum number of pads used for one instance. 
#ifndef NRF_CSENSE_MAX_PADS_NUMBER
#define NRF_CSENSE_MAX_PADS_NUMBER 20
#endif


// <o> NRF_CSENSE_MAX_VALUE - Maximum normalized value obtained from measurement. 
#ifndef NRF_CSENSE_MAX_VALUE
#define NRF_CSENSE_MAX_VALUE 1000
#endif


// <o> NRF_CSENSE_OUTPUT_PIN - Output pin used by the low-level module. 
// <i> This is used when capacitive sensor does not use COMP.


#ifndef NRF_CSENSE_OUTPUT_PIN
#define NRF_CSENSE_OUTPUT_PIN 26
#endif


// </e>


// <e> NRF_DRV_CSENSE_ENABLED - nrf_drv_csense - Capacitive sensor low-level module
//==========================================================
#ifndef NRF_DRV_CSENSE_ENABLED
#define NRF_DRV_CSENSE_ENABLED 0
#endif
// <e> USE_COMP - Use the comparator to implement the capacitive sensor driver.


// <i> Due to Anomaly 84, COMP I_SOURCE is not functional. It has too high a varation.
//==========================================================
#ifndef USE_COMP
#define USE_COMP 0
#endif
// <o> TIMER0_FOR_CSENSE - First TIMER instance used by the driver (not used on nRF51). 
#ifndef TIMER0_FOR_CSENSE
#define TIMER0_FOR_CSENSE 1
#endif


// <o> TIMER1_FOR_CSENSE - Second TIMER instance used by the driver (not used on nRF51). 
#ifndef TIMER1_FOR_CSENSE
#define TIMER1_FOR_CSENSE 2
#endif


// <o> MEASUREMENT_PERIOD - Single measurement period. 
// <i> Time of a single measurement can be calculated as
// <i> T = (1/2)*MEASUREMENT_PERIOD*(1/f_OSC) where f_OSC = I_SOURCE / (2C*(VUP-VDOWN) ).
// <i> I_SOURCE, VUP, and VDOWN are values used to initialize COMP and C is the capacitance of the used pad.


#ifndef MEASUREMENT_PERIOD
#define MEASUREMENT_PERIOD 20
#endif


// </e>


// </e>


// <q> NRF_FPRINTF_ENABLED  - nrf_fprintf - fprintf function.
 


#ifndef NRF_FPRINTF_ENABLED
#define NRF_FPRINTF_ENABLED 1
#endif


// <e> NRF_FSTORAGE_ENABLED - nrf_fstorage - Flash abstraction library
//==========================================================
#ifndef NRF_FSTORAGE_ENABLED
#define NRF_FSTORAGE_ENABLED 1
#endif
// <h> nrf_fstorage_sd - Implementation using the SoftDevice.


// <i> Configuration options for the fstorage implementation using the SoftDevice.
//==========================================================
// <o> NRF_FSTORAGE_SD_QUEUE_SIZE - Size of the internal queue of operations. 
// <i> Increase this value if API calls frequently return the error @ref NRF_ERROR_NO_MEM.


#ifndef NRF_FSTORAGE_SD_QUEUE_SIZE
#define NRF_FSTORAGE_SD_QUEUE_SIZE 4
#endif


// <o> NRF_FSTORAGE_SD_MAX_RETRIES - Maximum number of attempts at executing an operation when the SoftDevice is busy. 
// <i> Increase this value if events frequently return the @ref NRF_ERROR_TIMEOUT error.
// <i> The SoftDevice might fail to schedule flash access due to high BLE activity.


#ifndef NRF_FSTORAGE_SD_MAX_RETRIES
#define NRF_FSTORAGE_SD_MAX_RETRIES 8
#endif


// <o> NRF_FSTORAGE_SD_MAX_WRITE_SIZE - Maximum number of bytes to be written to flash in a single operation. 
// <i> This value must be a multiple of four.
// <i> Lowering this value can increase the chances of the SoftDevice being able to execute flash operations in between radio activity.
// <i> This value is bound by the maximum number of bytes that can be written to flash in a single call to @ref sd_flash_write.
// <i> That is 1024 bytes for nRF51 ICs and 4096 bytes for nRF52 ICs.


#ifndef NRF_FSTORAGE_SD_MAX_WRITE_SIZE
#define NRF_FSTORAGE_SD_MAX_WRITE_SIZE 4096
#endif


// </h> 
//==========================================================


// </e>


// <q> NRF_MEMOBJ_ENABLED  - nrf_memobj - Linked memory allocator module
 


#ifndef NRF_MEMOBJ_ENABLED
#define NRF_MEMOBJ_ENABLED 1
#endif


// <e> NRF_PWR_MGMT_ENABLED - nrf_pwr_mgmt - Power management module
//==========================================================
#ifndef NRF_PWR_MGMT_ENABLED
#define NRF_PWR_MGMT_ENABLED 1
#endif
// <e> NRF_PWR_MGMT_CONFIG_DEBUG_PIN_ENABLED - Enables pin debug in the module.


// <i> Selected pin will be set when CPU is in sleep mode.
//==========================================================
#ifndef NRF_PWR_MGMT_CONFIG_DEBUG_PIN_ENABLED
#define NRF_PWR_MGMT_CONFIG_DEBUG_PIN_ENABLED 0
#endif
// <o> NRF_PWR_MGMT_SLEEP_DEBUG_PIN  - Pin number
 
// <0=> 0 (P0.0) 
// <1=> 1 (P0.1) 
// <2=> 2 (P0.2) 
// <3=> 3 (P0.3) 
// <4=> 4 (P0.4) 
// <5=> 5 (P0.5) 
// <6=> 6 (P0.6) 
// <7=> 7 (P0.7) 
// <8=> 8 (P0.8) 
// <9=> 9 (P0.9) 
// <10=> 10 (P0.10) 
// <11=> 11 (P0.11) 
// <12=> 12 (P0.12) 
// <13=> 13 (P0.13) 
// <14=> 14 (P0.14) 
// <15=> 15 (P0.15) 
// <16=> 16 (P0.16) 
// <17=> 17 (P0.17) 
// <18=> 18 (P0.18) 
// <19=> 19 (P0.19) 
// <20=> 20 (P0.20) 
// <21=> 21 (P0.21) 
// <22=> 22 (P0.22) 
// <23=> 23 (P0.23) 
// <24=> 24 (P0.24) 
// <25=> 25 (P0.25) 
// <26=> 26 (P0.26) 
// <27=> 27 (P0.27) 
// <28=> 28 (P0.28) 
// <29=> 29 (P0.29) 
// <30=> 30 (P0.30) 
// <31=> 31 (P0.31) 
// <4294967295=> Not connected 


#ifndef NRF_PWR_MGMT_SLEEP_DEBUG_PIN
#define NRF_PWR_MGMT_SLEEP_DEBUG_PIN 31
#endif


// </e>


// <q> NRF_PWR_MGMT_CONFIG_CPU_USAGE_MONITOR_ENABLED  - Enables CPU usage monitor.
 


// <i> Module will trace percentage of CPU usage in one second intervals.


#ifndef NRF_PWR_MGMT_CONFIG_CPU_USAGE_MONITOR_ENABLED
#define NRF_PWR_MGMT_CONFIG_CPU_USAGE_MONITOR_ENABLED 0
#endif


// <e> NRF_PWR_MGMT_CONFIG_STANDBY_TIMEOUT_ENABLED - Enable standby timeout.
//==========================================================
#ifndef NRF_PWR_MGMT_CONFIG_STANDBY_TIMEOUT_ENABLED
#define NRF_PWR_MGMT_CONFIG_STANDBY_TIMEOUT_ENABLED 0
#endif
// <o> NRF_PWR_MGMT_CONFIG_STANDBY_TIMEOUT_S - Standby timeout (in seconds). 
// <i> Shutdown procedure will begin no earlier than after this number of seconds.


#ifndef NRF_PWR_MGMT_CONFIG_STANDBY_TIMEOUT_S
#define NRF_PWR_MGMT_CONFIG_STANDBY_TIMEOUT_S 3
#endif


// </e>


// <q> NRF_PWR_MGMT_CONFIG_FPU_SUPPORT_ENABLED  - Enables FPU event cleaning.
 


#ifndef NRF_PWR_MGMT_CONFIG_FPU_SUPPORT_ENABLED
#define NRF_PWR_MGMT_CONFIG_FPU_SUPPORT_ENABLED 1
#endif


// <q> NRF_PWR_MGMT_CONFIG_AUTO_SHUTDOWN_RETRY  - Blocked shutdown procedure will be retried every second.
 


#ifndef NRF_PWR_MGMT_CONFIG_AUTO_SHUTDOWN_RETRY
#define NRF_PWR_MGMT_CONFIG_AUTO_SHUTDOWN_RETRY 0
#endif


// <q> NRF_PWR_MGMT_CONFIG_USE_SCHEDULER  - Module will use @ref app_scheduler.
 


#ifndef NRF_PWR_MGMT_CONFIG_USE_SCHEDULER
#define NRF_PWR_MGMT_CONFIG_USE_SCHEDULER 0
#endif


// <o> NRF_PWR_MGMT_CONFIG_HANDLER_PRIORITY_COUNT - The number of priorities for module handlers. 
// <i> The number of stages of the shutdown process.


#ifndef NRF_PWR_MGMT_CONFIG_HANDLER_PRIORITY_COUNT
#define NRF_PWR_MGMT_CONFIG_HANDLER_PRIORITY_COUNT 3
#endif


// </e>


// <q> NRF_QUEUE_ENABLED  - nrf_queue - Queue module
 


#ifndef NRF_QUEUE_ENABLED
#define NRF_QUEUE_ENABLED 0
#endif


// <q> NRF_SECTION_ITER_ENABLED  - nrf_section_iter - Section iterator
 


#ifndef NRF_SECTION_ITER_ENABLED
#define NRF_SECTION_ITER_ENABLED 1
#endif


// <q> NRF_STRERROR_ENABLED  - nrf_strerror - Library for converting error code to string.
 


#ifndef NRF_STRERROR_ENABLED
#define NRF_STRERROR_ENABLED 1
#endif


// <q> NRF_TWI_MNGR_ENABLED  - nrf_twi_mngr - TWI transaction manager
 


#ifndef NRF_TWI_MNGR_ENABLED
#define NRF_TWI_MNGR_ENABLED 0
#endif


// <q> RETARGET_ENABLED  - retarget - Retargeting stdio functions
 


#ifndef RETARGET_ENABLED
#define RETARGET_ENABLED 1
#endif


// <q> SLIP_ENABLED  - slip - SLIP encoding and decoding
 


#ifndef SLIP_ENABLED
#define SLIP_ENABLED 0
#endif


// <h> nrf_cli - Command line interface


//==========================================================
// <q> NRF_CLI_ENABLED  - Enable/disable the CLI module.
 


#ifndef NRF_CLI_ENABLED
#define NRF_CLI_ENABLED 0
#endif


// <o> NRF_CLI_ARGC_MAX - Maximum number of parameters passed to the command handler. 
#ifndef NRF_CLI_ARGC_MAX
#define NRF_CLI_ARGC_MAX 12
#endif


// <q> NRF_CLI_BUILD_IN_CMDS_ENABLED  - CLI built-in commands.
 


#ifndef NRF_CLI_BUILD_IN_CMDS_ENABLED
#define NRF_CLI_BUILD_IN_CMDS_ENABLED 1
#endif


// <o> NRF_CLI_CMD_BUFF_SIZE - Maximum buffer size for a single command. 
#ifndef NRF_CLI_CMD_BUFF_SIZE
#define NRF_CLI_CMD_BUFF_SIZE 128
#endif


// <q> NRF_CLI_ECHO_STATUS  - CLI echo status. If set, echo is ON.
 


#ifndef NRF_CLI_ECHO_STATUS
#define NRF_CLI_ECHO_STATUS 1
#endif


// <o> NRF_CLI_PRINTF_BUFF_SIZE - Maximum print buffer size. 
#ifndef NRF_CLI_PRINTF_BUFF_SIZE
#define NRF_CLI_PRINTF_BUFF_SIZE 23
#endif


// <e> NRF_CLI_HISTORY_ENABLED - Enable CLI history mode.
//==========================================================
#ifndef NRF_CLI_HISTORY_ENABLED
#define NRF_CLI_HISTORY_ENABLED 1
#endif
// <o> NRF_CLI_HISTORY_ELEMENT_SIZE - Size of one memory object reserved for CLI history. 
#ifndef NRF_CLI_HISTORY_ELEMENT_SIZE
#define NRF_CLI_HISTORY_ELEMENT_SIZE 32
#endif


// <o> NRF_CLI_HISTORY_ELEMENT_COUNT - Number of history memory objects. 
#ifndef NRF_CLI_HISTORY_ELEMENT_COUNT
#define NRF_CLI_HISTORY_ELEMENT_COUNT 8
#endif


// </e>


// <q> NRF_CLI_VT100_COLORS_ENABLED  - CLI VT100 colors.
 


#ifndef NRF_CLI_VT100_COLORS_ENABLED
#define NRF_CLI_VT100_COLORS_ENABLED 1
#endif


// <q> NRF_CLI_STATISTICS_ENABLED  - Enable CLI statistics.
 


#ifndef NRF_CLI_STATISTICS_ENABLED
#define NRF_CLI_STATISTICS_ENABLED 1
#endif


// <q> NRF_CLI_LOG_BACKEND  - Enable logger backend interface.
 


#ifndef NRF_CLI_LOG_BACKEND
#define NRF_CLI_LOG_BACKEND 1
#endif


// <q> NRF_CLI_USES_TASK_MANAGER_ENABLED  - Enable CLI to use task_manager
 


#ifndef NRF_CLI_USES_TASK_MANAGER_ENABLED
#define NRF_CLI_USES_TASK_MANAGER_ENABLED 0
#endif


// </h> 
//==========================================================


// </h> 
//==========================================================


// <h> nRF_Log 


//==========================================================
// <e> NRF_LOG_BACKEND_RTT_ENABLED - nrf_log_backend_rtt - Log RTT backend
//==========================================================
#ifndef NRF_LOG_BACKEND_RTT_ENABLED
#define NRF_LOG_BACKEND_RTT_ENABLED 1
#endif
// <o> NRF_LOG_BACKEND_RTT_TEMP_BUFFER_SIZE - Size of buffer for partially processed strings. 
// <i> Size of the buffer is a trade-off between RAM usage and processing.
// <i> if buffer is smaller then strings will often be fragmented.
// <i> It is recommended to use size which will fit typical log and only the
// <i> longer one will be fragmented.


#ifndef NRF_LOG_BACKEND_RTT_TEMP_BUFFER_SIZE
#define NRF_LOG_BACKEND_RTT_TEMP_BUFFER_SIZE 64
#endif


// </e>


// <h> nrf_log - Logger


//==========================================================
// <e> NRF_LOG_ENABLED - Logging module for nRF5 SDK
//==========================================================
#ifndef NRF_LOG_ENABLED
#define NRF_LOG_ENABLED  1
#endif
// <e> NRF_LOG_USES_COLORS - If enabled then ANSI escape code for colors is prefixed to every string
//==========================================================
#ifndef NRF_LOG_USES_COLORS
#define NRF_LOG_USES_COLORS 1
#endif
// <o> NRF_LOG_COLOR_DEFAULT  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_LOG_COLOR_DEFAULT
#define NRF_LOG_COLOR_DEFAULT 0
#endif


// <o> NRF_LOG_ERROR_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_LOG_ERROR_COLOR
#define NRF_LOG_ERROR_COLOR 2
#endif


// <o> NRF_LOG_WARNING_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_LOG_WARNING_COLOR
#define NRF_LOG_WARNING_COLOR 4
#endif


// </e>


// <o> NRF_LOG_DEFAULT_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_LOG_DEFAULT_LEVEL
#define NRF_LOG_DEFAULT_LEVEL 4
#endif


// <q> NRF_LOG_DEFERRED  - Enable deffered logger.
 


// <i> Log data is buffered and can be processed in idle.


#ifndef NRF_LOG_DEFERRED
#define NRF_LOG_DEFERRED 1
#endif


// <o> NRF_LOG_BUFSIZE  - Size of the buffer for storing logs (in bytes).
 


// <i> Must be power of 2 and multiple of 4.
// <i> If NRF_LOG_DEFERRED = 0 then buffer size can be reduced to minimum.
// <128=> 128 
// <256=> 256 
// <512=> 512 
// <1024=> 1024 
// <2048=> 2048 
// <4096=> 4096 
// <8192=> 8192 
// <16384=> 16384 


#ifndef NRF_LOG_BUFSIZE
#define NRF_LOG_BUFSIZE 1024
#endif


// <q> NRF_LOG_ALLOW_OVERFLOW  - Configures behavior when circular buffer is full.
 


// <i> If set then oldest logs are overwritten. Otherwise a 
// <i> marker is injected informing about overflow.


#ifndef NRF_LOG_ALLOW_OVERFLOW
#define NRF_LOG_ALLOW_OVERFLOW 0
#endif


// <q> NRF_LOG_USES_TIMESTAMP  - Enable timestamping
 


// <i> Function for getting the timestamp is provided by the user


#ifndef NRF_LOG_USES_TIMESTAMP
#define NRF_LOG_USES_TIMESTAMP 0
#endif


// <q> NRF_LOG_FILTERS_ENABLED  - Enable dynamic filtering of logs.
 


#ifndef NRF_LOG_FILTERS_ENABLED
#define NRF_LOG_FILTERS_ENABLED 0
#endif


// <q> NRF_LOG_CLI_CMDS  - Enable CLI commands for the module.
 


#ifndef NRF_LOG_CLI_CMDS
#define NRF_LOG_CLI_CMDS 0
#endif


// <h> Log message pool - Configuration of log message pool


//==========================================================
// <o> NRF_LOG_MSGPOOL_ELEMENT_SIZE - Size of a single element in the pool of memory objects. 
// <i> If a small value is set, then performance of logs processing
// <i> is degraded because data is fragmented. Bigger value impacts
// <i> RAM memory utilization. The size is set to fit a message with
// <i> a timestamp and up to 2 arguments in a single memory object.


#ifndef NRF_LOG_MSGPOOL_ELEMENT_SIZE
#define NRF_LOG_MSGPOOL_ELEMENT_SIZE 20
#endif


// <o> NRF_LOG_MSGPOOL_ELEMENT_COUNT - Number of elements in the pool of memory objects 
// <i> If a small value is set, then it may lead to a deadlock
// <i> in certain cases if backend has high latency and holds
// <i> multiple messages for long time. Bigger value impacts
// <i> RAM memory usage.


#ifndef NRF_LOG_MSGPOOL_ELEMENT_COUNT
#define NRF_LOG_MSGPOOL_ELEMENT_COUNT 8
#endif


// </h> 
//==========================================================


// </e>


// <h> nrf_log module configuration 


//==========================================================
// <h> nrf_log in nRF_Core 


//==========================================================
// <e> NRF_MPU_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef NRF_MPU_CONFIG_LOG_ENABLED
#define NRF_MPU_CONFIG_LOG_ENABLED 0
#endif
// <o> NRF_MPU_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_MPU_CONFIG_LOG_LEVEL
#define NRF_MPU_CONFIG_LOG_LEVEL 4
#endif


// <o> NRF_MPU_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_MPU_CONFIG_INFO_COLOR
#define NRF_MPU_CONFIG_INFO_COLOR 0
#endif


// <o> NRF_MPU_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_MPU_CONFIG_DEBUG_COLOR
#define NRF_MPU_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_STACK_GUARD_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef NRF_STACK_GUARD_CONFIG_LOG_ENABLED
#define NRF_STACK_GUARD_CONFIG_LOG_ENABLED 0
#endif
// <o> NRF_STACK_GUARD_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_STACK_GUARD_CONFIG_LOG_LEVEL
#define NRF_STACK_GUARD_CONFIG_LOG_LEVEL 3
#endif


// <o> NRF_STACK_GUARD_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_STACK_GUARD_CONFIG_INFO_COLOR
#define NRF_STACK_GUARD_CONFIG_INFO_COLOR 0
#endif


// <o> NRF_STACK_GUARD_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_STACK_GUARD_CONFIG_DEBUG_COLOR
#define NRF_STACK_GUARD_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> TASK_MANAGER_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef TASK_MANAGER_CONFIG_LOG_ENABLED
#define TASK_MANAGER_CONFIG_LOG_ENABLED 0
#endif
// <o> TASK_MANAGER_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef TASK_MANAGER_CONFIG_LOG_LEVEL
#define TASK_MANAGER_CONFIG_LOG_LEVEL 3
#endif


// <o> TASK_MANAGER_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef TASK_MANAGER_CONFIG_INFO_COLOR
#define TASK_MANAGER_CONFIG_INFO_COLOR 0
#endif


// <o> TASK_MANAGER_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef TASK_MANAGER_CONFIG_DEBUG_COLOR
#define TASK_MANAGER_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// </h> 
//==========================================================


// <h> nrf_log in nRF_Drivers 


//==========================================================
// <e> CLOCK_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef CLOCK_CONFIG_LOG_ENABLED
#define CLOCK_CONFIG_LOG_ENABLED 0
#endif
// <o> CLOCK_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef CLOCK_CONFIG_LOG_LEVEL
#define CLOCK_CONFIG_LOG_LEVEL 3
#endif


// <o> CLOCK_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef CLOCK_CONFIG_INFO_COLOR
#define CLOCK_CONFIG_INFO_COLOR 0
#endif


// <o> CLOCK_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef CLOCK_CONFIG_DEBUG_COLOR
#define CLOCK_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> COMMON_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef COMMON_CONFIG_LOG_ENABLED
#define COMMON_CONFIG_LOG_ENABLED 0
#endif
// <o> COMMON_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef COMMON_CONFIG_LOG_LEVEL
#define COMMON_CONFIG_LOG_LEVEL 3
#endif


// <o> COMMON_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef COMMON_CONFIG_INFO_COLOR
#define COMMON_CONFIG_INFO_COLOR 0
#endif


// <o> COMMON_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef COMMON_CONFIG_DEBUG_COLOR
#define COMMON_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> COMP_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef COMP_CONFIG_LOG_ENABLED
#define COMP_CONFIG_LOG_ENABLED 0
#endif
// <o> COMP_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef COMP_CONFIG_LOG_LEVEL
#define COMP_CONFIG_LOG_LEVEL 3
#endif


// <o> COMP_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef COMP_CONFIG_INFO_COLOR
#define COMP_CONFIG_INFO_COLOR 0
#endif


// <o> COMP_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef COMP_CONFIG_DEBUG_COLOR
#define COMP_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> GPIOTE_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef GPIOTE_CONFIG_LOG_ENABLED
#define GPIOTE_CONFIG_LOG_ENABLED 0
#endif
// <o> GPIOTE_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef GPIOTE_CONFIG_LOG_LEVEL
#define GPIOTE_CONFIG_LOG_LEVEL 3
#endif


// <o> GPIOTE_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef GPIOTE_CONFIG_INFO_COLOR
#define GPIOTE_CONFIG_INFO_COLOR 0
#endif


// <o> GPIOTE_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef GPIOTE_CONFIG_DEBUG_COLOR
#define GPIOTE_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> I2S_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef I2S_CONFIG_LOG_ENABLED
#define I2S_CONFIG_LOG_ENABLED 0
#endif
// <o> I2S_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef I2S_CONFIG_LOG_LEVEL
#define I2S_CONFIG_LOG_LEVEL 3
#endif


// <o> I2S_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef I2S_CONFIG_INFO_COLOR
#define I2S_CONFIG_INFO_COLOR 0
#endif


// <o> I2S_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef I2S_CONFIG_DEBUG_COLOR
#define I2S_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> LPCOMP_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef LPCOMP_CONFIG_LOG_ENABLED
#define LPCOMP_CONFIG_LOG_ENABLED 0
#endif
// <o> LPCOMP_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef LPCOMP_CONFIG_LOG_LEVEL
#define LPCOMP_CONFIG_LOG_LEVEL 3
#endif


// <o> LPCOMP_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef LPCOMP_CONFIG_INFO_COLOR
#define LPCOMP_CONFIG_INFO_COLOR 0
#endif


// <o> LPCOMP_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef LPCOMP_CONFIG_DEBUG_COLOR
#define LPCOMP_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> PDM_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef PDM_CONFIG_LOG_ENABLED
#define PDM_CONFIG_LOG_ENABLED 0
#endif
// <o> PDM_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef PDM_CONFIG_LOG_LEVEL
#define PDM_CONFIG_LOG_LEVEL 3
#endif


// <o> PDM_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef PDM_CONFIG_INFO_COLOR
#define PDM_CONFIG_INFO_COLOR 0
#endif


// <o> PDM_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef PDM_CONFIG_DEBUG_COLOR
#define PDM_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> PPI_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef PPI_CONFIG_LOG_ENABLED
#define PPI_CONFIG_LOG_ENABLED 0
#endif
// <o> PPI_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef PPI_CONFIG_LOG_LEVEL
#define PPI_CONFIG_LOG_LEVEL 3
#endif


// <o> PPI_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef PPI_CONFIG_INFO_COLOR
#define PPI_CONFIG_INFO_COLOR 0
#endif


// <o> PPI_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef PPI_CONFIG_DEBUG_COLOR
#define PPI_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> PWM_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef PWM_CONFIG_LOG_ENABLED
#define PWM_CONFIG_LOG_ENABLED 0
#endif
// <o> PWM_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef PWM_CONFIG_LOG_LEVEL
#define PWM_CONFIG_LOG_LEVEL 3
#endif


// <o> PWM_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef PWM_CONFIG_INFO_COLOR
#define PWM_CONFIG_INFO_COLOR 0
#endif


// <o> PWM_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef PWM_CONFIG_DEBUG_COLOR
#define PWM_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> QDEC_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef QDEC_CONFIG_LOG_ENABLED
#define QDEC_CONFIG_LOG_ENABLED 0
#endif
// <o> QDEC_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef QDEC_CONFIG_LOG_LEVEL
#define QDEC_CONFIG_LOG_LEVEL 3
#endif


// <o> QDEC_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef QDEC_CONFIG_INFO_COLOR
#define QDEC_CONFIG_INFO_COLOR 0
#endif


// <o> QDEC_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef QDEC_CONFIG_DEBUG_COLOR
#define QDEC_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> RNG_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef RNG_CONFIG_LOG_ENABLED
#define RNG_CONFIG_LOG_ENABLED 0
#endif
// <o> RNG_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef RNG_CONFIG_LOG_LEVEL
#define RNG_CONFIG_LOG_LEVEL 3
#endif


// <o> RNG_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef RNG_CONFIG_INFO_COLOR
#define RNG_CONFIG_INFO_COLOR 0
#endif


// <o> RNG_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef RNG_CONFIG_DEBUG_COLOR
#define RNG_CONFIG_DEBUG_COLOR 0
#endif


// <q> RNG_CONFIG_RANDOM_NUMBER_LOG_ENABLED  - Enables logging of random numbers.
 


#ifndef RNG_CONFIG_RANDOM_NUMBER_LOG_ENABLED
#define RNG_CONFIG_RANDOM_NUMBER_LOG_ENABLED 0
#endif


// </e>


// <e> RTC_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef RTC_CONFIG_LOG_ENABLED
#define RTC_CONFIG_LOG_ENABLED 0
#endif
// <o> RTC_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef RTC_CONFIG_LOG_LEVEL
#define RTC_CONFIG_LOG_LEVEL 3
#endif


// <o> RTC_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef RTC_CONFIG_INFO_COLOR
#define RTC_CONFIG_INFO_COLOR 0
#endif


// <o> RTC_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef RTC_CONFIG_DEBUG_COLOR
#define RTC_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> SAADC_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef SAADC_CONFIG_LOG_ENABLED
#define SAADC_CONFIG_LOG_ENABLED 0
#endif
// <o> SAADC_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef SAADC_CONFIG_LOG_LEVEL
#define SAADC_CONFIG_LOG_LEVEL 3
#endif


// <o> SAADC_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef SAADC_CONFIG_INFO_COLOR
#define SAADC_CONFIG_INFO_COLOR 0
#endif


// <o> SAADC_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef SAADC_CONFIG_DEBUG_COLOR
#define SAADC_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> SPIS_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef SPIS_CONFIG_LOG_ENABLED
#define SPIS_CONFIG_LOG_ENABLED 0
#endif
// <o> SPIS_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef SPIS_CONFIG_LOG_LEVEL
#define SPIS_CONFIG_LOG_LEVEL 3
#endif


// <o> SPIS_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef SPIS_CONFIG_INFO_COLOR
#define SPIS_CONFIG_INFO_COLOR 0
#endif


// <o> SPIS_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef SPIS_CONFIG_DEBUG_COLOR
#define SPIS_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> SPI_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef SPI_CONFIG_LOG_ENABLED
#define SPI_CONFIG_LOG_ENABLED 0
#endif
// <o> SPI_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef SPI_CONFIG_LOG_LEVEL
#define SPI_CONFIG_LOG_LEVEL 3
#endif


// <o> SPI_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef SPI_CONFIG_INFO_COLOR
#define SPI_CONFIG_INFO_COLOR 0
#endif


// <o> SPI_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef SPI_CONFIG_DEBUG_COLOR
#define SPI_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> SWI_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef SWI_CONFIG_LOG_ENABLED
#define SWI_CONFIG_LOG_ENABLED 0
#endif
// <o> SWI_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef SWI_CONFIG_LOG_LEVEL
#define SWI_CONFIG_LOG_LEVEL 3
#endif


// <o> SWI_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef SWI_CONFIG_INFO_COLOR
#define SWI_CONFIG_INFO_COLOR 0
#endif


// <o> SWI_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef SWI_CONFIG_DEBUG_COLOR
#define SWI_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> TIMER_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef TIMER_CONFIG_LOG_ENABLED
#define TIMER_CONFIG_LOG_ENABLED 0
#endif
// <o> TIMER_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef TIMER_CONFIG_LOG_LEVEL
#define TIMER_CONFIG_LOG_LEVEL 3
#endif


// <o> TIMER_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef TIMER_CONFIG_INFO_COLOR
#define TIMER_CONFIG_INFO_COLOR 0
#endif


// <o> TIMER_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef TIMER_CONFIG_DEBUG_COLOR
#define TIMER_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> TWIS_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef TWIS_CONFIG_LOG_ENABLED
#define TWIS_CONFIG_LOG_ENABLED 0
#endif
// <o> TWIS_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef TWIS_CONFIG_LOG_LEVEL
#define TWIS_CONFIG_LOG_LEVEL 3
#endif


// <o> TWIS_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef TWIS_CONFIG_INFO_COLOR
#define TWIS_CONFIG_INFO_COLOR 0
#endif


// <o> TWIS_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef TWIS_CONFIG_DEBUG_COLOR
#define TWIS_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> TWI_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef TWI_CONFIG_LOG_ENABLED
#define TWI_CONFIG_LOG_ENABLED 0
#endif
// <o> TWI_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef TWI_CONFIG_LOG_LEVEL
#define TWI_CONFIG_LOG_LEVEL 3
#endif


// <o> TWI_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef TWI_CONFIG_INFO_COLOR
#define TWI_CONFIG_INFO_COLOR 0
#endif


// <o> TWI_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef TWI_CONFIG_DEBUG_COLOR
#define TWI_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> UART_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef UART_CONFIG_LOG_ENABLED
#define UART_CONFIG_LOG_ENABLED 0
#endif
// <o> UART_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef UART_CONFIG_LOG_LEVEL
#define UART_CONFIG_LOG_LEVEL 3
#endif


// <o> UART_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef UART_CONFIG_INFO_COLOR
#define UART_CONFIG_INFO_COLOR 0
#endif


// <o> UART_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef UART_CONFIG_DEBUG_COLOR
#define UART_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> USBD_CONFIG_LOG_ENABLED - Enable logging in the module
//==========================================================
#ifndef USBD_CONFIG_LOG_ENABLED
#define USBD_CONFIG_LOG_ENABLED 0
#endif
// <o> USBD_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef USBD_CONFIG_LOG_LEVEL
#define USBD_CONFIG_LOG_LEVEL 3
#endif


// <o> USBD_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef USBD_CONFIG_INFO_COLOR
#define USBD_CONFIG_INFO_COLOR 0
#endif


// <o> USBD_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef USBD_CONFIG_DEBUG_COLOR
#define USBD_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> WDT_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef WDT_CONFIG_LOG_ENABLED
#define WDT_CONFIG_LOG_ENABLED 0
#endif
// <o> WDT_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef WDT_CONFIG_LOG_LEVEL
#define WDT_CONFIG_LOG_LEVEL 3
#endif


// <o> WDT_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef WDT_CONFIG_INFO_COLOR
#define WDT_CONFIG_INFO_COLOR 0
#endif


// <o> WDT_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef WDT_CONFIG_DEBUG_COLOR
#define WDT_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// </h> 
//==========================================================


// <h> nrf_log in nRF_Libraries 


//==========================================================
// <e> APP_USBD_CDC_ACM_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef APP_USBD_CDC_ACM_CONFIG_LOG_ENABLED
#define APP_USBD_CDC_ACM_CONFIG_LOG_ENABLED 0
#endif
// <o> APP_USBD_CDC_ACM_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef APP_USBD_CDC_ACM_CONFIG_LOG_LEVEL
#define APP_USBD_CDC_ACM_CONFIG_LOG_LEVEL 3
#endif


// <o> APP_USBD_CDC_ACM_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef APP_USBD_CDC_ACM_CONFIG_INFO_COLOR
#define APP_USBD_CDC_ACM_CONFIG_INFO_COLOR 0
#endif


// <o> APP_USBD_CDC_ACM_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef APP_USBD_CDC_ACM_CONFIG_DEBUG_COLOR
#define APP_USBD_CDC_ACM_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> APP_USBD_MSC_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef APP_USBD_MSC_CONFIG_LOG_ENABLED
#define APP_USBD_MSC_CONFIG_LOG_ENABLED 0
#endif
// <o> APP_USBD_MSC_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef APP_USBD_MSC_CONFIG_LOG_LEVEL
#define APP_USBD_MSC_CONFIG_LOG_LEVEL 3
#endif


// <o> APP_USBD_MSC_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef APP_USBD_MSC_CONFIG_INFO_COLOR
#define APP_USBD_MSC_CONFIG_INFO_COLOR 0
#endif


// <o> APP_USBD_MSC_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef APP_USBD_MSC_CONFIG_DEBUG_COLOR
#define APP_USBD_MSC_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_BALLOC_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef NRF_BALLOC_CONFIG_LOG_ENABLED
#define NRF_BALLOC_CONFIG_LOG_ENABLED 0
#endif
// <o> NRF_BALLOC_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_BALLOC_CONFIG_LOG_LEVEL
#define NRF_BALLOC_CONFIG_LOG_LEVEL 3
#endif


// <o> NRF_BALLOC_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_BALLOC_CONFIG_INFO_COLOR
#define NRF_BALLOC_CONFIG_INFO_COLOR 0
#endif


// <o> NRF_BALLOC_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_BALLOC_CONFIG_DEBUG_COLOR
#define NRF_BALLOC_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_CLI_BLE_UART_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef NRF_CLI_BLE_UART_CONFIG_LOG_ENABLED
#define NRF_CLI_BLE_UART_CONFIG_LOG_ENABLED 0
#endif
// <o> NRF_CLI_BLE_UART_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_CLI_BLE_UART_CONFIG_LOG_LEVEL
#define NRF_CLI_BLE_UART_CONFIG_LOG_LEVEL 3
#endif


// <o> NRF_CLI_BLE_UART_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_CLI_BLE_UART_CONFIG_INFO_COLOR
#define NRF_CLI_BLE_UART_CONFIG_INFO_COLOR 0
#endif


// <o> NRF_CLI_BLE_UART_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_CLI_BLE_UART_CONFIG_DEBUG_COLOR
#define NRF_CLI_BLE_UART_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_CLI_UART_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef NRF_CLI_UART_CONFIG_LOG_ENABLED
#define NRF_CLI_UART_CONFIG_LOG_ENABLED 0
#endif
// <o> NRF_CLI_UART_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_CLI_UART_CONFIG_LOG_LEVEL
#define NRF_CLI_UART_CONFIG_LOG_LEVEL 3
#endif


// <o> NRF_CLI_UART_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_CLI_UART_CONFIG_INFO_COLOR
#define NRF_CLI_UART_CONFIG_INFO_COLOR 0
#endif


// <o> NRF_CLI_UART_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_CLI_UART_CONFIG_DEBUG_COLOR
#define NRF_CLI_UART_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_MEMOBJ_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef NRF_MEMOBJ_CONFIG_LOG_ENABLED
#define NRF_MEMOBJ_CONFIG_LOG_ENABLED 0
#endif
// <o> NRF_MEMOBJ_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_MEMOBJ_CONFIG_LOG_LEVEL
#define NRF_MEMOBJ_CONFIG_LOG_LEVEL 3
#endif


// <o> NRF_MEMOBJ_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_MEMOBJ_CONFIG_INFO_COLOR
#define NRF_MEMOBJ_CONFIG_INFO_COLOR 0
#endif


// <o> NRF_MEMOBJ_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_MEMOBJ_CONFIG_DEBUG_COLOR
#define NRF_MEMOBJ_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_PWR_MGMT_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef NRF_PWR_MGMT_CONFIG_LOG_ENABLED
#define NRF_PWR_MGMT_CONFIG_LOG_ENABLED 0
#endif
// <o> NRF_PWR_MGMT_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_PWR_MGMT_CONFIG_LOG_LEVEL
#define NRF_PWR_MGMT_CONFIG_LOG_LEVEL 3
#endif


// <o> NRF_PWR_MGMT_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_PWR_MGMT_CONFIG_INFO_COLOR
#define NRF_PWR_MGMT_CONFIG_INFO_COLOR 0
#endif


// <o> NRF_PWR_MGMT_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_PWR_MGMT_CONFIG_DEBUG_COLOR
#define NRF_PWR_MGMT_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_SDH_ANT_LOG_ENABLED - Enable logging in SoftDevice handler (ANT) module.
//==========================================================
#ifndef NRF_SDH_ANT_LOG_ENABLED
#define NRF_SDH_ANT_LOG_ENABLED 0
#endif
// <o> NRF_SDH_ANT_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_SDH_ANT_LOG_LEVEL
#define NRF_SDH_ANT_LOG_LEVEL 3
#endif


// <o> NRF_SDH_ANT_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SDH_ANT_INFO_COLOR
#define NRF_SDH_ANT_INFO_COLOR 0
#endif


// <o> NRF_SDH_ANT_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SDH_ANT_DEBUG_COLOR
#define NRF_SDH_ANT_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_SDH_BLE_LOG_ENABLED - Enable logging in SoftDevice handler (BLE) module.
//==========================================================
#ifndef NRF_SDH_BLE_LOG_ENABLED
#define NRF_SDH_BLE_LOG_ENABLED 1
#endif
// <o> NRF_SDH_BLE_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_SDH_BLE_LOG_LEVEL
#define NRF_SDH_BLE_LOG_LEVEL 3
#endif


// <o> NRF_SDH_BLE_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SDH_BLE_INFO_COLOR
#define NRF_SDH_BLE_INFO_COLOR 0
#endif


// <o> NRF_SDH_BLE_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SDH_BLE_DEBUG_COLOR
#define NRF_SDH_BLE_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_SDH_LOG_ENABLED - Enable logging in SoftDevice handler module.
//==========================================================
#ifndef NRF_SDH_LOG_ENABLED
#define NRF_SDH_LOG_ENABLED 1
#endif
// <o> NRF_SDH_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_SDH_LOG_LEVEL
#define NRF_SDH_LOG_LEVEL 3
#endif


// <o> NRF_SDH_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SDH_INFO_COLOR
#define NRF_SDH_INFO_COLOR 0
#endif


// <o> NRF_SDH_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SDH_DEBUG_COLOR
#define NRF_SDH_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_SDH_SOC_LOG_ENABLED - Enable logging in SoftDevice handler (SoC) module.
//==========================================================
#ifndef NRF_SDH_SOC_LOG_ENABLED
#define NRF_SDH_SOC_LOG_ENABLED 1
#endif
// <o> NRF_SDH_SOC_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_SDH_SOC_LOG_LEVEL
#define NRF_SDH_SOC_LOG_LEVEL 3
#endif


// <o> NRF_SDH_SOC_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SDH_SOC_INFO_COLOR
#define NRF_SDH_SOC_INFO_COLOR 0
#endif


// <o> NRF_SDH_SOC_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SDH_SOC_DEBUG_COLOR
#define NRF_SDH_SOC_DEBUG_COLOR 0
#endif


// </e>


// <e> NRF_SORTLIST_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef NRF_SORTLIST_CONFIG_LOG_ENABLED
#define NRF_SORTLIST_CONFIG_LOG_ENABLED 0
#endif
// <o> NRF_SORTLIST_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 


#ifndef NRF_SORTLIST_CONFIG_LOG_LEVEL
#define NRF_SORTLIST_CONFIG_LOG_LEVEL 3
#endif


// <o> NRF_SORTLIST_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SORTLIST_CONFIG_INFO_COLOR
#define NRF_SORTLIST_CONFIG_INFO_COLOR 0
#endif


// <o> NRF_SORTLIST_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 


#ifndef NRF_SORTLIST_CONFIG_DEBUG_COLOR
#define NRF_SORTLIST_CONFIG_DEBUG_COLOR 0
#endif


// </e>


// </h> 
//==========================================================


// </h> 
//==========================================================


// </h> 
//==========================================================


// </h> 
//==========================================================


// <h> nRF_Segger_RTT 


//==========================================================
// <h> segger_rtt - SEGGER RTT


//==========================================================
// <o> SEGGER_RTT_CONFIG_BUFFER_SIZE_UP - Size of upstream buffer. 
// <i> Note that either @ref NRF_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE
// <i> or this value is actually used. It depends on which one is bigger.


#ifndef SEGGER_RTT_CONFIG_BUFFER_SIZE_UP
#define SEGGER_RTT_CONFIG_BUFFER_SIZE_UP 512
#endif


// <o> SEGGER_RTT_CONFIG_MAX_NUM_UP_BUFFERS - Size of upstream buffer. 
#ifndef SEGGER_RTT_CONFIG_MAX_NUM_UP_BUFFERS
#define SEGGER_RTT_CONFIG_MAX_NUM_UP_BUFFERS 2
#endif


// <o> SEGGER_RTT_CONFIG_BUFFER_SIZE_DOWN - Size of upstream buffer. 
#ifndef SEGGER_RTT_CONFIG_BUFFER_SIZE_DOWN
#define SEGGER_RTT_CONFIG_BUFFER_SIZE_DOWN 16
#endif


// <o> SEGGER_RTT_CONFIG_MAX_NUM_DOWN_BUFFERS - Size of upstream buffer. 
#ifndef SEGGER_RTT_CONFIG_MAX_NUM_DOWN_BUFFERS
#define SEGGER_RTT_CONFIG_MAX_NUM_DOWN_BUFFERS 2
#endif


// <o> SEGGER_RTT_CONFIG_DEFAULT_MODE  - RTT behavior if the buffer is full.
 


// <i> The following modes are supported:
// <i> - SKIP  - Do not block, output nothing.
// <i> - TRIM  - Do not block, output as much as fits.
// <i> - BLOCK - Wait until there is space in the buffer.
// <0=> SKIP 
// <1=> TRIM 
// <2=> BLOCK_IF_FIFO_FULL 


#ifndef SEGGER_RTT_CONFIG_DEFAULT_MODE
#define SEGGER_RTT_CONFIG_DEFAULT_MODE 0
#endif


// </h> 
//==========================================================


// </h> 
//==========================================================


// <h> nRF_SoftDevice 


//==========================================================
// <e> NRF_SDH_BLE_ENABLED - nrf_sdh_ble - SoftDevice BLE event handler
//==========================================================
#ifndef NRF_SDH_BLE_ENABLED
#define NRF_SDH_BLE_ENABLED 1
#endif
// <h> BLE Stack configuration - Stack configuration parameters


// <i> These values are not used directly by the SoftDevice handler but the application or other libraries might depend on them.
// <i> Keep them up-to-date with the desired configuration.
//==========================================================
// <o> NRF_SDH_BLE_PERIPHERAL_LINK_COUNT - Maximum number of peripheral links. 
#ifndef NRF_SDH_BLE_PERIPHERAL_LINK_COUNT
#define NRF_SDH_BLE_PERIPHERAL_LINK_COUNT 1
#endif


// <o> NRF_SDH_BLE_CENTRAL_LINK_COUNT - Maximum number of central links. 
#ifndef NRF_SDH_BLE_CENTRAL_LINK_COUNT
#define NRF_SDH_BLE_CENTRAL_LINK_COUNT 0
#endif


// <o> NRF_SDH_BLE_TOTAL_LINK_COUNT - Maximum number of total concurrent connections using the default configuration. 
#ifndef NRF_SDH_BLE_TOTAL_LINK_COUNT
#define NRF_SDH_BLE_TOTAL_LINK_COUNT 1
#endif


// <o> NRF_SDH_BLE_GAP_EVENT_LENGTH - The time set aside for this connection on every connection interval in 1.25 ms units. 
#ifndef NRF_SDH_BLE_GAP_EVENT_LENGTH
#define NRF_SDH_BLE_GAP_EVENT_LENGTH 3
#endif


// <o> NRF_SDH_BLE_GATT_MAX_MTU_SIZE - Static maximum MTU size. 
#ifndef NRF_SDH_BLE_GATT_MAX_MTU_SIZE
#define NRF_SDH_BLE_GATT_MAX_MTU_SIZE 247
#endif


// <o> NRF_SDH_BLE_GATTS_ATTR_TAB_SIZE - Attribute Table size in bytes. The size must be a multiple of 4. 
#ifndef NRF_SDH_BLE_GATTS_ATTR_TAB_SIZE
#define NRF_SDH_BLE_GATTS_ATTR_TAB_SIZE 1408
#endif


// <o> NRF_SDH_BLE_VS_UUID_COUNT - The number of vendor-specific UUIDs. 
#ifndef NRF_SDH_BLE_VS_UUID_COUNT
#define NRF_SDH_BLE_VS_UUID_COUNT 1
#endif


// <q> NRF_SDH_BLE_SERVICE_CHANGED  - Include the Service Changed characteristic in the Attribute Table.
 


#ifndef NRF_SDH_BLE_SERVICE_CHANGED
#define NRF_SDH_BLE_SERVICE_CHANGED 0
#endif


// </h> 
//==========================================================


// <h> BLE Observers - Observers and priority levels


//==========================================================
// <o> NRF_SDH_BLE_OBSERVER_PRIO_LEVELS - Total number of priority levels for BLE observers. 
// <i> This setting configures the number of priority levels available for BLE event handlers.
// <i> The priority level of a handler determines the order in which it receives events, with respect to other handlers.


#ifndef NRF_SDH_BLE_OBSERVER_PRIO_LEVELS
#define NRF_SDH_BLE_OBSERVER_PRIO_LEVELS 4
#endif


// <h> BLE Observers priorities - Invididual priorities


//==========================================================
// <o> BLE_ADV_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Advertising module.


#ifndef BLE_ADV_BLE_OBSERVER_PRIO
#define BLE_ADV_BLE_OBSERVER_PRIO 1
#endif


// <o> BLE_ANCS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Apple Notification Service Client.


#ifndef BLE_ANCS_C_BLE_OBSERVER_PRIO
#define BLE_ANCS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_ANS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Alert Notification Service Client.


#ifndef BLE_ANS_C_BLE_OBSERVER_PRIO
#define BLE_ANS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_BAS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Battery Service.


#ifndef BLE_BAS_BLE_OBSERVER_PRIO
#define BLE_BAS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_BAS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Battery Service Client.


#ifndef BLE_BAS_C_BLE_OBSERVER_PRIO
#define BLE_BAS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_BPS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Blood Pressure Service.


#ifndef BLE_BPS_BLE_OBSERVER_PRIO
#define BLE_BPS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_CONN_PARAMS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Connection parameters module.


#ifndef BLE_CONN_PARAMS_BLE_OBSERVER_PRIO
#define BLE_CONN_PARAMS_BLE_OBSERVER_PRIO 1
#endif


// <o> BLE_CONN_STATE_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Connection State module.


#ifndef BLE_CONN_STATE_BLE_OBSERVER_PRIO
#define BLE_CONN_STATE_BLE_OBSERVER_PRIO 0
#endif


// <o> BLE_CSCS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Cycling Speed and Cadence Service.


#ifndef BLE_CSCS_BLE_OBSERVER_PRIO
#define BLE_CSCS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_CTS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Current Time Service Client.


#ifndef BLE_CTS_C_BLE_OBSERVER_PRIO
#define BLE_CTS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_DB_DISC_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Database Discovery module.


#ifndef BLE_DB_DISC_BLE_OBSERVER_PRIO
#define BLE_DB_DISC_BLE_OBSERVER_PRIO 1
#endif


// <o> BLE_DFU_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the DFU Service.


#ifndef BLE_DFU_BLE_OBSERVER_PRIO
#define BLE_DFU_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_GLS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Glucose Service.


#ifndef BLE_GLS_BLE_OBSERVER_PRIO
#define BLE_GLS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_HIDS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Human Interface Device Service.


#ifndef BLE_HIDS_BLE_OBSERVER_PRIO
#define BLE_HIDS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_HRS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Heart Rate Service.


#ifndef BLE_HRS_BLE_OBSERVER_PRIO
#define BLE_HRS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_HRS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Heart Rate Service Client.


#ifndef BLE_HRS_C_BLE_OBSERVER_PRIO
#define BLE_HRS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_HTS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Health Thermometer Service.


#ifndef BLE_HTS_BLE_OBSERVER_PRIO
#define BLE_HTS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_IAS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Immediate Alert Service.


#ifndef BLE_IAS_BLE_OBSERVER_PRIO
#define BLE_IAS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_IAS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Immediate Alert Service Client.


#ifndef BLE_IAS_C_BLE_OBSERVER_PRIO
#define BLE_IAS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_LBS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the LED Button Service.


#ifndef BLE_LBS_BLE_OBSERVER_PRIO
#define BLE_LBS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_LBS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the LED Button Service Client.


#ifndef BLE_LBS_C_BLE_OBSERVER_PRIO
#define BLE_LBS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_LLS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Link Loss Service.


#ifndef BLE_LLS_BLE_OBSERVER_PRIO
#define BLE_LLS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_LNS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Location Navigation Service.


#ifndef BLE_LNS_BLE_OBSERVER_PRIO
#define BLE_LNS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_NUS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the UART Service.


#ifndef BLE_NUS_BLE_OBSERVER_PRIO
#define BLE_NUS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_NUS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the UART Central Service.


#ifndef BLE_NUS_C_BLE_OBSERVER_PRIO
#define BLE_NUS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_OTS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Object transfer service.


#ifndef BLE_OTS_BLE_OBSERVER_PRIO
#define BLE_OTS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_OTS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Object transfer service client.


#ifndef BLE_OTS_C_BLE_OBSERVER_PRIO
#define BLE_OTS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_RSCS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Running Speed and Cadence Service.


#ifndef BLE_RSCS_BLE_OBSERVER_PRIO
#define BLE_RSCS_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_RSCS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Running Speed and Cadence Client.


#ifndef BLE_RSCS_C_BLE_OBSERVER_PRIO
#define BLE_RSCS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> BLE_TPS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the TX Power Service.


#ifndef BLE_TPS_BLE_OBSERVER_PRIO
#define BLE_TPS_BLE_OBSERVER_PRIO 2
#endif


// <o> BSP_BTN_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Button Control module.


#ifndef BSP_BTN_BLE_OBSERVER_PRIO
#define BSP_BTN_BLE_OBSERVER_PRIO 1
#endif


// <o> NFC_BLE_PAIR_LIB_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the NFC pairing library.


#ifndef NFC_BLE_PAIR_LIB_BLE_OBSERVER_PRIO
#define NFC_BLE_PAIR_LIB_BLE_OBSERVER_PRIO 1
#endif


// <o> NRF_BLE_BMS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Bond Management Service.


#ifndef NRF_BLE_BMS_BLE_OBSERVER_PRIO
#define NRF_BLE_BMS_BLE_OBSERVER_PRIO 2
#endif


// <o> NRF_BLE_CGMS_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Contiuon Glucose Monitoring Service.


#ifndef NRF_BLE_CGMS_BLE_OBSERVER_PRIO
#define NRF_BLE_CGMS_BLE_OBSERVER_PRIO 2
#endif


// <o> NRF_BLE_ES_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Eddystone module.


#ifndef NRF_BLE_ES_BLE_OBSERVER_PRIO
#define NRF_BLE_ES_BLE_OBSERVER_PRIO 2
#endif


// <o> NRF_BLE_GATTS_C_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the GATT Service Client.


#ifndef NRF_BLE_GATTS_C_BLE_OBSERVER_PRIO
#define NRF_BLE_GATTS_C_BLE_OBSERVER_PRIO 2
#endif


// <o> NRF_BLE_GATT_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the GATT module.


#ifndef NRF_BLE_GATT_BLE_OBSERVER_PRIO
#define NRF_BLE_GATT_BLE_OBSERVER_PRIO 1
#endif


// <o> NRF_BLE_QWR_BLE_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the Queued writes module.


#ifndef NRF_BLE_QWR_BLE_OBSERVER_PRIO
#define NRF_BLE_QWR_BLE_OBSERVER_PRIO 2
#endif


// <o> PM_BLE_OBSERVER_PRIO - Priority with which BLE events are dispatched to the Peer Manager module. 
#ifndef PM_BLE_OBSERVER_PRIO
#define PM_BLE_OBSERVER_PRIO 1
#endif


// </h> 
//==========================================================


// </h> 
//==========================================================




// </e>


// <e> NRF_SDH_ENABLED - nrf_sdh - SoftDevice handler
//==========================================================
#ifndef NRF_SDH_ENABLED
#define NRF_SDH_ENABLED 1
#endif
// <h> Dispatch model 


// <i> This setting configures how Stack events are dispatched to the application.
//==========================================================
// <o> NRF_SDH_DISPATCH_MODEL
 


// <i> NRF_SDH_DISPATCH_MODEL_INTERRUPT: SoftDevice events are passed to the application from the interrupt context.
// <i> NRF_SDH_DISPATCH_MODEL_APPSH: SoftDevice events are scheduled using @ref app_scheduler.
// <i> NRF_SDH_DISPATCH_MODEL_POLLING: SoftDevice events are to be fetched manually.
// <0=> NRF_SDH_DISPATCH_MODEL_INTERRUPT 
// <1=> NRF_SDH_DISPATCH_MODEL_APPSH 
// <2=> NRF_SDH_DISPATCH_MODEL_POLLING 


#ifndef NRF_SDH_DISPATCH_MODEL
#define NRF_SDH_DISPATCH_MODEL 0
#endif


// </h> 
//==========================================================


// <h> Clock - SoftDevice clock configuration


//==========================================================
// <o> NRF_SDH_CLOCK_LF_SRC  - SoftDevice clock source.
 
// <0=> NRF_CLOCK_LF_SRC_RC 
// <1=> NRF_CLOCK_LF_SRC_XTAL 
// <2=> NRF_CLOCK_LF_SRC_SYNTH 


#ifndef NRF_SDH_CLOCK_LF_SRC
#define NRF_SDH_CLOCK_LF_SRC 1
#endif


// <o> NRF_SDH_CLOCK_LF_RC_CTIV - SoftDevice calibration timer interval. 
#ifndef NRF_SDH_CLOCK_LF_RC_CTIV
#define NRF_SDH_CLOCK_LF_RC_CTIV 0
#endif


// <o> NRF_SDH_CLOCK_LF_RC_TEMP_CTIV - SoftDevice calibration timer interval under constant temperature. 
// <i> How often (in number of calibration intervals) the RC oscillator shall be calibrated
// <i>  if the temperature has not changed.


#ifndef NRF_SDH_CLOCK_LF_RC_TEMP_CTIV
#define NRF_SDH_CLOCK_LF_RC_TEMP_CTIV 0
#endif


// <o> NRF_SDH_CLOCK_LF_XTAL_ACCURACY  - External crystal clock accuracy used in the LL to compute timing windows.
 
// <0=> NRF_CLOCK_LF_XTAL_ACCURACY_250_PPM 
// <1=> NRF_CLOCK_LF_XTAL_ACCURACY_500_PPM 
// <2=> NRF_CLOCK_LF_XTAL_ACCURACY_150_PPM 
// <3=> NRF_CLOCK_LF_XTAL_ACCURACY_100_PPM 
// <4=> NRF_CLOCK_LF_XTAL_ACCURACY_75_PPM 
// <5=> NRF_CLOCK_LF_XTAL_ACCURACY_50_PPM 
// <6=> NRF_CLOCK_LF_XTAL_ACCURACY_30_PPM 
// <7=> NRF_CLOCK_LF_XTAL_ACCURACY_20_PPM 


#ifndef NRF_SDH_CLOCK_LF_XTAL_ACCURACY
#define NRF_SDH_CLOCK_LF_XTAL_ACCURACY 7
#endif


// </h> 
//==========================================================


// <h> SDH Observers - Observers and priority levels


//==========================================================
// <o> NRF_SDH_REQ_OBSERVER_PRIO_LEVELS - Total number of priority levels for request observers. 
// <i> This setting configures the number of priority levels available for the SoftDevice request event handlers.
// <i> The priority level of a handler determines the order in which it receives events, with respect to other handlers.


#ifndef NRF_SDH_REQ_OBSERVER_PRIO_LEVELS
#define NRF_SDH_REQ_OBSERVER_PRIO_LEVELS 2
#endif


// <o> NRF_SDH_STATE_OBSERVER_PRIO_LEVELS - Total number of priority levels for state observers. 
// <i> This setting configures the number of priority levels available for the SoftDevice state event handlers.
// <i> The priority level of a handler determines the order in which it receives events, with respect to other handlers.


#ifndef NRF_SDH_STATE_OBSERVER_PRIO_LEVELS
#define NRF_SDH_STATE_OBSERVER_PRIO_LEVELS 2
#endif


// <o> NRF_SDH_STACK_OBSERVER_PRIO_LEVELS - Total number of priority levels for stack event observers. 
// <i> This setting configures the number of priority levels available for the SoftDevice stack event handlers (ANT, BLE, SoC).
// <i> The priority level of a handler determines the order in which it receives events, with respect to other handlers.


#ifndef NRF_SDH_STACK_OBSERVER_PRIO_LEVELS
#define NRF_SDH_STACK_OBSERVER_PRIO_LEVELS 2
#endif




// <h> State Observers priorities - Invididual priorities


//==========================================================
// <o> CLOCK_CONFIG_STATE_OBSERVER_PRIO  
// <i> Priority with which state events are dispatched to the Clock driver.


#ifndef CLOCK_CONFIG_STATE_OBSERVER_PRIO
#define CLOCK_CONFIG_STATE_OBSERVER_PRIO 0
#endif


// <o> POWER_CONFIG_STATE_OBSERVER_PRIO  
// <i> Priority with which state events are dispatched to the Power driver.


#ifndef POWER_CONFIG_STATE_OBSERVER_PRIO
#define POWER_CONFIG_STATE_OBSERVER_PRIO 0
#endif


// <o> RNG_CONFIG_STATE_OBSERVER_PRIO  
// <i> Priority with which state events are dispatched to this module.


#ifndef RNG_CONFIG_STATE_OBSERVER_PRIO
#define RNG_CONFIG_STATE_OBSERVER_PRIO 0
#endif


// </h> 
//==========================================================


// <h> Stack Event Observers priorities - Invididual priorities


//==========================================================
// <o> NRF_SDH_ANT_STACK_OBSERVER_PRIO  
// <i> This setting configures the priority with which ANT events are processed with respect to other events coming from the stack.
// <i> Modify this setting if you need to have ANT events dispatched before or after other stack events, such as BLE or SoC.
// <i> Zero is the highest priority.


#ifndef NRF_SDH_ANT_STACK_OBSERVER_PRIO
#define NRF_SDH_ANT_STACK_OBSERVER_PRIO 0
#endif


// <o> NRF_SDH_BLE_STACK_OBSERVER_PRIO  
// <i> This setting configures the priority with which BLE events are processed with respect to other events coming from the stack.
// <i> Modify this setting if you need to have BLE events dispatched before or after other stack events, such as ANT or SoC.
// <i> Zero is the highest priority.


#ifndef NRF_SDH_BLE_STACK_OBSERVER_PRIO
#define NRF_SDH_BLE_STACK_OBSERVER_PRIO 0
#endif


// <o> NRF_SDH_SOC_STACK_OBSERVER_PRIO  
// <i> This setting configures the priority with which SoC events are processed with respect to other events coming from the stack.
// <i> Modify this setting if you need to have SoC events dispatched before or after other stack events, such as ANT or BLE.
// <i> Zero is the highest priority.


#ifndef NRF_SDH_SOC_STACK_OBSERVER_PRIO
#define NRF_SDH_SOC_STACK_OBSERVER_PRIO 0
#endif


// </h> 
//==========================================================


// </h> 
//==========================================================




// </e>


// <e> NRF_SDH_SOC_ENABLED - nrf_sdh_soc - SoftDevice SoC event handler
//==========================================================
#ifndef NRF_SDH_SOC_ENABLED
#define NRF_SDH_SOC_ENABLED 1
#endif
// <h> SoC Observers - Observers and priority levels


//==========================================================
// <o> NRF_SDH_SOC_OBSERVER_PRIO_LEVELS - Total number of priority levels for SoC observers. 
// <i> This setting configures the number of priority levels available for the SoC event handlers.
// <i> The priority level of a handler determines the order in which it receives events, with respect to other handlers.


#ifndef NRF_SDH_SOC_OBSERVER_PRIO_LEVELS
#define NRF_SDH_SOC_OBSERVER_PRIO_LEVELS 2
#endif


// <h> SoC Observers priorities - Invididual priorities


//==========================================================
// <o> BLE_ADV_SOC_OBSERVER_PRIO  
// <i> Priority with which SoC events are dispatched to the Advertising module.


#ifndef BLE_ADV_SOC_OBSERVER_PRIO
#define BLE_ADV_SOC_OBSERVER_PRIO 1
#endif


// <o> BLE_DFU_SOC_OBSERVER_PRIO  
// <i> Priority with which BLE events are dispatched to the DFU Service.


#ifndef BLE_DFU_SOC_OBSERVER_PRIO
#define BLE_DFU_SOC_OBSERVER_PRIO 1
#endif


// <o> CLOCK_CONFIG_SOC_OBSERVER_PRIO  
// <i> Priority with which SoC events are dispatched to the Clock driver.


#ifndef CLOCK_CONFIG_SOC_OBSERVER_PRIO
#define CLOCK_CONFIG_SOC_OBSERVER_PRIO 0
#endif


// <o> POWER_CONFIG_SOC_OBSERVER_PRIO  
// <i> Priority with which SoC events are dispatched to the Power driver.


#ifndef POWER_CONFIG_SOC_OBSERVER_PRIO
#define POWER_CONFIG_SOC_OBSERVER_PRIO 0
#endif


// </h> 
//==========================================================


// </h> 
//==========================================================




// </e>


// </h> 
//==========================================================


// <<< end of configuration section >>>
#endif //SDK_CONFIG_H


#ifndef   _ADV_EVT_H_
#define   _ADV_EVT_H_








#include "ble_advdata.h"






#define APP_ADV_INTERVAL                64
#define APP_ADV_TIMEOUT_IN_SECONDS      BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED 
#define APP_BLE_CONN_CFG_TAG            1 




extern ble_advdata_service_data_t  SocketServiceData;
extern uint8_t advertData[];
extern uint16_t  sk_adv_length;
extern uint8_t  CurDisconPend;








extern void InitAdvData(void);
extern void advertising_start(void);
extern void UpdateAdvData(void);
















#endif


#ifndef  _AUTO_SET_H_
#define  _AUTO_SET_H_




















extern void AUTO_EN_DIS(void);
extern void SetDevicePowerActionType(void);
extern void ReadDevicePowerActionType(void);




































#endif



/* Copyright (c) [2014 Baidu]. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at


    http://www.apache.org/licenses/LICENSE-2.0


 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * File Name          : 
 * Author             : 
 * Version            : $Revision:$
 * Date               : $Date:$
 * Description        : 
 *                      
 * HISTORY:
 * Date               | Modification                    | Author
 * 28/03/2014         | Initial Revision                | 
 
 */
#ifndef WALL_CLOCK_TIMER_H_
#define WALL_CLOCK_TIMER_H_


#include <stdint.h>


#define IsLeapYear(yr) (!((yr) % 400) || (((yr) % 100) && !((yr) % 4)))


#define YearLength(yr) (IsLeapYear(yr) ? 366 : 365)


// number of seconds since 0 hrs, 0 minutes, 0 seconds, on the
// 1st of January 2000 UTC


typedef uint32_t UTCTime; /* used to store the second counts for RTC */


#define BEGYEAR         2000     // UTC started at 00:00:00 January 1, 2000


#define DAY             86400UL  // 24 hours * 60 minutes * 60 seconds




// To be used with
typedef struct
{
    uint16_t year;    // 2000+
    uint8_t month;    // 0-11
    uint8_t day;      // 0-30
    uint8_t seconds;  // 0-59
    uint8_t minutes;  // 0-59
    uint8_t hour;     // 0-23
}
UTCTimeStruct;
typedef enum {
    MOn  = 0,
    Tues  = 1,
    Wed  = 2,
    Thur = 3,
    Fri  = 4,
    Sat  = 5,
    Sun  = 6
}DAY_OF_WEEK;




typedef struct
{
uint32_t seconds  :
    6;
uint32_t minute  :
    6;
uint32_t hours  :
    5;
uint32_t day   :
    5;
uint32_t month  :
    4;
uint32_t year   :
    6;
}
time_bit_field_type_t;


typedef union
{
    uint32_t data;
    time_bit_field_type_t time;
} time_union_t;


extern void system_clock_init(void);
void set_system_clock(time_union_t time);
UTCTimeStruct * get_wall_clock_time(void);


void ConvertToUTCTime( UTCTimeStruct *tm, UTCTime secTime );




#endif //WALL_CLOCK_TIMER_H_


/******************************************************************************
* Copyright (c) 2017, AXAET Pioneer of Smart Life
* All rights reserved.
* Module: BleCommand.h
* Author: ZhangYongQiang
* Version: V1.0
* History:
*   2017-05-22 Original version
*******************************************************************************/
#ifndef __BLECOMMAND_H_
#define __BLECOMMAND_H_


//*********************************************************
//设备类型
//*********************************************************
#define  DEVICE_TYPE_SWITCH  0x01 //智能开关
#define  DEVICE_TYPE_SOCKET  0x02 //智能插座
#define  DEVICE_TYPE_IBEACON  0x03 //IBEACON
#define  DEVICE_TYPE_ANTILOST  0x04 //防丢器
#define  DEVICE_TYPE_CONTROLBOX 0x05 //蓝牙控制盒
#define  DEVICE_TYPE_MASTERBOARD 0x06 //智能壁炉




//*********************************************************
//设备型号
//*********************************************************
//智能开关
#define  SWITCH_MODEL_CHANNELONE 0x01 //一路开关
#define  SWITCH_MODEL_CHANNELTWO 0x02 //二路开关
#define  SWITCH_MODEL_CHANNELTHREE 0x03 //三路开关


//iBeacon
#define  IBEACON_MODEL_STANDARD 0x11 //标准iBeacon
#define  IBEACON_MODEL_VOLTAGE 0x12 //带电量








//*********************************************************
//固件类型
//*********************************************************
#define  FIRMWARE_TYPE_CC2541 0x01 //TI CC2541
#define  FIRMWARE_TYPE_CC2640 0x02 //TI CC2640
#define  FIRMWARE_TYPE_NRF52832 0x03 //Nordic nRF52832




//*****************************************************************
//NORMAL CMD
//
//
//*****************************************************************


//*********************************************************
//Communicate CMD Definitions,
//*********************************************************


// app to ble
#define  BLE_CMD_CONNECTBREAK   0x00 //断开连接
#define  BLE_CMD_SWITCH        0x01 //开关切换,可通过指定序号控制不同的开关
#define  BLE_CMD_AUTO_EN_DIS  0x02 //使能或者关闭自动开关
#define  BLE_CMD_APPTIME    0x03 //当前APP时间
#define  BLE_CMD_NAMECHANGEA  0x04 //修改蓝牙配对名a
#define  BLE_CMD_NAMECHANGEB  0x05 //修改蓝牙配对名b
#define  BLE_CMD_TEMERLOSE  0x06 //连接时禁止定时关灯
#define  BLE_CMD_SWITCH_STATUS 0x07 //当前开关状态
#define  BLE_CMD_AUTO_STATUS      0x08 //当前自动状态
#define  BLE_CMD_MACADDR_GET      0x09 //获取从机mac地址。从机回应主机,回应mac addr
#define  BLE_CMD_VERSION_GET      0x0a //获取从机版本信息。从机回应主机,回应version   BLE_CMD_VERSION_GET
#define  BLE_CMD_PD_TYPE_GET      0x0b //获取从机类型信息。从机回应主机,回应类型
#define  BLE_CMD_PASSWORDMODIFY 0x0c //修改机器密码
#define  BLE_CMD_PASSWORDRECOVER 0x0d //恢复默认机器密码
#define  BLE_CMD_PWLOGIN      0x0e //密码登录
#define  BLE_CMD_FACTORYSETTING 0x0f //恢复出厂设置
#define  BLE_CMD_PW_OFF        0x10 //系统关机,关闭
#define  BLE_CMD_SYS_RESET    0x11 //系统重启
#define  BLE_CMD_SNED2SLAVE    0x12 //主机发送数据到从机
#define  BLE_CMD_SNED2MASTER  0x13 //从机发送数据到主机
#define  BLE_CMD_FACTORY_MODE                     0x14   //工厂测试模式
#define  BLE_CMD_POWER_ACTION_TYPE     0x15  
#define  BLE_CMD_READ_POWER_ON_ACTION   0x16    


//*********************************************************
//Communicate CMD Definitions,定时组
//*********************************************************
#define  BLE_CMD_TIMERGET    0x20 //获取定时组
#define  BLE_CMD_TIMER_ON_OFF 0x21 //定时组开/关切换
#define  BLE_CMD_TIMEREDIT  0x22 //增加/编辑定时组
#define  BLE_CMD_TIMERDELETE  0x23 //删除定时组
#define  BLE_CMD_COUNTDOWN  0x24 //开关倒计时,打开某个开关一段时间后自动关闭
#define  BLE_CMD_TIMERABLE  0x25 //定时功能开启/关闭




//*********************************************************
//Communicate CMD Definitions,倒计时
//*********************************************************
#define  BLE_CMD_OBTAIN_COUNT_TIME    0x26
#define  BLE_CMD_SET_COUNTDOWN        0x24
#define  BLE_CMD_TIMER_DOWN_CANCEL 0x27
#define  BLE_CMD_TIMER_ACTIVE         0x28


//*********************************************************
//Communicate CMD Definitions,帐号管理
//*********************************************************
#define  BLE_CMD_SUPPER_LIMIT    0x29 ///超级权限
#define  BLE_CMD_BONDINGVERIFY 0x2a //主机2从机,密码绑定设备;从机回应主机,绑定状态和从机mac地址
#define  BLE_CMD_MACVERIFY        0x2b //主机2从机,查询是否被从机绑定。从机回应主机,绑定状态和从机mac
#define  BLE_CMD_BONDINGLOSE  0x2c //失效当前绑定的帐号
#define  BLE_CMD_ALLBONDINGLOSE 0x2d //失效所有绑定账号和密码
#define  BLE_CMD_USER_NAME    0x2e //用户帐号
#define  BLE_CMD_USER_INFO    0x2f //用户帐号查询
#define  BLE_CMD_USER_LIMIT    0x30 //用户权限
#define  BLE_CMD_USER_LIMIT_INFO 0x31 //用户权限查询
#define  BLE_CMD_USER_DELET     0x32 //用户删除
#define  BLE_CMD_USER_LOGIN     0x33 //用户登录
#define  BLE_CMD_USER_LIST      0x34 //用户登录


#define  BLE_CMD_SET_DEVICE_ID      0x35  //设置设备ID
#define  BLE_CMD_GET_DEVICE_ID      0x36  //获取设备ID




//用户自定义命令
#define  BLE_CMD_USER_CUSTOM                       0xff
#define  BLE_CMD_USER_CUSTOM_SON_SEND_NAME         0x11//发送名字




//*****************************************************************
//big data transf
//
//
//*****************************************************************
#define  BLE_CMD_OTASTART      0x40 //空中升级开始
#define  BLE_CMD_OTATRANSFER    0x41 //空中升级数据包发送
#define  BLE_CMD_OTAFINISH    0x42 //空中升级数据发送完成
#define  BLE_CMD_BIGDATASTART  0x43 //大数据传输开始        
#define  BLE_CMD_BIGDATATRANSFER 0x44 //大数据传输数据包发送  
#define  BLE_CMD_BIGDATAFINISH 0x45 //大数据传输数据发送完成










//*****************************************************************
//sensor data cmd
//
//
//*****************************************************************
#define  BLE_CMD_POWERCORRECT 0x80 //功率校准
#define  BLE_CMD_POWERGET  0x81 //请求功率和电量
#define  BLE_CMD_POWERRESET 0x82 //智能插座总电量清零










//*****************************************************************
//some special pd data cmd
//
//
//*****************************************************************
//iBeacon
#define  BLE_CMD_UUIDDATA    0xc0 //发送UUID数据
#define  BLE_CMD_IBEACONDATA  0xc1 //发送Major,Minor,TxPower,period等数据






//智能壁炉
#define  BLE_CMD_CURRENTSTATE  0xc0 //设置壁炉当前状态
#define  BLE_CMD_FIREPLACEMODE 0xc1 //设置壁炉模式、档位及温度
#define  BLE_CMD_TIMERSWITCHOVER 0xc2 //切换定时功能模式












//防丢器
#define  BLE_CMD_ANTIDROP_KEY  0xc0 //放丢器 按键命令
#define  BLE_CMD_ANTIDROP_ALARM  0xc1 //放丢器 报警命令
#define  BLE_CMD_ANTIDROP_ALARM_STOP  0xc2 //放丢器 停止报警命令


//----------------------------------------------------------------------------------
#endif

#ifndef  _BOND_H_
#define  _BOND_H_


#include "stdint.h"
#include "socket_cfg.h"


typedef struct strbondstate
{
    uint8 SendData[2];
    uint8 Permission;
    uint8 BondResult;
}StrBondState; 




typedef struct
{
    uint8  bond[4];        //'Bond'表示有可用绑定MAC
    uint8  number;        //已绑定手机数量
    uint8  passwordflag;        //密码修改标志
}BondInfo_t;




//附加功能
#define ADDCTRL_OPEN_TIMING      0x80
#define ADDCTRL_TIMING_NOCLOSE   0x08
#define ADDCTRL_NOCLOSE          0x01






extern uint8 STORE_MAC_DATA[PHONE_MAC_LENGTH];
extern uint8 AdditionalCtrl;
extern uint8 Control_Limit;
extern uint8 Control_Permission;
extern uint8 PD_TYPE[15];
extern uint8 Send_Flag;




extern uint8 mac_flag[PHONE_MAC_MAXNUM];
extern uint8 phone_mac[PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE];




extern uint8 mac_flag0[PHONE_MAC_MAXNUM];
extern uint8 phone_mac0[PHONE_MAC_MAXNUM*BOND_PHONEMAC_SIZE];




//*********************************************************
//Custom function declaration
//*********************************************************
void AppBonding_Init(void);
StrBondState AppBonding_Phone(uint8 *uiPhoneMAC,uint8 BondFlag);
uint8 AppBonding_Verification(uint8 *uiPhoneMAC);
uint8 AppBonding_LostPhoneMAC(uint8 *uiPhoneMAC);
void AppBonding_LostPhoneAll(void);
uint8 AppBonding_CheckPhoneMAC(void);






extern void BONDINGLOSE(void);
extern void ALLBONDINGLOSE(void);
extern void BONDINGVERIFY(void);
extern void MACADDR_GET(void);
extern void SUPPER_LIMIT(void);














#endif



#ifndef  _CMD_DISPATCH_H_
#define  _CMD_DISPATCH_H_



extern void SocketCommandDispatch(void);


#endif


#ifndef   _CMD_PACKET_H_
#define   _CMD_PACKET_H_












#include  "dorlock_user_mgr.h"




void CalculaLockCmdPacketLrc(LockUartCmd_t *LockUartCmd);
void LockCmdPacketStringToUart(LockUartCmd_t *LockUartCmd);
void  PacketAddUserCipherCmdContent(LockUartCmd_t *LockUartCmdHandle, uint8_t UserType, SystemUserMgr_t *SystemUserMgr);
void  PacketDelUserCipherCmdContent(LockUartCmd_t *LockUartCmdHandle, uint8_t UserType, SystemUserMgr_t *SystemUserMgr);
void  PacketCipherQueryCmdContent(uint8_t  CipherQueryType, uint16_t  CipherSerial, LockUartCmd_t *LockUartCmdHandle, uint8_t UserType);














#endif

#ifndef  _DORLOCK_CMD_RSP_H_
#define  _DORLOCK_CMD_RSP_H_




#include <stdbool.h>
#include <stdint.h>




#define   RSP_WAIT_SINGLE_TIME     1000


bool  MonitorUartBusyExe(void);
void  SetCurDorLockUartCmdExe(uint8_t  CmdExeType, uint8_t  CmdExeCode, uint8_t  CmdExeReason, uint8_t  CmdExeHandle);
void  UartCmdRspProceStart(uint16_t  TaskDelay);
void  SetCurDorLockUartCmdRsp(uint8_t *cmdLine, uint8_t RspLenth);
void  CreatUartCmdRspMgrEvt(void);
void    CreatUartCmdRspMgrEvt(void);








#endif


#ifndef  _DORLOCK_USER_MGR_H_
#define  _DORLOCK_USER_MGR_H_






#include "stdint.h"
#include "stdbool.h"




#define   PRESCRIP_USER_SIZE      10




#define   TEMPOR_USER_NAME    "Bgyc"
#define   MASTER_NAME         "HourseKeeper"


#define   PASSWORD_SIZE    10


//#define   USER_NONE_CREAT_FLAG    0xfffe
#define   USER_NONE_CREAT_FLAG    0


#define   TEMPOR_ID_SIGN_POS    PRESCRIP_USER_SIZE
#define   MASTER_ID_SIGN_POS    (PRESCRIP_USER_SIZE+1)




#define   TEMPOR_USER_CMD_HANDLE    TEMPOR_ID_SIGN_POS
#define   MASTER_CMD_HANDLE MASTER_ID_SIGN_POS




#define  FILE_ID_USER_MGR_FLASH   0x134B  
#define  RECORD_KEY_USER_MGR      31




#define  FILE_ID_USER_CREAT   0x134D
#define  RECORD_KEY_USER_CREAT  33




typedef  struct
{
uint8_t   CmdHeader;
   uint32_t  Lcr;
      uint8_t   lenth;
      uint8_t   FunCode;
      uint8_t   Content[128];
      uint8_t   CurUartExeCmd;
   uint8_t   CurUartCmdExeType;
   uint8_t   CurUartCmdExeReason;
      uint8_t   CurCmdExeHandle;  
}LockUartCmd_t; 




#pragma pack(1)


typedef  struct
{
   uint8_t   Yearh;
uint8_t   Yearl;
   uint8_t   Month;
   uint8_t   Day;
      uint8_t   Hour;
      uint8_t   Minute;
   uint8_t   Second;
}RealTime_t;




typedef  struct
{
uint8_t    *DorLockUserName;
  uint8_t    DorLockOperaCipher[PASSWORD_SIZE];
  uint16_t   DorLockUserId;
  uint8_t    DorLockUseAuthor;
  RealTime_t   CipherValidStartTime;
     RealTime_t   CipherValidEndTime;
     uint8_t    CipherLenth;
     uint8_t    DorLockUseTimeSchedul;
  uint16_t    CipherId;
}DorLockUseMgr_t;






typedef  struct
{
DorLockUseMgr_t  NormalUserMgr[PRESCRIP_USER_SIZE];
 DorLockUseMgr_t  MasterMgr;
 DorLockUseMgr_t  TemporUserMgr;
 uint8_t    MasterIdRecordIndex;
 uint8_t    TemporUserIdRecordIndex;
 uint16_t   UserCreatRecordTab[PRESCRIP_USER_SIZE+2];
 uint16_t   UserCipherMgrFlag;
 uint8_t    IsUserCreat[12];
}SystemUserMgr_t;






typedef  struct
{
RealTime_t  UserCipherStartUseTime;
   RealTime_t  UserCipherEndUseTime;
}UserCipherLiveTime_t;




typedef  struct
{
uint16_t   UserIdCreatFlashBuf[PRESCRIP_USER_SIZE+2];
   uint16_t   UserCipherAddDelateFlag;
   UserCipherLiveTime_t   UserCipherLiveTime[PRESCRIP_USER_SIZE+1];
   uint8_t    UserCipherNumList[PASSWORD_SIZE*(PRESCRIP_USER_SIZE+2)];
   uint8_t    UserCipherLenList[PRESCRIP_USER_SIZE+2];
   uint8_t    CipherUseTimeSta[PRESCRIP_USER_SIZE+1];
      uint8_t    IsUserCreat[12];
   uint16_t   TemporCipherId;
}UserMgrFlashOpera_t;




enum
{
NORMAL_USER = 1,
   TEMPOR_USER,
   MASTER_USER
};




enum  
{
   NONE_TIME_USING = 1,
 BEFORE_TIME_USING,
   TIME_IN_USING,
   AFTER_TIME_USING
};


extern  uint8_t   *TimelineUserTab[PRESCRIP_USER_SIZE];


void  GetUserMgrCmdHandleAdd(LockUartCmd_t *UartCmd);
void  LockUartUserMgrReply(uint8_t *CmdLine, uint8_t CmdSize);
void  SetNormalUserCipherTimeSta(uint8_t UserIndex, uint8_t CipherTimeSta);
void  TimeForPermitNormalUserCipher(uint8_t UserIndex);
void   CancelTemporUserCipher(uint8_t UserIndex, uint8_t CmdTrigType);
//void   DelateOneNormalUserCipher(uint8_t UserIndex, uint8_t CmdTrigType);
void  GetSystemUserMgrAdd(SystemUserMgr_t *UserMgr);
void   AddOneNormalUserCipher(uint8_t UserIndex, RealTime_t *TimeStart, RealTime_t *TimeEnd, uint8_t *Cipher,uint8_t CipherSize);
void   CreatTemporUserCipher(RealTime_t *TimeEnd, uint8_t *Cipher, uint8_t UserIndex, uint8_t CipherSize);
void  FillInNewUserIdCode(uint8_t  CmdExeHandle, uint16_t  UserId);
void  FillInTemporCipherIdCode(uint16_t  CipherId);
void   AddUserPassCodeOperation(uint8_t  UserType, uint8_t UserHandle);
void  UserMgrFlashUpdata(void);
void  SetTemporUserCipherTimeSta(uint8_t CipherTimeSta);
void  ModifyMasterPassCode(uint8_t PassCodeSize, uint8_t *PassCodeContent);
void   MasterCipherQuery(void);
void  SetCurUartExeCmd(uint8_t  UartExeCmd);
void  DoorLockNormalOpen(void);
void  CreatTemporUserSuccess(uint8_t UserIndex);
bool   DelateOneNormalUserCipher(uint8_t UserIndex, uint8_t CmdTrigType);
uint8_t GetCurUartExeCmd(void);
void  UserMgrPowerOnInit(void);
void  SystemUserMgrConfig(void);




#endif



#ifndef __DR_LOCK_CMD_H
#define __DR_LOCK_CMD_H


#include <stdint.h>
#include <string.h>




#define   ADD_USER_SUCCESS   0x00
#define   ADD_USER_FAIL      0x01




#define   CMD_RSP_WATT    0
#define   CMD_RSP_START   1
#define   CMD_RSP_END     2


#define cmdLenMax 128


extern void ble_send_data(uint8_t *buf, uint8_t len);


typedef void (*sched_handler_t)(void);




void recv_proc(void );


void uart_recv(void);
void  UartSendBytesToDorLock(uint8_t *p_data_tx_buf, uint16_t size_bytes);


void scheduler_proc(sched_handler_t at_func);
void  GetUartCmdRspSta(uint8_t *RspSta);
void  SetUartCmdRspSta(uint8_t  RspSta);


#endif



#ifndef   _LOCK_CMD_DEF_H_
#define   _LOCK_CMD_DEF_H_








enum
{
DOR_LOCK_USER_MGR_CMD = 1,
DOR_LOCK_TIME_MGR_CMD
};








enum
{
     LOCK_CMD_ADD_CIPHER           =  0x1A,
     DOOR_LOCK_CMD_IDLE            =  0x00,   
     DOOR_LOCK_CMD_HEAD            =  0xF5,
DOOR_LOCK_CMD_ADD_USER        =  0x19,
DOOR_LOCK_CMD_DEL_CIPHER      =  0x1c,
LOCK_CMD_READ_RTC             =  0x17,
     LOCK_CMD_MODIFY_RTC           =  0X18,
  LOCK_CMD_QUERY_CIPHER       =  0x22,
  LOCK_CMD_OPEN_CLOSE         =  0xB1,
  LOCK_CMD_CIPHER_UPDATA      =  0X26
};








enum
{
ETMARS_CMD_EXE_TRIGGER     = 1,
NONE_RSP_CMD_EXE_TRIGGER,
INTERNAL_TIME_ARRIVE_CMD_EXE_TRIGGER
};








enum
{
CIPHER_USER_ID_QUERY  = 1,
 CIPHER_USER_NAME_QUERY
};












enum
{
NORMAL_OPEN_LOCK  = 0X01,
 CONSTANT_OPEN_LOCK  =  0X02,
 CLOSE_LOCK  = 0X03,
 TIME_LIMIT_OPEN_LOCK  = 0X11
};






























#endif



#ifndef  _NAME_EVT_H_
#define  _NAME_EVT_H_








#define GAP_DEVICE_NAME_LEN       21


extern uint8_t deviceName[31];
extern uint8 attDeviceName[GAP_DEVICE_NAME_LEN];


extern uint8  devName[31];




extern void NAMECHANGEA(void);
extern void NAMECHANGEB(void);




























#endif

#ifndef  _PWD_EVT_H_
#define  _PWD_EVT_H_










#include "socket_cfg.h"










void PASSWORDRECOVER(void);
void PASSWORDMODIFY(void);
uint8 IsPassWordModify(void);



#endif

#ifndef  _RTC_CRIPHT_MGR_H_
#define  _RTC_CRIPHT_MGR_H_








#include <stdint.h>
#include "dorlock_user_mgr.h"










void    CreatCipherMgrEvt(void);
void  CipherMgrTaskStart(uint16_t  TaskDelay);
void  CipherMgrTaskStop(void);
void   LockUartRtcUserMgrTask(uint8_t *cmdLine, uint8_t data_len);
bool   ModifyLockLocalTime(RealTime_t *LocalTime);








#endif

#ifndef   _SK_EVT_H_
#define   _SK_EVT_H_






#include  "app_timer.h"
#include  "socket_cfg.h"




APP_TIMER_DEF(ledTimeoutClock);
APP_TIMER_DEF(LedFlashClock);
APP_TIMER_DEF(StartAdvClock);
APP_TIMER_DEF(TimerPulseClock);
APP_TIMER_DEF(RtcTimerClock);
APP_TIMER_DEF(TerminateClock);
APP_TIMER_DEF(SendClocksClock);
APP_TIMER_DEF(SendDataClock);
APP_TIMER_DEF(DelayCloseClock);
APP_TIMER_DEF(TestEvtClock);
APP_TIMER_DEF(TimerDownCntClock);
APP_TIMER_DEF(FactorySetClock);




#define  LED_TIME_OUT         1
#define  LED_FLASH            2
#define  START_ADV            3
#define  RTC_TIMER            4
#define  BLE_DISCON           5
#define  SEND_CLOCKS          6
#define  SEND_DATA            7
#define  DELAY_CLOSE          8
#define  TIMER_DOWN_CNT       9
#define  FACTORY_SET          10




extern uint8  SocketDiscon;
extern sk_timer_down_t  CountDown[NUMBER_OF_SMARTSWITCH];
extern uint8  IsDevConnect;




extern void  UserConnectOnEvt(void);
extern void  UserDisconnectEvt(void);
extern void  sk_event_create(void);




extern void  LedFlashAction(uint16 TaskDelay);




extern void  SocketTaskStop(uint8 TaskId);
extern void  SocketTaskAction(uint8 TaskId, uint16 TaskDelay);
extern void RequireOtaStart(void);


















#endif

#ifndef   _SK_FLASH_H_
#define   _SK_FLASH_H_








#include  "sdk_errors.h"
#include  "socket_cfg.h"
#include  "bond.h"




#define RETURN_IF_ERROR(PARAM)                                                                     \
    if ((PARAM) != NRF_SUCCESS)                                                                    \
    {                                                                                              \
        return (PARAM);                                                                            \
    }






#define FLASH_ACCES_ERROR_CHECK_ALLOW_NOT_FOUND(err_code)                                          \
    if (err_code != (FDS_ERR_NOT_FOUND))                                                           \
        APP_ERROR_CHECK(err_code);




typedef enum
{
    ES_FLASH_ACCESS_READ,  //!< Read data.
    ES_FLASH_ACCESS_WRITE, //!< Write data.
    ES_FLASH_ACCESS_CLEAR  //!< Clear data.
} es_flash_access_t;




typedef struct
{
    uint16_t          record_key;
    uint16_t          file_id;
    uint8_t *         p_data_buf;
    uint8_t *         p_data;
    uint16_t          size_bytes;
    es_flash_access_t access_type;
} flash_access_params_t;




extern ret_code_t socket_flash_on_init(void);


extern uint32_t sk_flash_num_pending_ops(void);
extern ret_code_t sk_flash_access_sockets(Smart_Socket_t *p_sk, es_flash_access_t access_type);
extern void  sockets_flash_init(void);
extern ret_code_t sk_flash_access_mac_data(uint8 *p_mac_data, es_flash_access_t access_type);
extern ret_code_t  sk_flash_access_rtc_time(RTC_Time_t *p_rtc_time, es_flash_access_t access_type);
extern ret_code_t  sk_flash_access_power_on_cnt(uint32 *p_power_on_cnt, es_flash_access_t access_type);
extern ret_code_t  sk_flash_access_device_name(uint8 *p_device_name, es_flash_access_t access_type);
extern ret_code_t  sk_flash_access_mac_flag(uint8 *p_mac_flag, es_flash_access_t access_type);
extern ret_code_t  sk_flash_access_phone_mac(uint8 *p_phone_mac, es_flash_access_t access_type);
extern ret_code_t sk_flash_access_mac_flag0(uint8 *p_mac_flag0, es_flash_access_t access_type);
extern ret_code_t  sk_flash_access_phone_mac0(uint8 *p_phone_mac0, es_flash_access_t access_type);
//extern ret_code_t  sk_flash_access_bond_infor(BondInfo_t *p_bond_infor, es_flash_access_t access_type);
extern ret_code_t  sk_flash_access_dev_id(Socket_Id_t *p_dev_id, es_flash_access_t access_type);
extern ret_code_t  sk_flash_access_timer_permit(uint8 *p_timer_permit, es_flash_access_t access_type);


extern void  phone_mac_flash_init(void);
extern void  phone_mac0_flash_init(void);
extern void  mac_flag_flash_init(void);
extern void  mac_flag0_flash_init(void);
extern void  power_on_cnt_flash_init(void);
extern void  rtc_time_flash_init(void);
extern void  device_name_flash_init(void);
extern void  mac_data_flash_init(void);
extern void  timer_permit_flash_init(void);


extern void WaitFlashWriteEnd(void);
void  DubegStringPut(uint8 *p_data_tx_buf, uint16 size_bytes);


ret_code_t access_flash_data(const flash_access_params_t * p_params);


#endif

#ifndef  _SOCKET_CFG_H_
#define  _SOCKET_CFG_H_




#include "stdint.h" 


typedef unsigned          char uint8;
typedef unsigned short     int uint16;
typedef unsigned           int uint32;




#define GATEWAY_PASSWORD_0      '6'
#define GATEWAY_PASSWORD_1      '5'
#define GATEWAY_PASSWORD_2      '4'
#define GATEWAY_PASSWORD_3      '3'
#define GATEWAY_PASSWORD_4      '2'
#define GATEWAY_PASSWORD_5      '1'
#define AXA_FLAG  0xa5


#define NUMBER_OF_CLOCKS        10




#pragma pack(1)


typedef struct
{
    uint8  Status;
    uint8  Mode;
 uint8  PowerActionType;
 uint8  TimerActionType[NUMBER_OF_CLOCKS];
 uint8  IsRtcSetting[NUMBER_OF_CLOCKS+1];
    uint8  IsTimerActive[NUMBER_OF_CLOCKS];
    uint8  Valid[NUMBER_OF_CLOCKS];   
    uint8  Repeat[NUMBER_OF_CLOCKS];   
    uint16 ClockOn[NUMBER_OF_CLOCKS]; 
    uint16 ClockOff[NUMBER_OF_CLOCKS]; 
                          
}Smart_Socket_t;




typedef struct
{
    uint8 Week;
    uint8 Hour;
    uint8 Minute;
}RTC_Time_t;




//****************门锁重置创建用户允许***************************
#define   DOR_LOCK_RESET_USER_CREAT_ENABLE     1


//****************设备ID******************************************
#define   PRODUCT_ID_LOW_BYTE    0x69
#define   PRODUCT_ID_HIG_BYTE    0x00
#define   PRODUCT_ID_SIZE        2
#define   DEVICE_ID_MAX_SIZE     (18-PRODUCT_ID_SIZE)
#define   SET_DEV_ID_SUCCESS     1
#define   SET_DEV_ID_FAIL        0


#define   GET_DEV_ID_FAIL        0


//****************设备ID******************************************


typedef  struct
{
uint8  IdSize;
 uint8  IdNum[DEVICE_ID_MAX_SIZE];
}Socket_Id_t;






#define   WEEK_END_REPEAT   0x40   




#define   RTC_TIME_GROUP_ON_CFG     (6*256+1)
#define   RTC_TIME_GROUP_OFF_CFG    (1*256+1)


#define   BOTH_TIME_ON_OFF_GAIN     0x03


#define   NUMBER_OF_SMARTSWITCH     1
#define   DELAY_ON      1
#define   DELAY_OFF     0


typedef  struct
{
   uint8  Delay_Switch;
uint16 CountDownNum;
}sk_timer_down_t;




//****************倒计时类型****************************************
#define   POWER_ON_COUNT_DOWN_ENABLE   0
#define   SOCKET_COUNT_DOWN_TYPE     2


#if  (POWER_ON_COUNT_DOWN_ENABLE)
#if  (SOCKET_COUNT_DOWN_TYPE == 1)
#define   MINUTE_COUNT_DOWN
#elif  (SOCKET_COUNT_DOWN_TYPE == 2)
#define   SECOND_COUNT_DOWN
#endif
#endif


//****************倒计时类型****************************************




//****************设备类型定义**************************************
//1: 插座  0:控制盒
#define  DEVICE_TYPE    0


#if (DEVICE_TYPE)
#define  AXA_SMART_SOCKET
#else
#define  AXA_SMART_BOX
#endif


//****************设备类型定义**************************************


//****************设备固件升级测试开关**********************************


#define   DFU_TEST_ENABLE      0


//****************设备固件升级测试开关*******************************


//****************工作模式电平选择**********************************


#define  BOOT_TYPE    0


#if (BOOT_TYPE)
#define  BOOT_DTM
#else
#define  BOOT_USER_APP
#endif


#if  defined (BOOT_DTM)  
#define   MODE_ACTIVE_LEVEL    0
#elif  defined (BOOT_USER_APP)
#define   MODE_ACTIVE_LEVEL    1
#endif


//****************工作模式电平选择**********************************


//****************设备控制端口定义**********************************
#if  1
#define  IO_RELAY_CTRL    6
#define  IO_LED_CTRL      5
#define  IO_KEY_CTRL      14
#define  IO_MODE_TEST     18
#else
#define  IO_RELAY_CTRL    9
#define  IO_LED_CTRL      6
#define  IO_KEY_CTRL      10
#define  IO_MODE_TEST     16
#endif


//****************设备控制端口定义**********************************


//**************动作触发**************************
#define   SWITCH_ACTION_TRIGGER_TYPE_DEVICE_TOUCH          1
#define   SWITCH_ACTION_TRIGGER_TYPE_USER_PHONE_TOUCH      2
#define   SWITCH_ACTION_TRIGGER_TYPE_TIME_DELAY_END        3
#define   SWITCH_ACTION_TRIGGER_TYPE_TIME_RTC_ARRIVE       4


//****************自动模式**************************************


#define MODE_MANUAL        0x00
#define MODE_AUTO          0x01


//****************自动模式**************************************






//****************设备定时组配置**************************************


#define NUMBER_OF_CLOCKS                      10  //定时组数量,最多10组


//****************设备定时组配置**************************************


//****************手机绑定******************************************
#define PHONE_MAC_LENGTH                16
#define ADDCTRL_STORE_INDEX             (PHONE_MAC_LENGTH-11)
#define BOND_PHONEMAC_SIZE             6
#define BOND_PASSWORD_SIZE             6
#define BOND_MACFLAG_SIZE              1
#define PHONE_MAC_MAXNUM               2
#define FLASH_MAC_SIZE                 8


#define RTC_WEEK                      (PHONE_MAC_LENGTH-8)
#define RTC_HOUR                      (PHONE_MAC_LENGTH-9)
#define RTC_MINUTE                    (PHONE_MAC_LENGTH-10)


#define  FLASH_MACSTATE_CLEAR                (0xFF) 
#define  FLASH_MACSTATE_VALID                (0xFC) 
#define  FLASH_MACSTATE_INVALID              (0xCC) 




//Flash Address
#define BOND_PHONEDATA_START_ADDR        (0x10000)   //绑定手机数据信息的位置
#define BOND_MACFLAG_START_ADDR          (0x10010)   //Flag开始地址
#define BOND_PHONEMAC_START_ADDR         (0x10080)
#define BOND_PHONEMAC_END_ADDR           (0x10FFF)   //Sector 16


#define IMAGE_PHONEDATA_START_ADDR        (0x11000)   //绑定手机数据信息的位置
#define IMAGE_MACFLAG_START_ADDR          (0x11010)   //Flag开始地址
#define IMAGE_PHONEMAC_START_ADDR         (0x11080)
#define IMAGE_PHONEMAC_END_ADDR           (0x11FFF)   //Sector 16


//****************手机绑定******************************************


//****************手机密码******************************************
#define PHONE_PASSWORD                  (PHONE_MAC_LENGTH-7)


//用户自定义 定义手机设备保存的密码的长度
// A000 00BC     //A--最高位,代表密码是否修改 B--代表绑定设备2是否存在  C-表示绑定设备1是否存在
#define PHONE_FLAG                      (PHONE_MAC_LENGTH-1)




//****************手机密码******************************************


//****************设备名称******************************************
#define GAP_DEVICE_NAME_LEN                     21 








//****************设备名称******************************************






//****************SNV存储********************************************
#define BLE_NVID_CUST_START             0x80  //!< Start of the Customer's NV IDs


// APP_USER Rang 0x80-0x90
#define ENV_SOCKET_STORE_ADDR           0x80  //??255bytes
#define ENV_NAME_STORE_ADDR             0x84
#define ENV_RTC_TIME_ADDR               0x86


#define ENV_STORE_MAC_ADDR              0x87


#define ENV_STORE_VER_ADDR              0x88    //Lewis- 20170504(?????????)


#define ENV_POWER_CALI_ADDR             0x8A
   
#define ENV_STORE_PWRNUM_ADDR           0x8C   


#define BLE_NVID_CUST_END               0x8F  //!< End of the Customer's NV IDs
//****************SNV存储********************************************


//****************固件版本********************************************
#define FirmwareVersion                     "V1.0.33"       //2018.04.24




























#endif

#ifndef   _SOCKET_QUERY_H_
#define   _SOCKET_QUERY_H_




























extern uint32 PowerOnCount;




extern void PD_TYPE_GET(void);
extern void VERSION_GET(void);
extern void FACTORY_MODE(void);
extern void Accumulative_PowerOn(void);
extern void SetDeviceID(void);
extern void GetDeviceID(void);










#endif


#ifndef  _SWITCH_ACTION_H_
#define  _SWITCH_ACTION_H_


#include  "nrf_gpio.h"
#include  "socket_cfg.h"




#define LED_ACTIVE_STATE     1
#define RELAY_ACTIVE_STATE   1




#define     BSP_LED_SET(IO_LED_CTRL)   {nrf_gpio_pin_write(IO_LED_CTRL, LED_ACTIVE_STATE ? 1 : 0);}  
#define     BSP_LED_CLR(IO_LED_CTRL)   {nrf_gpio_pin_write(IO_LED_CTRL, LED_ACTIVE_STATE ? 0 : 1);}




#define     BSP_RELAY_SET(IO_RELAY_CTRL)   {nrf_gpio_pin_write(IO_RELAY_CTRL, RELAY_ACTIVE_STATE ? 1 : 0);}  
#define     BSP_RELAY_CLR(IO_RELAY_CTRL)   {nrf_gpio_pin_write(IO_RELAY_CTRL, RELAY_ACTIVE_STATE ? 0 : 1);}








extern void SwitchOn(void);
extern void SwitchOff(void);
static void sendswithstatus2(void);
static void sendswithstatus(void);
extern void SOCKETOFF(void);
extern void SOCKETON(void);
extern void control_led2(void);
extern void control_led(void);




extern void  SwitchOnAction(int idx);
extern void  SwitchOffAction(int idx);




#endif


#ifndef  _TIMER_CORRECT_H_
#define  _TIMER_CORRECT_H_




extern RTC_Time_t rtcTime;

extern void APPTIME(void);


#endif

#ifndef  _TIMER_MODIF_H_
#define  _TIMER_MODIF_H_




#include "socket_cfg.h"






extern Smart_Socket_t Sockets;
extern uint8 SendClocksIndex;
extern uint8 IsTimerPermit[NUMBER_OF_CLOCKS];






extern void TIMERDELETE(void);
extern void TIMEREDIT(void);
extern void TIMERGET(void);
extern void SetTimerActive(void);




#endif

#ifndef  _TIMER_SET_H_
#define  _TIMER_SET_H_
















extern void TIMERABLE(void);
extern void TEMERLOSE(void);
































#endif



#ifndef  _TIMER_TASK_H_
#define  _TIMER_TASK_H_












extern uint8 Status_count;












extern void ProcessTimerFunc(void);


extern void CountDown_Cancel(uint8 SwitchIdx);
extern void ClientObtainRemainCountTime(int SwitchIdx);
extern void ClientSetCountDown(uint8 SwitchIdx);
















#endif


#ifndef  _USER_CIPHER_MGR_H_
#define  _USER_CIPHER_MGR_H_






#include  "stdint.h"




void  CreatNorUserCipherEvt(void);
void  UartCmdTestStop(void);


void   SetAddCipherFailHandle(uint8_t UserScanIndex);
void  AddCipherTestStop(void);
void  AddCipherTestStart(uint16_t  TaskDelay);
void  CreatAddCipherTestEvt(void);
void  DelCipherTestStop(void);
void   SetDelCipherFailHandle(uint8_t UserScanIndex);
void  DelCipherTestStart(uint16_t  TaskDelay);
void   SetAddCipherFailHandle(uint8_t UserScanIndex);
void  AddCipherTestStart(uint16_t  TaskDelay);
void  GetNormalUserCipherInfor(void);
void   ModifyLockRealTime(void);
void   ModifyLockRealTimeBCD(void);
void  SetTemporUserPassCodeInfor(void);
void  CancleTemporUserPassCodeInfor(void);
void  GetTemporUserPassCodeInfor(void);
void  DoorLockOpen(void);
void  GetMasterPassCode(void);
void UpdataMasterPassCode(void);
void  CreatDelCipherTestEvt(void);
void  CreatUartCmdTestEvt(void);
void  AddNormalUserPassCodeInfor(void);
void DelNormalUserPassCodeInfor(void);






#endif

/**
 * Copyright (c) 2014 - 2017, Nordic Semiconductor ASA
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 * 
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 * 
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 * 
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 * 
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */
/**@file
 * @addtogroup nrf_wdt WDT HAL and driver
 * @ingroup nrf_drivers
 * @brief Watchdog timer (WDT) APIs.
 * @details The WDT HAL provides basic APIs for accessing the registers of the watchdog timer.
 * The WDT driver provides APIs on a higher level.
 * @defgroup nrf_drv_wdt WDT driver
 * @{
 * @ingroup  nrf_wdt
 *
 * @brief    Driver for managing the watchdog timer (WDT).
 */


#ifndef NRF_DRV_WDT_H__
#define NRF_DRV_WDT_H__


#include <stdbool.h>
#include <stdint.h>
#include "sdk_errors.h"
#include "nrf_wdt.h"
#include "sdk_config.h"


#ifdef __cplusplus
extern "C" {
#endif


/**@brief Struct for WDT initialization. */
typedef struct
{
    nrf_wdt_behaviour_t    behaviour;          /**< WDT behaviour when CPU in sleep/halt mode. */
    uint32_t               reload_value;       /**< WDT reload value in ms. */
    uint8_t                interrupt_priority; /**< WDT interrupt priority */
} nrf_drv_wdt_config_t;


/**@brief WDT event handler function type. */
typedef void (*nrf_wdt_event_handler_t)(void);


/**@brief WDT channel id type. */
typedef nrf_wdt_rr_register_t nrf_drv_wdt_channel_id;


#define NRF_DRV_WDT_DEAFULT_CONFIG                                       \
    {                                                                    \
        .behaviour          = (nrf_wdt_behaviour_t)WDT_CONFIG_BEHAVIOUR, \
        .reload_value       = WDT_CONFIG_RELOAD_VALUE,                   \
        .interrupt_priority = WDT_CONFIG_IRQ_PRIORITY,                   \
    }
/**
 * @brief This function initializes watchdog.
 *
 * @param[in] p_config          Initial configuration. Default configuration used if NULL.
 * @param[in] wdt_event_handler specifies event handler provided by user.
 *
 * @note Function asserts if wdt_event_handler is NULL.
 *
 * @return    NRF_SUCCESS on success, otherwise an error code.
 */
ret_code_t nrf_drv_wdt_init(nrf_drv_wdt_config_t const * p_config,
                            nrf_wdt_event_handler_t     wdt_event_handler);


/**
 * @brief This function allocate watchdog channel.
 *
 * @note This function can not be called after nrf_drv_wdt_start(void).
 *
 * @param[out] p_channel_id      ID of granted channel.
 *
 * @return    NRF_SUCCESS on success, otherwise an error code.
 */
ret_code_t nrf_drv_wdt_channel_alloc(nrf_drv_wdt_channel_id * p_channel_id);


/**
 * @brief This function starts watchdog.
 *
 * @note After calling this function the watchdog is started, so the user needs to feed all allocated
 *       watchdog channels to avoid reset. At least one watchdog channel has to be allocated.
 */
void nrf_drv_wdt_enable(void);


/**
 * @brief This function feeds the watchdog.
 *
 * @details Function feeds all allocated watchdog channels.
 */
void nrf_drv_wdt_feed(void);


/**
 * @brief This function feeds the invidual watchdog channel.
 *
 * @param[in] channel_id      ID of watchdog channel.
 */
void nrf_drv_wdt_channel_feed(nrf_drv_wdt_channel_id channel_id);


/**@brief Function for returning a requested task address for the wdt driver module.
 *
 * @param[in]  task                One of the peripheral tasks.
 *
 * @retval     Task address.
 */
__STATIC_INLINE uint32_t nrf_drv_wdt_ppi_task_addr(nrf_wdt_task_t task)
{
    return nrf_wdt_task_address_get(task);
}


/**@brief Function for returning a requested event address for the wdt driver module.
 *
 * @param[in]  event               One of the peripheral events.
 *
 * @retval     Event address
 */
__STATIC_INLINE uint32_t nrf_drv_wdt_ppi_event_addr(nrf_wdt_event_t event)
{
    return nrf_wdt_event_address_get(event);
}


#ifdef __cplusplus
}
#endif


#endif


/** @} */


/**
 * Copyright (c) 2015 - 2017, Nordic Semiconductor ASA
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 * 
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 * 
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 * 
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 * 
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */
/**
 * @defgroup nrf_wdt_hal WDT HAL
 * @{
 * @ingroup nrf_wdt
 *
 * @brief Hardware access layer for accessing the watchdog timer (WDT) peripheral.
 */


#ifndef NRF_WDT_H__
#define NRF_WDT_H__


#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>


#include "nrf.h"


#ifdef __cplusplus
extern "C" {
#endif


#define NRF_WDT_CHANNEL_NUMBER 0x8UL
#define NRF_WDT_RR_VALUE       0x6E524635UL /* Fixed value, shouldn't be modified.*/


#define NRF_WDT_TASK_SET       1UL
#define NRF_WDT_EVENT_CLEAR    0UL


/**
 * @enum nrf_wdt_task_t
 * @brief WDT tasks.
 */
typedef enum
{
    /*lint -save -e30 -esym(628,__INTADDR__)*/
    NRF_WDT_TASK_START = offsetof(NRF_WDT_Type, TASKS_START), /**< Task for starting WDT. */
    /*lint -restore*/
} nrf_wdt_task_t;


/**
 * @enum nrf_wdt_event_t
 * @brief WDT events.
 */
typedef enum
{
    /*lint -save -e30*/
    NRF_WDT_EVENT_TIMEOUT = offsetof(NRF_WDT_Type, EVENTS_TIMEOUT), /**< Event from WDT time-out. */
    /*lint -restore*/
} nrf_wdt_event_t;


/**
 * @enum nrf_wdt_behaviour_t
 * @brief WDT behavior in CPU SLEEP or HALT mode.
 */
typedef enum
{
    NRF_WDT_BEHAVIOUR_RUN_SLEEP        = WDT_CONFIG_SLEEP_Msk,                       /**< WDT will run when CPU is in SLEEP mode. */
    NRF_WDT_BEHAVIOUR_RUN_HALT         = WDT_CONFIG_HALT_Msk,                        /**< WDT will run when CPU is in HALT mode. */
    NRF_WDT_BEHAVIOUR_RUN_SLEEP_HALT   = WDT_CONFIG_SLEEP_Msk | WDT_CONFIG_HALT_Msk, /**< WDT will run when CPU is in SLEEP or HALT mode. */
    NRF_WDT_BEHAVIOUR_PAUSE_SLEEP_HALT = 0,                                          /**< WDT will be paused when CPU is in SLEEP or HALT mode. */
} nrf_wdt_behaviour_t;


/**
 * @enum nrf_wdt_rr_register_t
 * @brief WDT reload request registers.
 */
typedef enum
{
    NRF_WDT_RR0 = 0, /**< Reload request register 0. */
    NRF_WDT_RR1,     /**< Reload request register 1. */
    NRF_WDT_RR2,     /**< Reload request register 2. */
    NRF_WDT_RR3,     /**< Reload request register 3. */
    NRF_WDT_RR4,     /**< Reload request register 4. */
    NRF_WDT_RR5,     /**< Reload request register 5. */
    NRF_WDT_RR6,     /**< Reload request register 6. */
    NRF_WDT_RR7      /**< Reload request register 7. */
} nrf_wdt_rr_register_t;


/**
 * @enum nrf_wdt_int_mask_t
 * @brief WDT interrupts.
 */
typedef enum
{
    NRF_WDT_INT_TIMEOUT_MASK = WDT_INTENSET_TIMEOUT_Msk, /**< WDT interrupt from time-out event. */
} nrf_wdt_int_mask_t;


/**
 * @brief Function for configuring the watchdog behavior when the CPU is sleeping or halted.
 *
 * @param behaviour Watchdog behavior when CPU is in SLEEP or HALT mode.
 */
__STATIC_INLINE void nrf_wdt_behaviour_set(nrf_wdt_behaviour_t behaviour)
{
    NRF_WDT->CONFIG = behaviour;
}




/**
 * @brief Function for starting the watchdog.
 *
 * @param[in]  task             Task.
 */
__STATIC_INLINE void nrf_wdt_task_trigger(nrf_wdt_task_t task)
{
    *((volatile uint32_t *)((uint8_t *)NRF_WDT + task)) = NRF_WDT_TASK_SET;
}




/**
 * @brief Function for clearing the WDT event.
 *
 * @param[in]  event       Event.
 */
__STATIC_INLINE void nrf_wdt_event_clear(nrf_wdt_event_t event)
{
    *((volatile uint32_t *)((uint8_t *)NRF_WDT + (uint32_t)event)) = NRF_WDT_EVENT_CLEAR;
#if __CORTEX_M == 0x04
    volatile uint32_t dummy = *((volatile uint32_t *)((uint8_t *)NRF_WDT + (uint32_t)event));
    (void)dummy;
#endif
}




/**
 * @brief Function for retrieving the state of the WDT event.
 *
 * @param[in]  event       Event.
 *
 * @retval     true              If the event is set.
 * @retval     false             If the event is not set.
 */
__STATIC_INLINE bool nrf_wdt_event_check(nrf_wdt_event_t event)
{
    return (bool)*((volatile uint32_t *)((uint8_t *)NRF_WDT + event));
}




/**
 * @brief Function for enabling a specific interrupt.
 *
 * @param[in]  int_mask         Interrupt.
 */
__STATIC_INLINE void nrf_wdt_int_enable(uint32_t int_mask)
{
    NRF_WDT->INTENSET = int_mask;
}




/**
 * @brief Function for retrieving the state of given interrupt.
 *
 * @param[in]  int_mask         Interrupt.
 *
 * @retval     true                   Interrupt is enabled.
 * @retval     false                  Interrupt is not enabled.
 */
__STATIC_INLINE bool nrf_wdt_int_enable_check(uint32_t int_mask)
{
    return (bool)(NRF_WDT->INTENSET & int_mask);
}




/**
 * @brief Function for disabling a specific interrupt.
 *
 * @param[in]  int_mask         Interrupt.
 */
__STATIC_INLINE void nrf_wdt_int_disable(uint32_t int_mask)
{
    NRF_WDT->INTENCLR = int_mask;
}




/**
 * @brief Function for returning the address of a specific WDT task register.
 *
 * @param[in]  task             Task.
 */
__STATIC_INLINE uint32_t nrf_wdt_task_address_get(nrf_wdt_task_t task)
{
    return ((uint32_t)NRF_WDT + task);
}




/**
 * @brief Function for returning the address of a specific WDT event register.
 *
 * @param[in]  event       Event.
 *
 * @retval     address of requested event register
 */
__STATIC_INLINE uint32_t nrf_wdt_event_address_get(nrf_wdt_event_t event)
{
    return ((uint32_t)NRF_WDT + event);
}




/**
 * @brief Function for retrieving the watchdog status.
 *
 * @retval     true             If the watchdog is started.
 * @retval     false            If the watchdog is not started.
 */
__STATIC_INLINE bool nrf_wdt_started(void)
{
    return (bool)(NRF_WDT->RUNSTATUS);
}




/**
 * @brief Function for retrieving the watchdog reload request status.
 *
 * @param[in]  rr_register      Reload request register to check.
 *
 * @retval     true             If a reload request is running.
 * @retval     false            If no reload request is running.
 */
__STATIC_INLINE bool nrf_wdt_request_status(nrf_wdt_rr_register_t rr_register)
{
    return (bool)(((NRF_WDT->REQSTATUS) >> rr_register) & 0x1UL);
}




/**
 * @brief Function for setting the watchdog reload value.
 *
 * @param[in]  reload_value     Watchdog counter initial value.
 */
__STATIC_INLINE void nrf_wdt_reload_value_set(uint32_t reload_value)
{
    NRF_WDT->CRV = reload_value;
}




/**
 * @brief Function for retrieving the watchdog reload value.
 *
 * @retval                      Reload value.
 */
__STATIC_INLINE uint32_t nrf_wdt_reload_value_get(void)
{
    return (uint32_t)NRF_WDT->CRV;
}




/**
 * @brief Function for enabling a specific reload request register.
 *
 * @param[in]  rr_register       Reload request register to enable.
 */
__STATIC_INLINE void nrf_wdt_reload_request_enable(nrf_wdt_rr_register_t rr_register)
{
    NRF_WDT->RREN |= 0x1UL << rr_register;
}




/**
 * @brief Function for disabling a specific reload request register.
 *
 * @param[in]  rr_register       Reload request register to disable.
 */
__STATIC_INLINE void nrf_wdt_reload_request_disable(nrf_wdt_rr_register_t rr_register)
{
    NRF_WDT->RREN &= ~(0x1UL << rr_register);
}




/**
 * @brief Function for retrieving the status of a specific reload request register.
 *
 * @param[in]  rr_register       Reload request register to check.
 *
 * @retval     true              If the reload request register is enabled.
 * @retval     false             If the reload request register is not enabled.
 */
__STATIC_INLINE bool nrf_wdt_reload_request_is_enabled(nrf_wdt_rr_register_t rr_register)
{
    return (bool)(NRF_WDT->RREN & (0x1UL << rr_register));
}




/**
 * @brief Function for setting a specific reload request register.
 *
 * @param[in]  rr_register       Reload request register to set.
 */
__STATIC_INLINE void nrf_wdt_reload_request_set(nrf_wdt_rr_register_t rr_register)
{
    NRF_WDT->RR[rr_register] = NRF_WDT_RR_VALUE;
}






#ifdef __cplusplus
}
#endif


#endif


/** @} */













































































































































































































































































































































































































































































































































































































猜你喜欢

转载自blog.csdn.net/liqiqian19871027/article/details/80492900