Selaa lähdekoodia

src all commit

astrodom 3 vuotta sitten
vanhempi
commit
98c349c7ae
100 muutettua tiedostoa jossa 122615 lisäystä ja 0 poistoa
  1. 562 0
      BLE_Central.si4project/BLE_Central.SearchResults
  2. 49 0
      BLE_Central.si4project/BLE_Central.bookmarks.xml
  3. BIN
      BLE_Central.si4project/BLE_Central.sip_sym
  4. BIN
      BLE_Central.si4project/BLE_Central.sip_xab
  5. BIN
      BLE_Central.si4project/BLE_Central.sip_xad
  6. BIN
      BLE_Central.si4project/BLE_Central.sip_xc
  7. BIN
      BLE_Central.si4project/BLE_Central.sip_xf
  8. BIN
      BLE_Central.si4project/BLE_Central.sip_xm
  9. BIN
      BLE_Central.si4project/BLE_Central.sip_xr
  10. BIN
      BLE_Central.si4project/BLE_Central.sip_xsb
  11. BIN
      BLE_Central.si4project/BLE_Central.sip_xsd
  12. BIN
      BLE_Central.si4project/BLE_Central.siproj
  13. 22 0
      BLE_Central.si4project/BLE_Central.siproj_settings.xml
  14. BIN
      BLE_Central.si4project/BLE_Central.siwork
  15. 7 0
      BLE_Central.si4project/BLE_Central.snippets.xml
  16. 581 0
      BLE_Central.si4project/Backup/aes(7926).c
  17. 252 0
      BLE_Central.si4project/Backup/app_uart_fifo(502).c
  18. 1725 0
      BLE_Central.si4project/Backup/main(1113).c
  19. 25 0
      BLE_Central.si4project/Backup/main(1397).h
  20. 1420 0
      BLE_Central.si4project/Backup/main(1399).c
  21. 1576 0
      BLE_Central.si4project/Backup/main(1438).c
  22. 1694 0
      BLE_Central.si4project/Backup/main(1470).c
  23. 25 0
      BLE_Central.si4project/Backup/main(1582).h
  24. 1425 0
      BLE_Central.si4project/Backup/main(1735).c
  25. 1416 0
      BLE_Central.si4project/Backup/main(174).c
  26. 1648 0
      BLE_Central.si4project/Backup/main(1771).c
  27. 1719 0
      BLE_Central.si4project/Backup/main(1947).c
  28. 1725 0
      BLE_Central.si4project/Backup/main(2048).c
  29. 1403 0
      BLE_Central.si4project/Backup/main(2072).c
  30. 1724 0
      BLE_Central.si4project/Backup/main(2344).c
  31. 1730 0
      BLE_Central.si4project/Backup/main(3159).c
  32. 1426 0
      BLE_Central.si4project/Backup/main(3197).c
  33. 25 0
      BLE_Central.si4project/Backup/main(3281).h
  34. 1724 0
      BLE_Central.si4project/Backup/main(3414).c
  35. 1717 0
      BLE_Central.si4project/Backup/main(3466).c
  36. 1713 0
      BLE_Central.si4project/Backup/main(3685).c
  37. 1698 0
      BLE_Central.si4project/Backup/main(3897).c
  38. 25 0
      BLE_Central.si4project/Backup/main(3902).h
  39. 1725 0
      BLE_Central.si4project/Backup/main(3917).c
  40. 1420 0
      BLE_Central.si4project/Backup/main(400).c
  41. 1752 0
      BLE_Central.si4project/Backup/main(4204).c
  42. 25 0
      BLE_Central.si4project/Backup/main(4247).h
  43. 1700 0
      BLE_Central.si4project/Backup/main(5194).c
  44. 1645 0
      BLE_Central.si4project/Backup/main(530).c
  45. 25 0
      BLE_Central.si4project/Backup/main(5353).h
  46. 1428 0
      BLE_Central.si4project/Backup/main(5379).c
  47. 1788 0
      BLE_Central.si4project/Backup/main(5567).c
  48. 1786 0
      BLE_Central.si4project/Backup/main(5718).c
  49. 1654 0
      BLE_Central.si4project/Backup/main(5892).c
  50. 1714 0
      BLE_Central.si4project/Backup/main(5937).c
  51. 1741 0
      BLE_Central.si4project/Backup/main(5997).c
  52. 1716 0
      BLE_Central.si4project/Backup/main(6682).c
  53. 1419 0
      BLE_Central.si4project/Backup/main(6900).c
  54. 1722 0
      BLE_Central.si4project/Backup/main(7071).c
  55. 1685 0
      BLE_Central.si4project/Backup/main(7114).c
  56. 1444 0
      BLE_Central.si4project/Backup/main(7218).c
  57. 1468 0
      BLE_Central.si4project/Backup/main(7242).c
  58. 1722 0
      BLE_Central.si4project/Backup/main(7447).c
  59. 1714 0
      BLE_Central.si4project/Backup/main(7469).c
  60. 1420 0
      BLE_Central.si4project/Backup/main(7722).c
  61. 1403 0
      BLE_Central.si4project/Backup/main(7788).c
  62. 1403 0
      BLE_Central.si4project/Backup/main(7818).c
  63. 1728 0
      BLE_Central.si4project/Backup/main(8087).c
  64. 1724 0
      BLE_Central.si4project/Backup/main(8160).c
  65. 1814 0
      BLE_Central.si4project/Backup/nrf_ble_scan(1154).c
  66. 1828 0
      BLE_Central.si4project/Backup/nrf_ble_scan(1206).c
  67. 1807 0
      BLE_Central.si4project/Backup/nrf_ble_scan(1597).c
  68. 1975 0
      BLE_Central.si4project/Backup/nrf_ble_scan(1684).c
  69. 1920 0
      BLE_Central.si4project/Backup/nrf_ble_scan(206).c
  70. 1962 0
      BLE_Central.si4project/Backup/nrf_ble_scan(2207).c
  71. 1812 0
      BLE_Central.si4project/Backup/nrf_ble_scan(2457).c
  72. 1973 0
      BLE_Central.si4project/Backup/nrf_ble_scan(2531).c
  73. 1939 0
      BLE_Central.si4project/Backup/nrf_ble_scan(2974).c
  74. 1984 0
      BLE_Central.si4project/Backup/nrf_ble_scan(3374).c
  75. 1939 0
      BLE_Central.si4project/Backup/nrf_ble_scan(3645).c
  76. 1806 0
      BLE_Central.si4project/Backup/nrf_ble_scan(394).c
  77. 1925 0
      BLE_Central.si4project/Backup/nrf_ble_scan(4424).c
  78. 1795 0
      BLE_Central.si4project/Backup/nrf_ble_scan(4605).c
  79. 1939 0
      BLE_Central.si4project/Backup/nrf_ble_scan(4867).c
  80. 1791 0
      BLE_Central.si4project/Backup/nrf_ble_scan(5076).c
  81. 1961 0
      BLE_Central.si4project/Backup/nrf_ble_scan(5257).c
  82. 1809 0
      BLE_Central.si4project/Backup/nrf_ble_scan(5821).c
  83. 1814 0
      BLE_Central.si4project/Backup/nrf_ble_scan(585).c
  84. 1814 0
      BLE_Central.si4project/Backup/nrf_ble_scan(605).c
  85. 1926 0
      BLE_Central.si4project/Backup/nrf_ble_scan(6747).c
  86. 1830 0
      BLE_Central.si4project/Backup/nrf_ble_scan(7374).c
  87. 1786 0
      BLE_Central.si4project/Backup/nrf_ble_scan(7773).c
  88. 1791 0
      BLE_Central.si4project/Backup/nrf_ble_scan(88).c
  89. 305 0
      BLE_Central.si4project/Backup/nrf_sdh(5646).h
  90. 402 0
      BLE_Central.si4project/Backup/nrf_sdh(7960).c
  91. 1565 0
      BLE_Central.si4project/Backup/our_service(1008).c
  92. 342 0
      BLE_Central.si4project/Backup/our_service(1225).h
  93. 247 0
      BLE_Central.si4project/Backup/our_service(142).h
  94. 331 0
      BLE_Central.si4project/Backup/our_service(145).h
  95. 319 0
      BLE_Central.si4project/Backup/our_service(177).h
  96. 244 0
      BLE_Central.si4project/Backup/our_service(2634).h
  97. 1461 0
      BLE_Central.si4project/Backup/our_service(2862).c
  98. 1427 0
      BLE_Central.si4project/Backup/our_service(3473).c
  99. 1578 0
      BLE_Central.si4project/Backup/our_service(3512).c
  100. 1427 0
      BLE_Central.si4project/Backup/our_service(4012).c

+ 562 - 0
BLE_Central.si4project/BLE_Central.SearchResults

@@ -0,0 +1,562 @@
+---- IES600RB_VER_LOW Matches (3 in 2 files) ----
+main.h (examples\ble_central\ble_app_uart_c) line 16 : #define IES600RB_VER_LOW	1
+Server_Answer_Version in our_service.c (examples\ble_central\ble_app_uart_c) : 		SvrSendBuff[12] =  IES600RB_VER_LOW;
+Server_Answer_Upgread in our_service.c (examples\ble_central\ble_app_uart_c) : 		SvrSendBuff[12] =  IES600RB_VER_LOW;
+---- ble_nus_c_evt_handler Matches (2 in 1 files) ----
+main.c (examples\ble_central\ble_app_uart_c) line 587 : static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+nus_c_init in main.c (examples\ble_central\ble_app_uart_c) :     init.evt_handler   = ble_nus_c_evt_handler;
+---- WES Matches (1 in 1 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						NRF_LOG_RAW_INFO("WES ");
+---- WES Matches (97 in 32 files) ----
+app_pwm_init in app_pwm.c (components\libraries\pwm) :         .interrupt_priority = APP_IRQ_PRIORITY_LOWEST,
+app_simple_timer.h (components\libraries\simple_timer) line 115 :  *        anymore to reach lowest power consumption in system.
+app_simple_timer.h (components\libraries\simple_timer) line 117 :  * @note  The function switches off the internal core of the timer to reach lowest power consumption
+app_timer_rtx.c (components\libraries\timer) line 50 : #define RTC1_IRQ_PRI        APP_IRQ_PRIORITY_LOWEST    /**< Priority of the RTC1 interrupt. */
+app_usbd_hid_kbd.h (components\libraries\usbd\class\hid\kbd) line 227 :    APP_USBD_HID_KBD_GLOBAL_DEF(my_awesome_kbd, 0, NRF_DRV_USBD_EPIN1, NULL, APP_USBD_HID_SUBCLASS_BOOT);
+app_usbd_hid_mouse.h (components\libraries\usbd\class\hid\mouse) line 94 :    APP_USBD_HID_MOUSE_GLOBAL_DEF(my_awesome_mouse, 0, NRF_DRV_USBD_EPIN1, 3, NULL);
+app_usbd_langid.h (components\libraries\usbd) line 62 :  * Offset of the lowest bit of primary language identifier.
+app_usbd_langid.h (components\libraries\usbd) line 81 :  * Offset of the lowest bit of sublanguage identifier.
+app_util.h (components\libraries\util) line 440 :  * @param[in] boff Lowest bit number
+app_util.h (components\libraries\util) line 451 :  * @param[in] boff Lowest bit number
+app_util.h (components\libraries\util) line 495 :  * @param[in] boff Lowest bit number
+app_util.h (components\libraries\util) line 513 :  * @brief Get lowest bit number in the field
+app_util.h (components\libraries\util) line 519 :  * @return Lowest bit number in given bit-field
+app_util_platform.h (components\libraries\util) line 73 : #define _PRIO_APP_LOWEST    3
+app_util_platform.h (components\libraries\util) line 83 : #define _PRIO_APP_LOWEST    7
+app_util_platform.h (components\libraries\util) line 107 :     APP_IRQ_PRIORITY_LOWEST  = _PRIO_APP_LOWEST,  /**< Running in Application Lowest interrupt level. */
+ble_cts_c.c (components\ble\ble_services\ble_cts_c) line 53 : #define CTS_YEAR_MIN 1582                     /**< The lowest valid Current Time year is the year when the Western calendar was introduced. */
+ble_gap.h (components\softdevice\s132\headers) line 526 : #define BLE_GAP_CP_MIN_CONN_INTVL_MIN            0x0006  /**< Lowest minimum connection interval permitted, in units of 1.25 ms, i.e. 7.5 ms. */
+ble_gap.h (components\softdevice\s132\headers) line 529 : #define BLE_GAP_CP_MAX_CONN_INTVL_MIN            0x0006  /**< Lowest maximum connection interval permitted, in units of 1.25 ms, i.e. 7.5 ms. */
+ble_gap.h (components\softdevice\s132\headers) line 533 : #define BLE_GAP_CP_CONN_SUP_TIMEOUT_MIN          0x000A  /**< Lowest supervision timeout permitted, in units of 10 ms, i.e. 100 ms. */
+ble_gap.h (components\softdevice\s132\headers) line 2740 :  *          having the lowest priority of all roles and modules, this may not be possible. In that
+es_security_tlm_to_etlm in es_security.c (components\ble\ble_services\eddystone) :     // Take the current timestamp and clear the lowest K bits, use it as nonce.
+slip_uart_open in hci_slip.c (components\libraries\hci) :                              APP_IRQ_PRIORITY_LOWEST);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						NRF_LOG_RAW_INFO("WES");
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 									NRF_LOG_INFO("Send WESACK");
+uart_init in main.c (examples\ble_central\ble_app_uart_c) :                        APP_IRQ_PRIORITY_LOWEST,
+nrfx_swi.h (modules\nrfx\drivers\include) line 80 : #define NRFX_SWI_DEFAULT_PRIORITY  APP_IRQ_PRIORITY_LOWEST
+nrfx_timer.h (modules\nrfx\drivers\include) line 161 :  * The timer will allow to enter the lowest possible SYSTEM_ON state
+nrfx_uarte_uninit in nrfx_uarte.c (modules\nrfx\drivers\src) :     // to achieve the lowest power consumption.
+nrfx_uarte_tx in nrfx_uarte.c (modules\nrfx\drivers\src) :             // the lowest possible level of the UARTE power consumption.
+uarte_irq_handler in nrfx_uarte.c (modules\nrfx\drivers\src) :         // the lowest possible level of the UARTE power consumption.
+nrfx_usbd.c (modules\nrfx\drivers\src) line 125 :  * @brief Lowest position of bit for IN endpoint.
+nrfx_usbd.c (modules\nrfx\drivers\src) line 133 :  * @brief Lowest position of bit for OUT endpoint.
+nrf_ble_gatt.c (components\ble\nrf_ble_gatt) line 196 :  * @details The effective ATT MTU is set to the lowest between what we requested and the peer's
+on_exchange_mtu_rsp_evt in nrf_ble_gatt.c (components\ble\nrf_ble_gatt) :     // Determine the lowest MTU between our own desired MTU and the peer's.
+HS_AdParser in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 		else if( strncmp("ICSWES", data+1, 6) == 0 )
+HS_AdParser in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 			NRF_LOG_RAW_INFO("==> ICSWES : ");
+HS_AdParser in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 			SystemManager.DevType = DEV_WES_ADV;
+nrf_ble_scan.c (components\ble\nrf_ble_scan) line 1067 :         }else if( strncmp("ICSWES", data+1, 6) == 0 )
+nrf_ble_scan.c (components\ble\nrf_ble_scan) line 1073 : 			   SystemManager.DevType = DEV_WES_ADV;
+nrf_ble_scan_on_adv_report in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 	else if( SystemManager.DevType == DEV_WES_ADV )
+nrf_ble_scan_on_adv_report in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+nrf_ble_scan_on_adv_report in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 			SystemManager.Encryption_Mode = AES_ENC_WES;
+nrf_crypto_rng.h (components\libraries\crypto) line 194 :  *          element / lowest address.
+irq_prio_inc in nrf_libuarte_async.c (components\libraries\libuarte) :             APP_IRQ_PRIORITY_LOWEST, /* 6 + 1 = 7 */
+nrf_libuarte_async_init in nrf_libuarte_async.c (components\libraries\libuarte) :     if (p_config->int_prio == APP_IRQ_PRIORITY_LOWEST ||
+nrf_libuarte_async_init in nrf_libuarte_async.c (components\libraries\libuarte) :         NRF_LOG_ERROR("Too low priority. Lowest possible priority is %d", APP_IRQ_PRIORITY_LOW);
+nrf_power.h (modules\nrfx\hal) line 571 :  * clear its settings (set to the lowest voltage).
+nrf_soc.h (components\softdevice\s132\headers) line 63 : /**@brief The number of the lowest SVC number reserved for the SoC library. */
+nrf_stack_info.h (components\libraries\stack_info) line 69 :  * @brief Base (lowest) stack address.
+our_service.h (examples\ble_central\ble_app_uart_c) line 104 : #define DEV_WES				4
+our_service.h (examples\ble_central\ble_app_uart_c) line 105 : #define DEV_WES_EMG			5			// 비상벨 버튼 
+our_service.h (examples\ble_central\ble_app_uart_c) line 106 : #define DEV_WES_ALIVE		6			// 수신기 Alive
+our_service.h (examples\ble_central\ble_app_uart_c) line 107 : #define DEV_WES_REG			7			// 수신기 목록 
+our_service.h (examples\ble_central\ble_app_uart_c) line 108 : #define DEV_WES_ADV			8			// 수신기 
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :                              pm_peer_id_t * p_lowest_ranked_peer,
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :                              uint32_t     * p_lowest_rank)
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :     uint32_t             lowest_rank  = 0xFFFFFFFF;
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :     pm_peer_id_t         lowest_ranked_peer  = PM_PEER_ID_INVALID;
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :             if (peer_rank < lowest_rank)
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :                 lowest_rank      = peer_rank;
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :                 lowest_ranked_peer = peer_id;
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :         if ((highest_ranked_peer == PM_PEER_ID_INVALID) || (lowest_ranked_peer == PM_PEER_ID_INVALID))
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :         if (p_lowest_ranked_peer != NULL)
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :             *p_lowest_ranked_peer = lowest_ranked_peer;
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :         if (p_lowest_rank != NULL)
+pm_peer_ranks_get in peer_manager.c (components\ble\peer_manager) :             *p_lowest_rank = lowest_rank;
+peer_manager.h (components\ble\peer_manager) line 765 : /**@brief Function for finding the highest and lowest ranked peers.
+peer_manager.h (components\ble\peer_manager) line 779 :  * @param[out] p_lowest_ranked_peer   The peer ID with the lowest rank of all peers, for example,
+peer_manager.h (components\ble\peer_manager) line 781 :  * @param[out] p_lowest_rank          The lowest rank.
+pm_peer_ranks_get in peer_manager.h (components\ble\peer_manager) :                              pm_peer_id_t * p_lowest_ranked_peer,
+pm_peer_ranks_get in peer_manager.h (components\ble\peer_manager) :                              uint32_t     * p_lowest_rank);
+pm_handler_flash_clean in peer_manager_handler.c (components\ble\peer_manager) :                         NRF_LOG_INFO("Deleting lowest ranked peer (peer_id: %d)", peer_id_to_delete);
+peer_manager_handler.h (components\ble\peer_manager) line 90 :  *  - Deletes the lowest ranked peer(s) when garbage collection is insufficient.
+sdk_config.h (config\nrf52832\config) line 101 : // <0=> Lowest ANT Tx power level setting. (-20dBm) 
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 99 : #define AES_ENC_WES		4
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 100 : #define AES_ENC_WES_EMG	5
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 101 : #define AES_ENC_WES_ALV	6
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 102 : #define AES_ENC_WES_TST	7
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 103 : #define AES_ENC_WES_REG	8
+utf8DecodeRune in utf.c (external\utf_converter) : 	uint8_t lowestAllowed, highestAllowed;
+utf8DecodeRune in utf.c (external\utf_converter) : 	lowestAllowed = 0x80;
+utf8DecodeRune in utf.c (external\utf_converter) : 		lowestAllowed = 0xA0;
+utf8DecodeRune in utf.c (external\utf_converter) : 		lowestAllowed = 0x90;
+utf8DecodeRune in utf.c (external\utf_converter) : 		if (c < lowestAllowed || c > highestAllowed) {
+utf8DecodeRune in utf.c (external\utf_converter) : 		// the old lowestAllowed and highestAllowed is only for the first continuation byte
+utf8DecodeRune in utf.c (external\utf_converter) : 		lowestAllowed = 0x80;
+---- AES128_ECB_encrypt Matches (8 in 3 files) ----
+aes.c (examples\ble_central\ble_app_uart_c) line 453 : void AES128_ECB_encrypt(uint8_t* input, const uint8_t* key, uint8_t* output)
+aes.h (examples\ble_central\ble_app_uart_c) line 25 : void AES128_ECB_encrypt(uint8_t* input, const uint8_t* key, uint8_t *output);
+test_encrypt_ecb_verbose in sysmgr.c (examples\ble_central\ble_app_uart_c) :         AES128_ECB_encrypt(plain_text + (i*16), key, buf+(i*16));
+test_encrypt_ecb in sysmgr.c (examples\ble_central\ble_app_uart_c) :   AES128_ECB_encrypt(in, key, buffer);
+CarEncryptEcb in sysmgr.c (examples\ble_central\ble_app_uart_c) :   AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+CarEncryptEcbACK in sysmgr.c (examples\ble_central\ble_app_uart_c) : 	AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+PcaEncryptEcb in sysmgr.c (examples\ble_central\ble_app_uart_c) :   AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+PcaEncryptEcbACK in sysmgr.c (examples\ble_central\ble_app_uart_c) : 	AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+---- AES_ENC_CAR Matches (7 in 4 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 				case AES_ENC_CAR:
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					CarEncryptEcb( AES_ENC_CAR );
+HS_AdParser in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 					SystemManager.Encryption_Mode = AES_ENC_CAR;
+nrf_ble_scan.c (components\ble\nrf_ble_scan) line 1042 : 			SystemManager.BandMode = AES_ENC_CAR;
+CarEncryptEcb in sysmgr.c (examples\ble_central\ble_app_uart_c) :   if( mode == AES_ENC_CAR )
+PcaEncryptEcb in sysmgr.c (examples\ble_central\ble_app_uart_c) :   if( mode == AES_ENC_CAR )
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 96 : #define AES_ENC_CAR		1
+---- CarEncryptEcb Matches (11 in 3 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					CarEncryptEcb( AES_ENC_WES );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					CarEncryptEcb( AES_ENC_CAR );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					CarEncryptEcb( AES_ENC_EMG );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					CarEncryptEcb( AES_ENC_PCA );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							CarEncryptEcbACK(SystemManager.BandType);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							CarEncryptEcbACK(SystemManager.BandType);
+sysmgr.c (examples\ble_central\ble_app_uart_c) line 918 : void CarEncryptEcb(int mode)
+sysmgr.c (examples\ble_central\ble_app_uart_c) line 958 : void CarEncryptEcbACK(char type)
+sysmgr.c (examples\ble_central\ble_app_uart_c) line 1191 : 	//CarEncryptEcb();
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 160 : void CarEncryptEcb(int mode);
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 162 : void CarEncryptEcbACK(char type);
+---- CarEncryptEcbACK Matches (4 in 3 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							CarEncryptEcbACK(SystemManager.BandType);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							CarEncryptEcbACK(SystemManager.BandType);
+sysmgr.c (examples\ble_central\ble_app_uart_c) line 958 : void CarEncryptEcbACK(char type)
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 171 : void CarEncryptEcbACK(char type);
+---- Wes_Encryp_Ecb Matches (4 in 3 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					Wes_Encryp_Ecb();
+sysmgr.c (examples\ble_central\ble_app_uart_c) line 853 : void Wes_Encryp_Ecb()
+Wes_Encryp_Ecb in sysmgr.c (examples\ble_central\ble_app_uart_c) : 	NRF_LOG_RAW_INFO("Wes_Encryp_Ecb : 0x%04x\n", tempVal);
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 163 : void Wes_Encryp_Ecb();
+---- =================  DEV_WES_ADV Matches (1 in 1 files) ----
+nrf_ble_scan_on_adv_report in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+---- =================  DEV_WES_ADV Matches (1 in 1 files) ----
+nrf_ble_scan_on_adv_report in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+---- ==> ICSWES Matches (1 in 1 files) ----
+HS_AdParser in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 			NRF_LOG_RAW_INFO("==> ICSWES : ");
+---- <--------------------- BLE_GAP_EVT_CONNECTED --... Matches (1 in 1 files) ----
+nrf_ble_scan_on_ble_evt in nrf_ble_scan.c (components\ble\nrf_ble_scan) :             NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+---- Wes_Encrypt_EcbACK Matches (2 in 2 files) ----
+sysmgr.c (examples\ble_central\ble_app_uart_c) line 877 : void Wes_Encrypt_EcbACK()
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 164 : void Wes_Encrypt_EcbACK();
+---- CarEncryptEcbACK Matches (4 in 3 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							CarEncryptEcbACK(SystemManager.BandType);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							CarEncryptEcbACK(SystemManager.BandType);
+sysmgr.c (examples\ble_central\ble_app_uart_c) line 958 : void CarEncryptEcbACK(char type)
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 171 : void CarEncryptEcbACK(char type);
+---- SendAck Matches (5 in 2 files) ----
+ParseEventServer in our_service.c (examples\ble_central\ble_app_uart_c) : 						SendAck(COM_TYPE_SVR_RECV_REG_ANSWER);
+ParseEventServer in our_service.c (examples\ble_central\ble_app_uart_c) : 					SendAck(COM_TYPE_SVR_RECV_INIT_ANSWER);
+our_service.c (examples\ble_central\ble_app_uart_c) line 654 : void SendAck(uint8_t cmd)
+SendAck in our_service.c (examples\ble_central\ble_app_uart_c) : 	NRF_LOG_RAW_INFO("===> SendAck()\n");
+our_service.h (examples\ble_central\ble_app_uart_c) line 318 : void SendAck(uint8_t cmd);
+---- SendEmergency() Matches (4 in 3 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 										SendEmergency();
+our_service.c (examples\ble_central\ble_app_uart_c) line 698 : void SendEmergency()
+SendEmergency in our_service.c (examples\ble_central\ble_app_uart_c) : 	NRF_LOG_RAW_INFO("===> SendEmergency()\n");
+our_service.h (examples\ble_central\ble_app_uart_c) line 312 : void SendEmergency();
+---- ===============================================... Matches (1 in 1 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) :             NRF_LOG_INFO("=======================================================ble_nus_c_evt_handler -- BLE_NUS_C_EVT_DISCOVERY_COMPLETE");
+---- DEV_NUS_TEST Matches (2 in 2 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							case DEV_NUS_TEST:
+our_service.h (examples\ble_central\ble_app_uart_c) line 115 : #define DEV_NUS_TEST		2
+---- SystemManager.AesEncData Matches (66 in 2 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 											ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 										ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 											ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 										ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 									ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 								ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[0] = SystemManager.AesEncData[4];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[1] = SystemManager.AesEncData[5];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[2] = SystemManager.AesEncData[6];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[3] = SystemManager.AesEncData[7];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Key_Num = SystemManager.AesEncData[12];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Key_Type = SystemManager.AesEncData[13];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[0] = SystemManager.AesEncData[4];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[1] = SystemManager.AesEncData[5];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[2] = SystemManager.AesEncData[6];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[3] = SystemManager.AesEncData[7];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Key_Num = SystemManager.AesEncData[12];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Key_Type = SystemManager.AesEncData[13];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[0] = SystemManager.AesEncData[4];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[1] = SystemManager.AesEncData[5];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[2] = SystemManager.AesEncData[6];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Site[3] = SystemManager.AesEncData[7];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Key_Num = SystemManager.AesEncData[12];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Key_Type = SystemManager.AesEncData[13];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+Wes_Encryp_Ecb in sysmgr.c (examples\ble_central\ble_app_uart_c) : 	AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+Wes_Encrypt_EcbACK in sysmgr.c (examples\ble_central\ble_app_uart_c) : 	AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+CarEncryptEcb in sysmgr.c (examples\ble_central\ble_app_uart_c) : 	AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+CarEncryptEcbACK in sysmgr.c (examples\ble_central\ble_app_uart_c) : 	AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+PcaEncryptEcb in sysmgr.c (examples\ble_central\ble_app_uart_c) :   AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+PcaEncryptEcbACK in sysmgr.c (examples\ble_central\ble_app_uart_c) : 	AES128_ECB_encrypt(in, key, SystemManager.AesEncData);
+---- <--------------------- BLE_GAP_EVT_CONNECTED --... Matches (1 in 1 files) ----
+nrf_ble_scan_on_ble_evt in nrf_ble_scan.c (components\ble\nrf_ble_scan) :             NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+---- evt_handler Matches (298 in 79 files) ----
+attr_len2_parse in ancs_attr_parser.c (components\ble\ble_services\ble_ancs_c) :             p_ancs->evt_handler(&p_ancs->evt);
+attr_data_parse in ancs_attr_parser.c (components\ble\ble_services\ble_ancs_c) :             p_ancs->evt_handler(&p_ancs->evt);
+attr_skip in ancs_attr_parser.c (components\ble\ble_services\ble_ancs_c) :             p_ancs->evt_handler(&p_ancs->evt);
+ble_advertising_init in ble_advertising.c (components\ble\ble_advertising) :     p_advertising->evt_handler                    = p_init->evt_handler;
+ble_advertising_start in ble_advertising.c (components\ble\ble_advertising) :         if (p_advertising->evt_handler != NULL)
+ble_advertising_start in ble_advertising.c (components\ble\ble_advertising) :             p_advertising->evt_handler(BLE_ADV_EVT_PEER_ADDR_REQUEST);
+ble_advertising_start in ble_advertising.c (components\ble\ble_advertising) :     if ((p_advertising->evt_handler != NULL) &&
+ble_advertising_start in ble_advertising.c (components\ble\ble_advertising) :         p_advertising->evt_handler(BLE_ADV_EVT_WHITELIST_REQUEST);
+ble_advertising_start in ble_advertising.c (components\ble\ble_advertising) :     if (p_advertising->evt_handler != NULL)
+ble_advertising_start in ble_advertising.c (components\ble\ble_advertising) :         p_advertising->evt_handler(p_advertising->adv_evt);
+{anonble_advertising_t} in ble_advertising.h (components\ble\ble_advertising) :     ble_adv_evt_handler_t   evt_handler;                                      /**< Handler for the advertising events. Can be initialized as NULL if no handling is implemented on in the main application. */
+{anonble_advertising_init_t} in ble_advertising.h (components\ble\ble_advertising) :     ble_adv_evt_handler_t   evt_handler;   /**< Event handler that will be called upon advertising events. */
+ble_ans_c_on_db_disc_evt in ble_ans_c.c (components\ble\ble_services\ble_ans_c) :     p_ans->evt_handler(&evt);
+event_notify in ble_ans_c.c (components\ble\ble_services\ble_ans_c) :     p_ans->evt_handler(&event);
+event_read_rsp in ble_ans_c.c (components\ble\ble_services\ble_ans_c) :     p_ans->evt_handler(&event);
+event_disconnect in ble_ans_c.c (components\ble\ble_services\ble_ans_c) :         p_ans->evt_handler(&evt);
+ble_ans_c_init in ble_ans_c.c (components\ble\ble_services\ble_ans_c) :     VERIFY_PARAM_NOT_NULL(p_ans_init->evt_handler);
+ble_ans_c_init in ble_ans_c.c (components\ble\ble_services\ble_ans_c) :     p_ans->evt_handler         = p_ans_init->evt_handler;
+ble_ans_c_s in ble_ans_c.h (components\ble\ble_services\ble_ans_c) :     ble_ans_c_evt_handler_t             evt_handler;          /**< Event handler to be called for handling events in the Alert Notification Client Application. */
+{anonble_ans_c_init_t} in ble_ans_c.h (components\ble\ble_services\ble_ans_c) :     ble_ans_c_evt_handler_t             evt_handler;          /**< Event handler to be called for handling events in the Battery Service. */
+on_write in ble_bas.c (components\ble\ble_services\ble_bas) :         if (p_bas->evt_handler == NULL)
+on_write in ble_bas.c (components\ble\ble_services\ble_bas) :         p_bas->evt_handler(p_bas, &evt);
+ble_bas_init in ble_bas.c (components\ble\ble_services\ble_bas) :     p_bas->evt_handler               = p_bas_init->evt_handler;
+{anonble_bas_init_t} in ble_bas.h (components\ble\ble_services\ble_bas) :     ble_bas_evt_handler_t  evt_handler;                    /**< Event handler to be called for handling events in the Battery Service. */
+ble_bas_s in ble_bas.h (components\ble\ble_services\ble_bas) :     ble_bas_evt_handler_t    evt_handler;               /**< Event handler to be called for handling events in the Battery Service. */
+on_read_rsp in ble_bas_c.c (components\ble\ble_services\ble_bas_c) :         p_bas_c->evt_handler(p_bas_c, &evt);
+on_hvx in ble_bas_c.c (components\ble\ble_services\ble_bas_c) :             p_ble_bas_c->evt_handler(p_ble_bas_c, &ble_bas_c_evt);
+ble_bas_on_db_disc_evt in ble_bas_c.c (components\ble\ble_services\ble_bas_c) :         p_ble_bas_c->evt_handler(p_ble_bas_c, &evt);
+ble_bas_c_init in ble_bas_c.c (components\ble\ble_services\ble_bas_c) :     p_ble_bas_c->evt_handler                = p_ble_bas_c_init->evt_handler;
+ble_bas_c_s in ble_bas_c.h (components\ble\ble_services\ble_bas_c) :     ble_bas_c_evt_handler_t   evt_handler;     /**< Application event handler to be called when there is an event related to the Battery Service. */
+{anonble_bas_c_init_t} in ble_bas_c.h (components\ble\ble_services\ble_bas_c) :     ble_bas_c_evt_handler_t   evt_handler;  /**< Event handler to be called by the Battery Service Client module when there is an event related to the Battery Service. */
+on_cccd_write in ble_bps.c (components\ble\ble_services\ble_bps) :         if (p_bps->evt_handler != NULL)
+on_cccd_write in ble_bps.c (components\ble\ble_services\ble_bps) :             p_bps->evt_handler(p_bps, &evt);
+on_hvc in ble_bps.c (components\ble\ble_services\ble_bps) :         p_bps->evt_handler(p_bps, &evt);
+ble_bps_init in ble_bps.c (components\ble\ble_services\ble_bps) :     p_bps->evt_handler   = p_bps_init->evt_handler;
+{anonble_bps_init_t} in ble_bps.h (components\ble\ble_services\ble_bps) :     ble_bps_evt_handler_t        evt_handler;                               /**< Event handler to be called for handling events in the Blood Pressure Service. */
+ble_bps_s in ble_bps.h (components\ble\ble_services\ble_bps) :     ble_bps_evt_handler_t        evt_handler;                               /**< Event handler to be called for handling events in the Blood Pressure Service. */
+update_timeout_handler in ble_conn_params.c (components\ble\common) :             if (m_conn_params_config.evt_handler != NULL)
+update_timeout_handler in ble_conn_params.c (components\ble\common) :                 m_conn_params_config.evt_handler(&evt);
+conn_params_negotiation in ble_conn_params.c (components\ble\common) :         if (m_conn_params_config.evt_handler != NULL)
+conn_params_negotiation in ble_conn_params.c (components\ble\common) :             m_conn_params_config.evt_handler(&evt);
+{anonble_conn_params_init_t} in ble_conn_params.h (components\ble\common) :     ble_conn_params_evt_handler_t evt_handler;                      //!< Event handler to be called for handling events in the Connection Parameters.
+on_meas_cccd_write in ble_cscs.c (components\ble\ble_services\ble_cscs) :         if (p_cscs->evt_handler != NULL)
+on_meas_cccd_write in ble_cscs.c (components\ble\ble_services\ble_cscs) :             p_cscs->evt_handler(p_cscs, &evt);
+ble_cscs_init in ble_cscs.c (components\ble\ble_services\ble_cscs) :     p_cscs->evt_handler = p_cscs_init->evt_handler;
+ble_cscs_init in ble_cscs.c (components\ble\ble_services\ble_cscs) :     sc_ctrlpt_init.evt_handler                   = p_cscs_init->ctrlpt_evt_handler;
+{anonble_cscs_init_t} in ble_cscs.h (components\ble\ble_services\ble_cscs) :     ble_cscs_evt_handler_t       evt_handler;                           /**< Event handler to be called for handling events in the Cycling Speed and Cadence Service. */
+ble_cscs_s in ble_cscs.h (components\ble\ble_services\ble_cscs) :     ble_cscs_evt_handler_t       evt_handler;                           /**< Event handler to be called for handling events in the Cycling Speed and Cadence Service. */
+ble_cts_c_on_db_disc_evt in ble_cts_c.c (components\ble\ble_services\ble_cts_c) :     p_cts->evt_handler(p_cts, &evt);
+ble_cts_c_init in ble_cts_c.c (components\ble\ble_services\ble_cts_c) :     VERIFY_PARAM_NOT_NULL(p_cts_init->evt_handler);
+ble_cts_c_init in ble_cts_c.c (components\ble\ble_services\ble_cts_c) :     p_cts->evt_handler                  = p_cts_init->evt_handler;
+current_time_read in ble_cts_c.c (components\ble\ble_services\ble_cts_c) :         p_cts->evt_handler(p_cts, &evt);
+on_disconnect in ble_cts_c.c (components\ble\ble_services\ble_cts_c) :         p_cts->evt_handler(p_cts, &evt);
+ble_cts_c_s in ble_cts_c.h (components\ble\ble_services\ble_cts_c) :     ble_cts_c_evt_handler_t   evt_handler;         /**< Event handler to be called for handling events from the Current Time Service client. */
+{anonble_cts_c_init_t} in ble_cts_c.h (components\ble\ble_services\ble_cts_c) :     ble_cts_c_evt_handler_t   evt_handler;   /**< Event handler to be called for handling events from the Current Time Service client. */
+ble_db_discovery.c (components\ble\ble_db_discovery) line 68 :  * @retval    evt_handler Event handler of the module, registered for the given service UUID.
+pending_user_evts_send in ble_db_discovery.c (components\ble\ble_db_discovery) :         p_db_discovery->pending_usr_evts[i].evt_handler(&(p_db_discovery->pending_usr_evts[i].evt));
+discovery_complete_evt_trigger in ble_db_discovery.c (components\ble\ble_db_discovery) :             p_db_discovery->pending_usr_evts[p_db_discovery->pending_usr_evt_index].evt_handler = p_evt_handler;
+ble_db_discovery_init in ble_db_discovery.c (components\ble\ble_db_discovery) :     VERIFY_PARAM_NOT_NULL(p_db_init->evt_handler);
+ble_db_discovery_init in ble_db_discovery.c (components\ble\ble_db_discovery) :     m_evt_handler           = p_db_init->evt_handler;
+{anonble_db_discovery_user_evt_t} in ble_db_discovery.h (components\ble\ble_db_discovery) :     ble_db_discovery_evt_handler_t evt_handler;  /**< Event handler which should be called to raise this event. */
+{anonble_db_discovery_init_t} in ble_db_discovery.h (components\ble\ble_db_discovery) :     ble_db_discovery_evt_handler_t   evt_handler;  /**< Event handler to be called by the DB Discovery module. */
+on_hvc in ble_dfu.c (components\ble\ble_services\ble_dfu) :                 m_dfu.evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED);
+ble_dfu_buttonless_bootloader_start_finalize in ble_dfu.c (components\ble\ble_services\ble_dfu) :     m_dfu.evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER);
+ble_dfu_buttonless_init in ble_dfu.c (components\ble\ble_services\ble_dfu) :     m_dfu.evt_handler                  = p_dfu_init->evt_handler;
+ble_dfu_buttonless_init in ble_dfu.c (components\ble\ble_services\ble_dfu) :     if (m_dfu.evt_handler == NULL)
+ble_dfu_buttonless_init in ble_dfu.c (components\ble\ble_services\ble_dfu) :         m_dfu.evt_handler = dummy_evt_handler;
+{anonble_dfu_buttonless_t} in ble_dfu.h (components\ble\ble_services\ble_dfu) :     ble_dfu_buttonless_evt_handler_t    evt_handler;                    /**< Event handler that is called upon Buttonless DFU events. See @ref ble_dfu_buttonless_evt_type_t. */
+{anonble_dfu_buttonless_init_t} in ble_dfu.h (components\ble\ble_services\ble_dfu) :     ble_dfu_buttonless_evt_handler_t   evt_handler;                       /**< Bootloader event handler. */
+pm_evt_handler in ble_dfu_bonded.c (components\ble\ble_services\ble_dfu) :                         mp_dfu->evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED);
+pm_evt_handler in ble_dfu_bonded.c (components\ble\ble_services\ble_dfu) :                 mp_dfu->evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED);
+ble_dfu_buttonless_on_sys_evt in ble_dfu_bonded.c (components\ble\ble_services\ble_dfu) :             mp_dfu->evt_handler(BLE_DFU_EVT_RESPONSE_SEND_ERROR);
+ble_dfu_buttonless_on_sys_evt in ble_dfu_bonded.c (components\ble\ble_services\ble_dfu) :             mp_dfu->evt_handler(BLE_DFU_EVT_RESPONSE_SEND_ERROR);
+ble_dfu_buttonless_on_sys_evt in ble_dfu_bonded.c (components\ble\ble_services\ble_dfu) :         mp_dfu->evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED);
+ble_dfu_buttonless_on_ctrl_pt_write in ble_dfu_bonded.c (components\ble\ble_services\ble_dfu) :             mp_dfu->evt_handler(BLE_DFU_EVT_RESPONSE_SEND_ERROR);
+ble_dfu_buttonless_on_ctrl_pt_write in ble_dfu_bonded.c (components\ble\ble_services\ble_dfu) :         mp_dfu->evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED);
+ble_dfu_buttonless_bootloader_start_prepare in ble_dfu_bonded.c (components\ble\ble_services\ble_dfu) :     mp_dfu->evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER_PREPARE);
+enter_bootloader in ble_dfu_unbonded.c (components\ble\ble_services\ble_dfu) :             mp_dfu->evt_handler(BLE_DFU_EVT_RESPONSE_SEND_ERROR);
+ble_dfu_buttonless_on_sys_evt in ble_dfu_unbonded.c (components\ble\ble_services\ble_dfu) :             mp_dfu->evt_handler(BLE_DFU_EVT_RESPONSE_SEND_ERROR);
+ble_dfu_buttonless_on_sys_evt in ble_dfu_unbonded.c (components\ble\ble_services\ble_dfu) :             mp_dfu->evt_handler(BLE_DFU_EVT_RESPONSE_SEND_ERROR);
+ble_dfu_buttonless_on_sys_evt in ble_dfu_unbonded.c (components\ble\ble_services\ble_dfu) :         mp_dfu->evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED);
+ble_dfu_buttonless_on_ctrl_pt_write in ble_dfu_unbonded.c (components\ble\ble_services\ble_dfu) :             mp_dfu->evt_handler(BLE_DFU_EVT_RESPONSE_SEND_ERROR);
+ble_dfu_buttonless_on_ctrl_pt_write in ble_dfu_unbonded.c (components\ble\ble_services\ble_dfu) :         mp_dfu->evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED);
+ble_dfu_buttonless_bootloader_start_prepare in ble_dfu_unbonded.c (components\ble\ble_services\ble_dfu) :     mp_dfu->evt_handler(BLE_DFU_EVT_BOOTLOADER_ENTER_PREPARE);
+on_read_rsp in ble_dis_c.c (components\ble\ble_services\ble_dis_c) :     if ((p_ble_dis_c->evt_handler == NULL) ||
+on_read_rsp in ble_dis_c.c (components\ble\ble_services\ble_dis_c) :             p_ble_dis_c->evt_handler(p_ble_dis_c, &ble_dis_c_evt);
+on_read_rsp in ble_dis_c.c (components\ble\ble_services\ble_dis_c) :             p_ble_dis_c->evt_handler(p_ble_dis_c, &ble_dis_c_evt);
+on_disconnected in ble_dis_c.c (components\ble\ble_services\ble_dis_c) :         if (p_ble_dis_c->evt_handler != NULL)
+on_disconnected in ble_dis_c.c (components\ble\ble_services\ble_dis_c) :             p_ble_dis_c->evt_handler(p_ble_dis_c, &dis_c_evt);
+ble_dis_c_init in ble_dis_c.c (components\ble\ble_services\ble_dis_c) :     p_ble_dis_c->evt_handler   = p_ble_dis_c_init->evt_handler;
+ble_dis_c_on_db_disc_evt in ble_dis_c.c (components\ble\ble_services\ble_dis_c) :     if ((p_ble_dis_c->evt_handler == NULL) ||
+ble_dis_c_on_db_disc_evt in ble_dis_c.c (components\ble\ble_services\ble_dis_c) :         p_ble_dis_c->evt_handler(p_ble_dis_c, &ble_dis_c_evt);
+ble_dis_c_s in ble_dis_c.h (components\ble\ble_services\ble_dis_c) :     ble_dis_c_evt_handler_t evt_handler;                       /**< Application event handler to be called when there is an event related to the DIS. */
+{anonble_dis_c_init_t} in ble_dis_c.h (components\ble\ble_services\ble_dis_c) :     ble_dis_c_evt_handler_t evt_handler;   /**< Application event handler to be called when there is an event related to the Device Information service. */
+ble_gls_init in ble_gls.c (components\ble\ble_services\ble_gls) :     p_gls->evt_handler          = p_gls_init->evt_handler;
+on_glm_cccd_write in ble_gls.c (components\ble\ble_services\ble_gls) :         if (p_gls->evt_handler != NULL)
+on_glm_cccd_write in ble_gls.c (components\ble\ble_services\ble_gls) :             p_gls->evt_handler(p_gls, &evt);
+{anonble_gls_init_t} in ble_gls.h (components\ble\ble_services\ble_gls) :     ble_gls_evt_handler_t   evt_handler;          /**< Event handler to be called for handling events in the Glucose Service. */
+ble_gls_s in ble_gls.h (components\ble\ble_services\ble_gls) :     ble_gls_evt_handler_t    evt_handler;         /**< Event handler to be called for handling events in the Glucose Service. */
+on_control_point_write in ble_hids.c (components\ble\ble_services\ble_hids) :         if (p_hids->evt_handler != NULL)
+on_control_point_write in ble_hids.c (components\ble\ble_services\ble_hids) :             p_hids->evt_handler(p_hids, &evt);
+on_protocol_mode_write in ble_hids.c (components\ble\ble_services\ble_hids) :         if (p_hids->evt_handler != NULL)
+on_protocol_mode_write in ble_hids.c (components\ble\ble_services\ble_hids) :             p_hids->evt_handler(p_hids, &evt);
+on_report_cccd_write in ble_hids.c (components\ble\ble_services\ble_hids) :         if (p_hids->evt_handler != NULL)
+on_report_cccd_write in ble_hids.c (components\ble\ble_services\ble_hids) :             p_hids->evt_handler(p_hids, &evt);
+on_report_value_write in ble_hids.c (components\ble\ble_services\ble_hids) :     if (p_hids->evt_handler != NULL)
+on_report_value_write in ble_hids.c (components\ble\ble_services\ble_hids) :         p_hids->evt_handler(p_hids, &evt);
+on_report_value_read_auth in ble_hids.c (components\ble\ble_services\ble_hids) :     if (p_hids->evt_handler != NULL)
+on_report_value_read_auth in ble_hids.c (components\ble\ble_services\ble_hids) :         p_hids->evt_handler(p_hids, &evt);
+ble_hids_init in ble_hids.c (components\ble\ble_services\ble_hids) :     p_hids->evt_handler       = p_hids_init->evt_handler;
+{anonble_hids_init_t} in ble_hids.h (components\ble\ble_services\ble_hids) :     ble_hids_evt_handler_t              evt_handler;                                  /**< Event handler to be called for handling events in the HID Service. */
+ble_hids_s in ble_hids.h (components\ble\ble_services\ble_hids) :     ble_hids_evt_handler_t              evt_handler;                                  /**< Event handler to be called for handling events in the HID Service. */
+on_hrm_cccd_write in ble_hrs.c (components\ble\ble_services\ble_hrs) :         if (p_hrs->evt_handler != NULL)
+on_hrm_cccd_write in ble_hrs.c (components\ble\ble_services\ble_hrs) :             p_hrs->evt_handler(p_hrs, &evt);
+ble_hrs_init in ble_hrs.c (components\ble\ble_services\ble_hrs) :     p_hrs->evt_handler                 = p_hrs_init->evt_handler;
+{anonble_hrs_init_t} in ble_hrs.h (components\ble\ble_services\ble_hrs) :     ble_hrs_evt_handler_t        evt_handler;                                          /**< Event handler to be called for handling events in the Heart Rate Service. */
+ble_hrs_s in ble_hrs.h (components\ble\ble_services\ble_hrs) :     ble_hrs_evt_handler_t        evt_handler;                                          /**< Event handler to be called for handling events in the Heart Rate Service. */
+on_hvx in ble_hrs_c.c (components\ble\ble_services\ble_hrs_c) :         p_ble_hrs_c->evt_handler(p_ble_hrs_c, &ble_hrs_c_evt);
+ble_hrs_on_db_disc_evt in ble_hrs_c.c (components\ble\ble_services\ble_hrs_c) :         p_ble_hrs_c->evt_handler(p_ble_hrs_c, &evt);
+ble_hrs_c_init in ble_hrs_c.c (components\ble\ble_services\ble_hrs_c) :     p_ble_hrs_c->evt_handler                 = p_ble_hrs_c_init->evt_handler;
+ble_hrs_c_s in ble_hrs_c.h (components\ble\ble_services\ble_hrs_c) :     ble_hrs_c_evt_handler_t evt_handler;   /**< Application event handler to be called when there is an event related to the Heart Rate Service. */
+{anonble_hrs_c_init_t} in ble_hrs_c.h (components\ble\ble_services\ble_hrs_c) :     ble_hrs_c_evt_handler_t   evt_handler;   /**< Event handler to be called by the Heart Rate Client module when there is an event related to the Heart Rate Service. */
+on_cccd_write in ble_hts.c (components\ble\ble_services\ble_hts) :         if (p_hts->evt_handler != NULL)
+on_cccd_write in ble_hts.c (components\ble\ble_services\ble_hts) :             p_hts->evt_handler(p_hts, &evt);
+on_hvc in ble_hts.c (components\ble\ble_services\ble_hts) :         p_hts->evt_handler(p_hts, &evt);
+ble_hts_init in ble_hts.c (components\ble\ble_services\ble_hts) :     p_hts->evt_handler   = p_hts_init->evt_handler;
+{anonble_hts_init_t} in ble_hts.h (components\ble\ble_services\ble_hts) :     ble_hts_evt_handler_t        evt_handler;                               /**< Event handler to be called for handling events in the Health Thermometer Service. */
+ble_hts_s in ble_hts.h (components\ble\ble_services\ble_hts) :     ble_hts_evt_handler_t        evt_handler;                               /**< Event handler to be called for handling events in the Health Thermometer Service. */
+on_write in ble_ias.c (components\ble\ble_services\ble_ias) :         p_ias->evt_handler(p_ias, &evt);
+ble_ias_init in ble_ias.c (components\ble\ble_services\ble_ias) :     if (p_ias_init->evt_handler == NULL)
+ble_ias_init in ble_ias.c (components\ble\ble_services\ble_ias) :     p_ias->evt_handler = p_ias_init->evt_handler;
+{anonble_ias_init_t} in ble_ias.h (components\ble\ble_services\ble_ias) :     ble_ias_evt_handler_t evt_handler;                  /**< Event handler to be called for handling events in the Immediate Alert Service. */
+ble_ias_s in ble_ias.h (components\ble\ble_services\ble_ias) :     ble_ias_evt_handler_t           evt_handler;         /**< Event handler to be called for handling events in the Immediate Alert Service. */
+ble_ias_c_on_db_disc_evt in ble_ias_c.c (components\ble\ble_services\ble_ias_c) :     p_ias_c->evt_handler(p_ias_c, &evt);
+ble_ias_c_init in ble_ias_c.c (components\ble\ble_services\ble_ias_c) :     VERIFY_PARAM_NOT_NULL(p_ias_c_init->evt_handler);
+ble_ias_c_init in ble_ias_c.c (components\ble\ble_services\ble_ias_c) :     p_ias_c->evt_handler                   = p_ias_c_init->evt_handler;
+on_disconnect in ble_ias_c.c (components\ble\ble_services\ble_ias_c) :         p_ias_c->evt_handler(p_ias_c, &evt);
+ble_ias_c_s in ble_ias_c.h (components\ble\ble_services\ble_ias_c) :     ble_ias_c_evt_handler_t   evt_handler;        /**< Event handler to be called for handling events in the Immediate Alert Service client. */
+{anonble_ias_c_init_t} in ble_ias_c.h (components\ble\ble_services\ble_ias_c) :     ble_ias_c_evt_handler_t   evt_handler;        /**< Event handler to be called for handling events from the Immediate Alert Service client. */
+ble_ipsp_init in ble_ipsp.c (components\ble\ble_services\ble_ipsp) :     NULL_PARAM_CHECK(p_init->evt_handler);
+ble_ipsp_init in ble_ipsp.c (components\ble\ble_services\ble_ipsp) :     m_evt_handler = p_init->evt_handler;
+{anonble_ipsp_init_t} in ble_ipsp.h (components\ble\ble_services\ble_ipsp) :     ble_ipsp_evt_handler_t    evt_handler;                                                          /**< Event notification callback registered with the module to receive asynchronous events. */
+on_hvx in ble_lbs_c.c (components\ble\ble_services\ble_lbs_c) :             p_ble_lbs_c->evt_handler(p_ble_lbs_c, &ble_lbs_c_evt);
+ble_lbs_on_db_disc_evt in ble_lbs_c.c (components\ble\ble_services\ble_lbs_c) :         p_ble_lbs_c->evt_handler(p_ble_lbs_c, &evt);
+ble_lbs_c_init in ble_lbs_c.c (components\ble\ble_services\ble_lbs_c) :     VERIFY_PARAM_NOT_NULL(p_ble_lbs_c_init->evt_handler);
+ble_lbs_c_init in ble_lbs_c.c (components\ble\ble_services\ble_lbs_c) :     p_ble_lbs_c->evt_handler                    = p_ble_lbs_c_init->evt_handler;
+ble_lbs_c_s in ble_lbs_c.h (components\ble\ble_services\ble_lbs_c) :     ble_lbs_c_evt_handler_t   evt_handler;   /**< Application event handler to be called when there is an event related to the LED Button service. */
+{anonble_lbs_c_init_t} in ble_lbs_c.h (components\ble\ble_services\ble_lbs_c) :     ble_lbs_c_evt_handler_t   evt_handler;   /**< Event handler to be called by the LED Button Client module when there is an event related to the LED Button Service. */
+on_connect in ble_lls.c (components\ble\ble_services\ble_lls) :     p_lls->evt_handler(p_lls, &evt);
+on_disconnect in ble_lls.c (components\ble\ble_services\ble_lls) :             p_lls->evt_handler(p_lls, &evt);
+on_auth_status in ble_lls.c (components\ble\ble_services\ble_lls) :         p_lls->evt_handler(p_lls, &evt);
+ble_lls_init in ble_lls.c (components\ble\ble_services\ble_lls) :     if (p_lls_init->evt_handler == NULL)
+ble_lls_init in ble_lls.c (components\ble\ble_services\ble_lls) :     p_lls->evt_handler   = p_lls_init->evt_handler;
+{anonble_lls_init_t} in ble_lls.h (components\ble\ble_services\ble_lls) :     ble_lls_evt_handler_t     evt_handler;              /**< Event handler to be called for handling events in the Link Loss Service. */
+ble_lls_s in ble_lls.h (components\ble\ble_services\ble_lls) :     ble_lls_evt_handler_t     evt_handler;              /**< Event handler to be called for handling events in the Link Loss Service. */
+on_ctrl_pt_cccd_write in ble_lns.c (components\ble\ble_services\experimental_ble_lns) :         if (p_lns->evt_handler != NULL)
+on_ctrl_pt_cccd_write in ble_lns.c (components\ble\ble_services\experimental_ble_lns) :             p_lns->evt_handler(p_lns, &evt);
+on_loc_speed_cccd_write in ble_lns.c (components\ble\ble_services\experimental_ble_lns) :         if (p_lns->evt_handler != NULL)
+on_loc_speed_cccd_write in ble_lns.c (components\ble\ble_services\experimental_ble_lns) :             p_lns->evt_handler(p_lns, &evt);
+on_nav_cccd_write in ble_lns.c (components\ble\ble_services\experimental_ble_lns) :         if (p_lns->evt_handler != NULL)
+on_nav_cccd_write in ble_lns.c (components\ble\ble_services\experimental_ble_lns) :             p_lns->evt_handler(p_lns, &evt);
+ble_lns_init in ble_lns.c (components\ble\ble_services\experimental_ble_lns) :     p_lns->evt_handler           = p_lns_init->evt_handler;
+ble_lns_init in ble_lns.c (components\ble\ble_services\experimental_ble_lns) :         lncp_init.evt_handler                   = p_lns_init->lncp_evt_handler;
+ble_lns_init_s in ble_lns.h (components\ble\ble_services\experimental_ble_lns) :     ble_lns_evt_handler_t   evt_handler;                                /**< Event handler to be called for handling events in the Location and Navigation Service. */
+ble_lns_s in ble_lns.h (components\ble\ble_services\experimental_ble_lns) :     ble_lns_evt_handler_t         evt_handler;                          /**< Event handler to be called for handling events in the Location and Navigation Service. */
+notify_app in ble_ln_cp.c (components\ble\ble_services\experimental_ble_lns) :     if (p_lncp->evt_handler != NULL)
+notify_app in ble_ln_cp.c (components\ble\ble_services\experimental_ble_lns) :         rsp = p_lncp->evt_handler(p_lncp, p_evt);
+ble_lncp_init in ble_ln_cp.c (components\ble\ble_services\experimental_ble_lns) :     p_lncp->evt_handler                  = p_lncp_init->evt_handler;
+{anonble_lncp_init_t} in ble_ln_cp.h (components\ble\ble_services\experimental_ble_lns) :     ble_lncp_evt_handler_t      evt_handler;
+ble_lncp_s in ble_ln_cp.h (components\ble\ble_services\experimental_ble_lns) :     ble_lncp_evt_handler_t      evt_handler;
+ble_nus_c_on_db_disc_evt in ble_nus_c.c (components\ble\ble_services\ble_nus_c) :         if (p_ble_nus_c->evt_handler != NULL)
+ble_nus_c_on_db_disc_evt in ble_nus_c.c (components\ble\ble_services\ble_nus_c) :             p_ble_nus_c->evt_handler(p_ble_nus_c, &nus_c_evt);
+on_hvx in ble_nus_c.c (components\ble\ble_services\ble_nus_c) :         && (p_ble_nus_c->evt_handler != NULL))
+on_hvx in ble_nus_c.c (components\ble\ble_services\ble_nus_c) :         p_ble_nus_c->evt_handler(p_ble_nus_c, &ble_nus_c_evt);
+ble_nus_c_init in ble_nus_c.c (components\ble\ble_services\ble_nus_c) :     p_ble_nus_c->evt_handler           = p_ble_nus_c_init->evt_handler;
+ble_nus_c_on_ble_evt in ble_nus_c.c (components\ble\ble_services\ble_nus_c) :                     && p_ble_nus_c->evt_handler != NULL)
+ble_nus_c_on_ble_evt in ble_nus_c.c (components\ble\ble_services\ble_nus_c) :                 p_ble_nus_c->evt_handler(p_ble_nus_c, &nus_c_evt);
+ble_nus_c_s in ble_nus_c.h (components\ble\ble_services\ble_nus_c) :     ble_nus_c_evt_handler_t   evt_handler;    /**< Application event handler to be called when there is an event related to the NUS. */
+{anonble_nus_c_init_t} in ble_nus_c.h (components\ble\ble_services\ble_nus_c) :     ble_nus_c_evt_handler_t   evt_handler;    /**< Application event handler to be called when there is an event related to the NUS. */
+ble_ots_init in ble_ots.c (components\ble\ble_services\experimental_ble_ots) :     p_ots->evt_handler              = p_ots_init->evt_handler;
+ble_ots_init in ble_ots.c (components\ble\ble_services\experimental_ble_ots) :     p_ots->evt_handler              = p_ots_init->evt_handler;
+ble_ots_l2cap_s in ble_ots.h (components\ble\ble_services\experimental_ble_ots) :     ble_ots_l2cap_evt_handler_t   evt_handler;
+{anonble_ots_l2cap_init_t} in ble_ots.h (components\ble\ble_services\experimental_ble_ots) :     ble_ots_l2cap_evt_handler_t   evt_handler;
+{anonble_ots_init_t} in ble_ots.h (components\ble\ble_services\experimental_ble_ots) :     ble_ots_evt_handler_t         evt_handler;
+ble_ots_s in ble_ots.h (components\ble\ble_services\experimental_ble_ots) :     ble_ots_evt_handler_t        evt_handler;
+ble_ots_l2cap_init in ble_ots_l2cap.c (components\ble\ble_services\experimental_ble_ots) :     if (p_ots_l2cap_init->evt_handler == NULL)
+ble_ots_l2cap_init in ble_ots_l2cap.c (components\ble\ble_services\experimental_ble_ots) :     p_ots_l2cap->evt_handler              = p_ots_l2cap_init->evt_handler;
+on_l2cap_ch_setup in ble_ots_l2cap.c (components\ble\ble_services\experimental_ble_ots) :     p_ots_l2cap->evt_handler(p_ots_l2cap, &evt);
+on_l2cap_ch_released in ble_ots_l2cap.c (components\ble\ble_services\experimental_ble_ots) :     p_ots_l2cap->evt_handler(p_ots_l2cap, &evt);
+on_l2cap_ch_tx in ble_ots_l2cap.c (components\ble\ble_services\experimental_ble_ots) :         p_ots_l2cap->evt_handler(p_ots_l2cap, &evt);
+on_l2cap_ch_rx in ble_ots_l2cap.c (components\ble\ble_services\experimental_ble_ots) :         p_ots_l2cap->evt_handler(p_ots_l2cap, &evt);
+ots_l2cap_evt_handler in ble_ots_oacp.c (components\ble\ble_services\experimental_ble_ots) :             p_ots_l2cap->p_ots_oacp->p_ots->evt_handler(p_ots_l2cap->p_ots_oacp->p_ots, &evt);
+oacp_write_proc in ble_ots_oacp.c (components\ble\ble_services\experimental_ble_ots) :     p_ots_oacp->p_ots->evt_handler(p_ots_oacp->p_ots, &ble_ots_evt);
+oacp_read_proc in ble_ots_oacp.c (components\ble\ble_services\experimental_ble_ots) :     p_ots_oacp->p_ots->evt_handler(p_ots_oacp->p_ots, &ble_ots_evt);
+oacp_abort_proc in ble_ots_oacp.c (components\ble\ble_services\experimental_ble_ots) :     p_ots_oacp->p_ots->evt_handler(p_ots_oacp->p_ots, &ble_ots_evt);
+on_cccd_write in ble_ots_oacp.c (components\ble\ble_services\experimental_ble_ots) :         if (p_ots_oacp->p_ots->evt_handler != NULL)
+on_cccd_write in ble_ots_oacp.c (components\ble\ble_services\experimental_ble_ots) :             p_ots_oacp->p_ots->evt_handler(p_ots_oacp->p_ots, &evt);
+ble_ots_oacp_init in ble_ots_oacp.c (components\ble\ble_services\experimental_ble_ots) :     l2cap_init.evt_handler       = ots_l2cap_evt_handler;
+on_obj_properties_write in ble_ots_object.c (components\ble\ble_services\experimental_ble_ots) :         p_ots_object_chars->p_ots->evt_handler(p_ots_object_chars->p_ots, &ble_ots_evt);
+ble_radio_notification_init in ble_radio_notification.c (components\ble\ble_radio_notification) :                                      ble_radio_notification_evt_handler_t evt_handler)
+ble_radio_notification_init in ble_radio_notification.c (components\ble\ble_radio_notification) :     m_evt_handler = evt_handler;
+ble_radio_notification.h (components\ble\ble_radio_notification) line 66 :  * @param[in]  evt_handler    Handler to be executed when a radio notification event has been
+ble_radio_notification_init in ble_radio_notification.h (components\ble\ble_radio_notification) :                                      ble_radio_notification_evt_handler_t evt_handler);
+on_meas_cccd_write in ble_rscs.c (components\ble\ble_services\ble_rscs) :         if (p_rscs->evt_handler != NULL)
+on_meas_cccd_write in ble_rscs.c (components\ble\ble_services\ble_rscs) :             p_rscs->evt_handler(p_rscs, &evt);
+ble_rscs_init in ble_rscs.c (components\ble\ble_services\ble_rscs) :     p_rscs->evt_handler = p_rscs_init->evt_handler;
+{anonble_rscs_init_t} in ble_rscs.h (components\ble\ble_services\ble_rscs) :     ble_rscs_evt_handler_t evt_handler;                                     /**< Event handler to be called for handling events in the Running Speed and Cadence Service. */
+ble_rscs_s in ble_rscs.h (components\ble\ble_services\ble_rscs) :     ble_rscs_evt_handler_t       evt_handler;                               /**< Event handler to be called for handling events in the Running Speed and Cadence Service. */
+on_hvx in ble_rscs_c.c (components\ble\ble_services\ble_rscs_c) :         p_ble_rscs_c->evt_handler(p_ble_rscs_c, &ble_rscs_c_evt);
+ble_rscs_on_db_disc_evt in ble_rscs_c.c (components\ble\ble_services\ble_rscs_c) :         p_ble_rscs_c->evt_handler(p_ble_rscs_c, &evt);
+ble_rscs_c_init in ble_rscs_c.c (components\ble\ble_services\ble_rscs_c) :     p_ble_rscs_c->evt_handler             = p_ble_rscs_c_init->evt_handler;
+ble_rscs_c_s in ble_rscs_c.h (components\ble\ble_services\ble_rscs_c) :     ble_rscs_c_evt_handler_t evt_handler;   /**< Application event handler to be called when there is an event related to the Running Speed and Cadence service. */
+{anonble_rscs_c_init_t} in ble_rscs_c.h (components\ble\ble_services\ble_rscs_c) :     ble_rscs_c_evt_handler_t evt_handler;   /**< Event handler to be called by the Running Speed and Cadence Client module whenever there is an event related to the Running Speed and Cadence Service. */
+ble_sc_ctrlpt_init in ble_sc_ctrlpt.c (components\ble\ble_services\ble_cscs) :     p_sc_ctrlpt->evt_handler            = p_sc_ctrlpt_init->evt_handler;
+on_ctrlpt_write in ble_sc_ctrlpt.c (components\ble\ble_services\ble_cscs) :                         if (p_sc_ctrlpt->evt_handler != NULL)
+on_ctrlpt_write in ble_sc_ctrlpt.c (components\ble\ble_services\ble_cscs) :                             rsp.status = p_sc_ctrlpt->evt_handler(p_sc_ctrlpt, &evt);
+on_ctrlpt_write in ble_sc_ctrlpt.c (components\ble\ble_services\ble_cscs) :                     if (p_sc_ctrlpt->evt_handler != NULL)
+on_ctrlpt_write in ble_sc_ctrlpt.c (components\ble\ble_services\ble_cscs) :                         rsp.status = p_sc_ctrlpt->evt_handler(p_sc_ctrlpt, &evt);
+on_ctrlpt_write in ble_sc_ctrlpt.c (components\ble\ble_services\ble_cscs) :                     if (p_sc_ctrlpt->evt_handler != NULL)
+on_ctrlpt_write in ble_sc_ctrlpt.c (components\ble\ble_services\ble_cscs) :                         rsp.status = p_sc_ctrlpt->evt_handler(p_sc_ctrlpt, &evt);
+{anonble_cs_ctrlpt_init_t} in ble_sc_ctrlpt.h (components\ble\ble_services\ble_cscs) :     ble_sc_ctrlpt_evt_handler_t  evt_handler;                                             /**< event handler */
+ble_sc_ctrlpt_s in ble_sc_ctrlpt.h (components\ble\ble_services\ble_cscs) :     ble_sc_ctrlpt_evt_handler_t  evt_handler;                                             /**< Handle of the parent service (as provided by the BLE stack). */
+on_meas_cccd_write in cgms_meas.c (components\ble\ble_services\experimental_nrf_ble_cgms) :         if (p_cgms->evt_handler != NULL)
+on_meas_cccd_write in cgms_meas.c (components\ble\ble_services\experimental_nrf_ble_cgms) :             p_cgms->evt_handler(p_cgms, &evt);
+on_socp_value_write in cgms_socp.c (components\ble\ble_services\experimental_nrf_ble_cgms) :             p_cgms->evt_handler(p_cgms, &evt);
+on_socp_value_write in cgms_socp.c (components\ble\ble_services\experimental_nrf_ble_cgms) :                 if (p_cgms->evt_handler != NULL)
+on_socp_value_write in cgms_socp.c (components\ble\ble_services\experimental_nrf_ble_cgms) :                     p_cgms->evt_handler(p_cgms, &evt);
+on_socp_value_write in cgms_socp.c (components\ble\ble_services\experimental_nrf_ble_cgms) :             p_cgms->evt_handler(p_cgms, &evt);
+on_socp_value_write in cgms_socp.c (components\ble\ble_services\experimental_nrf_ble_cgms) :             if (p_cgms->evt_handler != NULL)
+on_socp_value_write in cgms_socp.c (components\ble\ble_services\experimental_nrf_ble_cgms) :                 p_cgms->evt_handler(p_cgms, &evt);
+fds.c (components\libraries\fds) line 71 :     .evt_handler = fs_event_handler,
+nus_c_init in main.c (examples\ble_central\ble_app_uart_c) :     init.evt_handler   = ble_nus_c_evt_handler;
+db_discovery_init in main.c (examples\ble_central\ble_app_uart_c) :     db_init.evt_handler  = db_disc_handler;
+nrfx_gpiote_in_init in nrfx_gpiote.c (modules\nrfx\drivers\src) :                                nrfx_gpiote_evt_handler_t       evt_handler)
+nrfx_gpiote_in_init in nrfx_gpiote.c (modules\nrfx\drivers\src) :         int8_t channel = channel_port_alloc(pin, evt_handler, p_config->hi_accuracy);
+nrfx_gpiote.h (modules\nrfx\drivers\include) line 380 :  * @param[in] evt_handler User function to be called when the configured transition occurs.
+nrfx_gpiote_in_init in nrfx_gpiote.h (modules\nrfx\drivers\include) :                                nrfx_gpiote_evt_handler_t       evt_handler);
+ble_ancs_c_on_db_disc_evt in nrf_ble_ancs_c.c (components\ble\ble_services\ble_ancs_c) :     p_ancs->evt_handler(&evt);
+parse_notif in nrf_ble_ancs_c.c (components\ble\ble_services\ble_ancs_c) :         p_ancs->evt_handler(&ancs_evt);
+parse_notif in nrf_ble_ancs_c.c (components\ble\ble_services\ble_ancs_c) :     p_ancs->evt_handler(&ancs_evt);
+on_ctrlpt_error_rsp in nrf_ble_ancs_c.c (components\ble\ble_services\ble_ancs_c) :     p_ancs->evt_handler(&ancs_evt);
+ble_ancs_c_init in nrf_ble_ancs_c.c (components\ble\ble_services\ble_ancs_c) :     VERIFY_PARAM_NOT_NULL(p_ancs_init->evt_handler);
+ble_ancs_c_init in nrf_ble_ancs_c.c (components\ble\ble_services\ble_ancs_c) :     p_ancs->evt_handler      = p_ancs_init->evt_handler;
+{anonble_ancs_c_t} in nrf_ble_ancs_c.h (components\ble\ble_services\ble_ancs_c) :     ble_ancs_c_evt_handler_t         evt_handler;                                     //!< Event handler to be called for handling events in the Apple Notification client application.
+{anonble_ancs_c_init_t} in nrf_ble_ancs_c.h (components\ble\ble_services\ble_ancs_c) :     ble_ancs_c_evt_handler_t   evt_handler;    //!< Event handler to be called for handling events in the Battery Service.
+ctrlpt_auth in nrf_ble_bms.c (components\ble\ble_services\nrf_ble_bms) :         if (p_bms->evt_handler != NULL)
+ctrlpt_auth in nrf_ble_bms.c (components\ble\ble_services\nrf_ble_bms) :             p_bms->evt_handler(p_bms, &bms_evt);
+feature_char_add in nrf_ble_bms.c (components\ble\ble_services\nrf_ble_bms) :         VERIFY_PARAM_NOT_NULL(p_bms_init->evt_handler);
+nrf_ble_bms_init in nrf_ble_bms.c (components\ble\ble_services\nrf_ble_bms) :     p_bms->evt_handler    = p_bms_init->evt_handler;
+{anonnrf_ble_bms_init_t} in nrf_ble_bms.h (components\ble\ble_services\nrf_ble_bms) :     ble_bms_evt_handler_t   evt_handler;         //!< Event handler to be called for handling events in the Bond Management Service.
+nrf_ble_bms_s in nrf_ble_bms.h (components\ble\ble_services\nrf_ble_bms) :     ble_bms_evt_handler_t     evt_handler;     //!< Event handler to be called for handling events in the Bond Management Service.
+nrf_ble_cgms_init in nrf_ble_cgms.c (components\ble\ble_services\experimental_nrf_ble_cgms) :     VERIFY_PARAM_NOT_NULL(p_cgms_init->evt_handler);
+nrf_ble_cgms_init in nrf_ble_cgms.c (components\ble\ble_services\experimental_nrf_ble_cgms) :     p_cgms->evt_handler        = p_cgms_init->evt_handler;
+{anonnrf_ble_cgms_init_t} in nrf_ble_cgms.h (components\ble\ble_services\experimental_nrf_ble_cgms) :     ble_cgms_evt_handler_t    evt_handler;           /**< Event handler to be called for handling events in the CGM Service. */
+ble_cgms_s in nrf_ble_cgms.h (components\ble\ble_services\experimental_nrf_ble_cgms) :     ble_cgms_evt_handler_t      evt_handler;                                 /**< Event handler to be called for handling events in the CGM Service. */
+nrf_ble_es.c (components\ble\ble_services\eddystone) line 409 : void nrf_ble_es_init(nrf_ble_es_evt_handler_t evt_handler)
+nrf_ble_es_init in nrf_ble_es.c (components\ble\ble_services\eddystone) :     m_evt_handler = evt_handler;
+nrf_ble_es.h (components\ble\ble_services\eddystone) line 91 :  * @param[in]   evt_handler Event handler to be called for handling BLE events.
+nrf_ble_es.h (components\ble\ble_services\eddystone) line 93 : void nrf_ble_es_init(nrf_ble_es_evt_handler_t evt_handler);
+on_exchange_mtu_rsp_evt in nrf_ble_gatt.c (components\ble\nrf_ble_gatt) :     if ((p_gatt->evt_handler != NULL) && (p_link->att_mtu_exchange_requested))
+on_exchange_mtu_rsp_evt in nrf_ble_gatt.c (components\ble\nrf_ble_gatt) :         p_gatt->evt_handler(p_gatt, &evt);
+on_exchange_mtu_request_evt in nrf_ble_gatt.c (components\ble\nrf_ble_gatt) :     if (p_gatt->evt_handler != NULL)
+on_exchange_mtu_request_evt in nrf_ble_gatt.c (components\ble\nrf_ble_gatt) :         p_gatt->evt_handler(p_gatt, &evt);
+on_data_length_update_evt in nrf_ble_gatt.c (components\ble\nrf_ble_gatt) :     if (p_gatt->evt_handler != NULL)
+on_data_length_update_evt in nrf_ble_gatt.c (components\ble\nrf_ble_gatt) :         p_gatt->evt_handler(p_gatt, &evt);
+nrf_ble_gatt.c (components\ble\nrf_ble_gatt) line 369 : ret_code_t nrf_ble_gatt_init(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_handler_t evt_handler)
+nrf_ble_gatt_init in nrf_ble_gatt.c (components\ble\nrf_ble_gatt) :     p_gatt->evt_handler             = evt_handler;
+---- Wes_Encryp_Ecb Matches (4 in 3 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 					Wes_Encryp_Ecb();
+sysmgr.c (examples\ble_central\ble_app_uart_c) line 853 : void Wes_Encryp_Ecb()
+Wes_Encryp_Ecb in sysmgr.c (examples\ble_central\ble_app_uart_c) : 	NRF_LOG_INFO("==> Wes_Encryp_Ecb : 0x%04x\n", tempVal);
+sysmgr.h (examples\ble_central\ble_app_uart_c) line 163 : void Wes_Encryp_Ecb();
+---- my_addr Matches (2 in 1 files) ----
+main.c (examples\ble_central\ble_app_uart_c) line 153 : static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+scan_init in main.c (examples\ble_central\ble_app_uart_c) :         err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+---- shutdown_handler Matches (2 in 1 files) ----
+main.c (examples\ble_central\ble_app_uart_c) line 1112 : static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+main.c (examples\ble_central\ble_app_uart_c) line 1134 : NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+---- _1000ms_timer_handle Matches (7 in 1 files) ----
+main.c (examples\ble_central\ble_app_uart_c) line 1537 : void _1000ms_timer_handle()
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : //	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : 			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : 			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : 			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : 			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+main in main.c (examples\ble_central\ble_app_uart_c) : 			_1000ms_timer_handle();
+---- AppParkingCheck_Android Matches (2 in 2 files) ----
+nrf_ble_scan_on_adv_report in nrf_ble_scan.c (components\ble\nrf_ble_scan) : 		AppParkingCheck_Android(p_adv_report->data.p_data);
+sysmgr.c (examples\ble_central\ble_app_uart_c) line 1208 : int AppParkingCheck_Android(char *data)
+---- SendParkingApp Matches (6 in 4 files) ----
+ble_nus_c_evt_handler in main.c (examples\ble_central\ble_app_uart_c) : 							SendParkingApp();
+our_service.c (examples\ble_central\ble_app_uart_c) line 367 : void SendParkingApp()
+SendParkingApp in our_service.c (examples\ble_central\ble_app_uart_c) : 	NRF_LOG_RAW_INFO("===> SendParkingApp()\n");
+our_service.h (examples\ble_central\ble_app_uart_c) line 323 : void SendParkingApp();
+AppParkingCheck_Android in sysmgr.c (examples\ble_central\ble_app_uart_c) : 		SendParkingApp();
+AppParkingCheck_IOS in sysmgr.c (examples\ble_central\ble_app_uart_c) : 		SendParkingApp();
+---- _1000ms_timer_handle Matches (7 in 1 files) ----
+main.c (examples\ble_central\ble_app_uart_c) line 1537 : void _1000ms_timer_handle()
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : //	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : 			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : 			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : 			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+_1000ms_timer_handle in main.c (examples\ble_central\ble_app_uart_c) : 			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+main in main.c (examples\ble_central\ble_app_uart_c) : 			_1000ms_timer_handle();
+---- nrf_ble_scan_on_ble_evt Matches (3 in 2 files) ----
+nrf_ble_scan.c (components\ble\nrf_ble_scan) line 1711 : void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+NRF_BLE_SCAN_DEF in nrf_ble_scan.h (components\ble\nrf_ble_scan) :                          nrf_ble_scan_on_ble_evt, &_name); \
+nrf_ble_scan.h (components\ble\nrf_ble_scan) line 474 : void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_scan);
+---- ble_nus_c_evt_handler Matches (3 in 1 files) ----
+main.c (examples\ble_central\ble_app_uart_c) line 582 : static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+main.c (examples\ble_central\ble_app_uart_c) line 596 :             NRF_LOG_INFO("======================ble_nus_c_evt_handler -- BLE_NUS_C_EVT_DISCOVERY_COMPLETE");
+main.c (examples\ble_central\ble_app_uart_c) line 1361 :     init.evt_handler   = ble_nus_c_evt_handler;
+---- nrf_ble_scan_start Matches (4 in 3 files) ----
+scan_start in main.c (examples\ble_central\ble_app_uart_c) :     ret = nrf_ble_scan_start(&m_scan);
+nrf_ble_scan.c (components\ble\nrf_ble_scan) line 1605 : ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+nrf_ble_scan.h (components\ble\nrf_ble_scan) line 351 : ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx);
+nrf_ble_scan.h (components\ble\nrf_ble_scan) line 452 :  *         the scan is stopped. To resume scanning, use @ref nrf_ble_scan_start.
+---- ParseEventServer Matches (3 in 3 files) ----
+main in main.c (examples\ble_central\ble_app_uart_c) :         ParseEventServer();   
+our_service.c (examples\ble_central\ble_app_uart_c) line 123 : void ParseEventServer()
+our_service.h (examples\ble_central\ble_app_uart_c) line 310 : void ParseEventServer();

+ 49 - 0
BLE_Central.si4project/BLE_Central.bookmarks.xml

@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="utf-8"?>
+<SourceInsightBookmarks
+	AppVer="4.00.0106"
+	AppVerMinReader="4.00.0009"
+	>
+	<Bookmarks>
+		<Mark
+			Name="5974740384517101302202"
+			Comment="ble nus c evt handler"
+			File="examples\ble_central\ble_app_uart_c\main.c"
+			Line="1240"
+			Column="10"
+			Symbol="ble_evt_handler"
+			SymbolInstance="0"
+			SymbolType="Function"
+			LineOffset="100"
+			/>
+		<Mark
+			Name="3239980693602122302202"
+			Comment="ble_gap_adv_data_t"
+			File="components\softdevice\s132\headers\ble_gap.h"
+			Line="874"
+			Column="2"
+			LineOffset="0"
+			/>
+		<Mark
+			Name="7750800071830032302202"
+			Comment="SystemManager.DevType == DEV_BAND_PARK"
+			File="components\ble\nrf_ble_scan\nrf_ble_scan.c"
+			Line="1126"
+			Column="5"
+			Symbol="nrf_ble_scan_on_adv_report"
+			SymbolInstance="0"
+			SymbolType="Function"
+			LineOffset="82"
+			/>
+		<Mark
+			Name="2256229923937160402202"
+			Comment="aaa"
+			File="examples\ble_central\ble_app_uart_c\main.c"
+			Line="730"
+			Column="0"
+			Symbol="ble_nus_c_evt_handler"
+			SymbolInstance="0"
+			SymbolType="Function"
+			LineOffset="149"
+			/>
+	</Bookmarks>
+</SourceInsightBookmarks>

BIN
BLE_Central.si4project/BLE_Central.sip_sym


BIN
BLE_Central.si4project/BLE_Central.sip_xab


BIN
BLE_Central.si4project/BLE_Central.sip_xad


BIN
BLE_Central.si4project/BLE_Central.sip_xc


BIN
BLE_Central.si4project/BLE_Central.sip_xf


BIN
BLE_Central.si4project/BLE_Central.sip_xm


BIN
BLE_Central.si4project/BLE_Central.sip_xr


BIN
BLE_Central.si4project/BLE_Central.sip_xsb


BIN
BLE_Central.si4project/BLE_Central.sip_xsd


BIN
BLE_Central.si4project/BLE_Central.siproj


+ 22 - 0
BLE_Central.si4project/BLE_Central.siproj_settings.xml

@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<ProjectSettings
+	AppVer="4.00.0106"
+	AppVerMinReader="4.00.0034"
+	GlobalConfiguration="1"
+	GlobalWorkspace="0"
+	LocalsInDb="0"
+	IndexMembers="1"
+	IndexFragments="1"
+	UseMasterFileList="0"
+	SourceDir="..\"
+	BackupDir="%PROJECT_DATA_DIR%\Backup"
+	MasterFileList="%PROJECT_SOURCE_DIR%\%PROJECT_NAME%_filelist.txt"
+	IsImportProject="0"
+	>
+	<Imports>
+		<ImportedLibs/>
+	</Imports>
+	<ParseConditions>
+		<Defines/>
+	</ParseConditions>
+</ProjectSettings>

BIN
BLE_Central.si4project/BLE_Central.siwork


+ 7 - 0
BLE_Central.si4project/BLE_Central.snippets.xml

@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<SourceInsightCodeSnippets
+	AppVer="4.00.0106"
+	AppVerMinReader="4.00.0019"
+	>
+	<SnippetList/>
+</SourceInsightCodeSnippets>

+ 581 - 0
BLE_Central.si4project/Backup/aes(7926).c

@@ -0,0 +1,581 @@
+/*
+
+This is an implementation of the AES128 algorithm, specifically ECB and CBC mode.
+
+The implementation is verified against the test vectors in:
+  National Institute of Standards and Technology Special Publication 800-38A 2001 ED
+
+ECB-AES128
+----------
+
+  plain-text:
+    6bc1bee22e409f96e93d7e117393172a
+    ae2d8a571e03ac9c9eb76fac45af8e51
+    30c81c46a35ce411e5fbc1191a0a52ef
+    f69f2445df4f9b17ad2b417be66c3710
+
+  key:
+    2b7e151628aed2a6abf7158809cf4f3c
+
+  resulting cipher
+    3ad77bb40d7a3660a89ecaf32466ef97 
+    f5d3d58503b9699de785895a96fdbaaf 
+    43b1cd7f598ece23881b00e3ed030688 
+    7b0c785e27e8ad3f8223207104725dd4 
+
+
+NOTE:   String length must be evenly divisible by 16byte (str_len % 16 == 0)
+        You should pad the end of the string with zeros if this is not the case.
+
+*/
+
+
+/*****************************************************************************/
+/* Includes:                                                                 */
+/*****************************************************************************/
+#include <stdint.h>
+#include <string.h> // CBC mode, for memset
+#include "aes.h"
+
+
+/*****************************************************************************/
+/* Defines:                                                                  */
+/*****************************************************************************/
+// The number of columns comprising a state in AES. This is a constant in AES. Value=4
+#define Nb 4
+// The number of 32 bit words in a key.
+#define Nk 4
+// Key length in bytes [128 bit]
+#define KEYLEN 16
+// The number of rounds in AES Cipher.
+#define Nr 10
+
+// jcallan@github points out that declaring Multiply as a function 
+// reduces code size considerably with the Keil ARM compiler.
+// See this link for more information: https://github.com/kokke/tiny-AES128-C/pull/3
+#ifndef MULTIPLY_AS_A_FUNCTION
+  #define MULTIPLY_AS_A_FUNCTION 0
+#endif
+
+/*****************************************************************************/
+/* Private variables:                                                        */
+/*****************************************************************************/
+// state - array holding the intermediate results during decryption.
+typedef uint8_t state_t[4][4];
+static state_t* state;
+
+// The array that stores the round keys.
+static uint8_t RoundKey[176];
+
+// The Key input to the AES Program
+static const uint8_t* Key;
+
+#if defined(CBC) && CBC
+  // Initial Vector used only for CBC mode
+  static uint8_t* Iv;
+#endif
+
+// The lookup-tables are marked const so they can be placed in read-only storage instead of RAM
+// The numbers below can be computed dynamically trading ROM for RAM - 
+// This can be useful in (embedded) bootloader applications, where ROM is often limited.
+static const uint8_t sbox[256] =   {
+  //0     1    2      3     4    5     6     7      8    9     A      B    C     D     E     F
+  0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
+  0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
+  0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
+  0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
+  0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
+  0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
+  0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
+  0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
+  0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
+  0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
+  0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
+  0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
+  0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
+  0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
+  0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
+  0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };
+
+static const uint8_t rsbox[256] =
+{ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
+  0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
+  0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
+  0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
+  0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
+  0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
+  0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
+  0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
+  0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
+  0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
+  0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
+  0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
+  0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
+  0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
+  0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
+  0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };
+
+
+// The round constant word array, Rcon[i], contains the values given by 
+// x to th e power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)
+// Note that i starts at 1, not 0).
+static const uint8_t Rcon[255] = {
+  0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 
+  0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 
+  0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 
+  0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 
+  0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 
+  0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 
+  0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 
+  0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 
+  0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 
+  0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 
+  0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 
+  0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 
+  0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 
+  0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 
+  0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 
+  0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb  };
+
+
+/*****************************************************************************/
+/* Private functions:                                                        */
+/*****************************************************************************/
+static uint8_t getSBoxValue(uint8_t num)
+{
+  return sbox[num];
+}
+
+static uint8_t getSBoxInvert(uint8_t num)
+{
+  return rsbox[num];
+}
+
+// This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states. 
+static void KeyExpansion(void)
+{
+  uint32_t i, j, k;
+  uint8_t tempa[4]; // Used for the column/row operations
+  
+  // The first round key is the key itself.
+  for(i = 0; i < Nk; ++i)
+  {
+    RoundKey[(i * 4) + 0] = Key[(i * 4) + 0];
+    RoundKey[(i * 4) + 1] = Key[(i * 4) + 1];
+    RoundKey[(i * 4) + 2] = Key[(i * 4) + 2];
+    RoundKey[(i * 4) + 3] = Key[(i * 4) + 3];
+  }
+
+  // All other round keys are found from the previous round keys.
+  for(; (i < (Nb * (Nr + 1))); ++i)
+  {
+    for(j = 0; j < 4; ++j)
+    {
+      tempa[j]=RoundKey[(i-1) * 4 + j];
+    }
+    if (i % Nk == 0)
+    {
+      // This function rotates the 4 bytes in a word to the left once.
+      // [a0,a1,a2,a3] becomes [a1,a2,a3,a0]
+
+      // Function RotWord()
+      {
+        k = tempa[0];
+        tempa[0] = tempa[1];
+        tempa[1] = tempa[2];
+        tempa[2] = tempa[3];
+        tempa[3] = k;
+      }
+
+      // SubWord() is a function that takes a four-byte input word and 
+      // applies the S-box to each of the four bytes to produce an output word.
+
+      // Function Subword()
+      {
+        tempa[0] = getSBoxValue(tempa[0]);
+        tempa[1] = getSBoxValue(tempa[1]);
+        tempa[2] = getSBoxValue(tempa[2]);
+        tempa[3] = getSBoxValue(tempa[3]);
+      }
+
+      tempa[0] =  tempa[0] ^ Rcon[i/Nk];
+    }
+    else if (Nk > 6 && i % Nk == 4)
+    {
+      // Function Subword()
+      {
+        tempa[0] = getSBoxValue(tempa[0]);
+        tempa[1] = getSBoxValue(tempa[1]);
+        tempa[2] = getSBoxValue(tempa[2]);
+        tempa[3] = getSBoxValue(tempa[3]);
+      }
+    }
+    RoundKey[i * 4 + 0] = RoundKey[(i - Nk) * 4 + 0] ^ tempa[0];
+    RoundKey[i * 4 + 1] = RoundKey[(i - Nk) * 4 + 1] ^ tempa[1];
+    RoundKey[i * 4 + 2] = RoundKey[(i - Nk) * 4 + 2] ^ tempa[2];
+    RoundKey[i * 4 + 3] = RoundKey[(i - Nk) * 4 + 3] ^ tempa[3];
+  }
+}
+
+// This function adds the round key to state.
+// The round key is added to the state by an XOR function.
+static void AddRoundKey(uint8_t round)
+{
+  uint8_t i,j;
+  for(i=0;i<4;++i)
+  {
+    for(j = 0; j < 4; ++j)
+    {
+      (*state)[i][j] ^= RoundKey[round * Nb * 4 + i * Nb + j];
+    }
+  }
+}
+
+// The SubBytes Function Substitutes the values in the
+// state matrix with values in an S-box.
+static void SubBytes(void)
+{
+  uint8_t i, j;
+  for(i = 0; i < 4; ++i)
+  {
+    for(j = 0; j < 4; ++j)
+    {
+      (*state)[j][i] = getSBoxValue((*state)[j][i]);
+    }
+  }
+}
+
+// The ShiftRows() function shifts the rows in the state to the left.
+// Each row is shifted with different offset.
+// Offset = Row number. So the first row is not shifted.
+static void ShiftRows(void)
+{
+  uint8_t temp;
+
+  // Rotate first row 1 columns to left  
+  temp           = (*state)[0][1];
+  (*state)[0][1] = (*state)[1][1];
+  (*state)[1][1] = (*state)[2][1];
+  (*state)[2][1] = (*state)[3][1];
+  (*state)[3][1] = temp;
+
+  // Rotate second row 2 columns to left  
+  temp           = (*state)[0][2];
+  (*state)[0][2] = (*state)[2][2];
+  (*state)[2][2] = temp;
+
+  temp       = (*state)[1][2];
+  (*state)[1][2] = (*state)[3][2];
+  (*state)[3][2] = temp;
+
+  // Rotate third row 3 columns to left
+  temp       = (*state)[0][3];
+  (*state)[0][3] = (*state)[3][3];
+  (*state)[3][3] = (*state)[2][3];
+  (*state)[2][3] = (*state)[1][3];
+  (*state)[1][3] = temp;
+}
+
+static uint8_t xtime(uint8_t x)
+{
+  return ((x<<1) ^ (((x>>7) & 1) * 0x1b));
+}
+
+// MixColumns function mixes the columns of the state matrix
+static void MixColumns(void)
+{
+  uint8_t i;
+  uint8_t Tmp,Tm,t;
+  for(i = 0; i < 4; ++i)
+  {  
+    t   = (*state)[i][0];
+    Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ;
+    Tm  = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm);  (*state)[i][0] ^= Tm ^ Tmp ;
+    Tm  = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm);  (*state)[i][1] ^= Tm ^ Tmp ;
+    Tm  = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm);  (*state)[i][2] ^= Tm ^ Tmp ;
+    Tm  = (*state)[i][3] ^ t ;        Tm = xtime(Tm);  (*state)[i][3] ^= Tm ^ Tmp ;
+  }
+}
+
+// Multiply is used to multiply numbers in the field GF(2^8)
+#if MULTIPLY_AS_A_FUNCTION
+static uint8_t Multiply(uint8_t x, uint8_t y)
+{
+  return (((y & 1) * x) ^
+       ((y>>1 & 1) * xtime(x)) ^
+       ((y>>2 & 1) * xtime(xtime(x))) ^
+       ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^
+       ((y>>4 & 1) * xtime(xtime(xtime(xtime(x))))));
+  }
+#else
+#define Multiply(x, y)                                \
+      (  ((y & 1) * x) ^                              \
+      ((y>>1 & 1) * xtime(x)) ^                       \
+      ((y>>2 & 1) * xtime(xtime(x))) ^                \
+      ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^         \
+      ((y>>4 & 1) * xtime(xtime(xtime(xtime(x))))))   \
+
+#endif
+
+// MixColumns function mixes the columns of the state matrix.
+// The method used to multiply may be difficult to understand for the inexperienced.
+// Please use the references to gain more information.
+static void InvMixColumns(void)
+{
+  int i;
+  uint8_t a,b,c,d;
+  for(i=0;i<4;++i)
+  { 
+    a = (*state)[i][0];
+    b = (*state)[i][1];
+    c = (*state)[i][2];
+    d = (*state)[i][3];
+
+    (*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);
+    (*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);
+    (*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);
+    (*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);
+  }
+}
+
+
+// The SubBytes Function Substitutes the values in the
+// state matrix with values in an S-box.
+static void InvSubBytes(void)
+{
+  uint8_t i,j;
+  for(i=0;i<4;++i)
+  {
+    for(j=0;j<4;++j)
+    {
+      (*state)[j][i] = getSBoxInvert((*state)[j][i]);
+    }
+  }
+}
+
+static void InvShiftRows(void)
+{
+  uint8_t temp;
+
+  // Rotate first row 1 columns to right  
+  temp=(*state)[3][1];
+  (*state)[3][1]=(*state)[2][1];
+  (*state)[2][1]=(*state)[1][1];
+  (*state)[1][1]=(*state)[0][1];
+  (*state)[0][1]=temp;
+
+  // Rotate second row 2 columns to right 
+  temp=(*state)[0][2];
+  (*state)[0][2]=(*state)[2][2];
+  (*state)[2][2]=temp;
+
+  temp=(*state)[1][2];
+  (*state)[1][2]=(*state)[3][2];
+  (*state)[3][2]=temp;
+
+  // Rotate third row 3 columns to right
+  temp=(*state)[0][3];
+  (*state)[0][3]=(*state)[1][3];
+  (*state)[1][3]=(*state)[2][3];
+  (*state)[2][3]=(*state)[3][3];
+  (*state)[3][3]=temp;
+}
+
+
+// Cipher is the main function that encrypts the PlainText.
+static void Cipher(void)
+{
+  uint8_t round = 0;
+
+  // Add the First round key to the state before starting the rounds.
+  AddRoundKey(0); 
+  
+  // There will be Nr rounds.
+  // The first Nr-1 rounds are identical.
+  // These Nr-1 rounds are executed in the loop below.
+  for(round = 1; round < Nr; ++round)
+  {
+    SubBytes();
+    ShiftRows();
+    MixColumns();
+    AddRoundKey(round);
+  }
+  
+  // The last round is given below.
+  // The MixColumns function is not here in the last round.
+  SubBytes();
+  ShiftRows();
+  AddRoundKey(Nr);
+}
+
+static void InvCipher(void)
+{
+  uint8_t round=0;
+
+  // Add the First round key to the state before starting the rounds.
+  AddRoundKey(Nr); 
+
+  // There will be Nr rounds.
+  // The first Nr-1 rounds are identical.
+  // These Nr-1 rounds are executed in the loop below.
+  for(round=Nr-1;round>0;round--)
+  {
+    InvShiftRows();
+    InvSubBytes();
+    AddRoundKey(round);
+    InvMixColumns();
+  }
+  
+  // The last round is given below.
+  // The MixColumns function is not here in the last round.
+  InvShiftRows();
+  InvSubBytes();
+  AddRoundKey(0);
+}
+
+static void BlockCopy(uint8_t* output, uint8_t* input)
+{
+  uint8_t i;
+  for (i=0;i<KEYLEN;++i)
+  {
+    output[i] = input[i];
+  }
+}
+
+
+
+/*****************************************************************************/
+/* Public functions:                                                         */
+/*****************************************************************************/
+#if defined(ECB) && ECB
+
+
+void AES128_ECB_encrypt(uint8_t* input, const uint8_t* key, uint8_t* output)
+{
+  // Copy input to output, and work in-memory on output
+  BlockCopy(output, input);
+  state = (state_t*)output;
+
+  Key = key;
+  KeyExpansion();
+
+  // The next function call encrypts the PlainText with the Key using AES algorithm.
+  Cipher();
+}
+
+void AES128_ECB_decrypt(uint8_t* input, const uint8_t* key, uint8_t *output)
+{
+  // Copy input to output, and work in-memory on output
+  BlockCopy(output, input);
+  state = (state_t*)output;
+
+  // The KeyExpansion routine must be called before encryption.
+  Key = key;
+  KeyExpansion();
+
+  InvCipher();
+}
+
+
+#endif // #if defined(ECB) && ECB
+
+
+
+
+
+#if defined(CBC) && CBC
+
+
+static void XorWithIv(uint8_t* buf)
+{
+  uint8_t i;
+  for(i = 0; i < KEYLEN; ++i)
+  {
+    buf[i] ^= Iv[i];
+  }
+}
+
+void AES128_CBC_encrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv)
+{
+  uintptr_t i;
+  uint8_t remainders = length % KEYLEN; /* Remaining bytes in the last non-full block */
+
+  BlockCopy(output, input);
+  state = (state_t*)output;
+
+  // Skip the key expansion if key is passed as 0
+  if(0 != key)
+  {
+    Key = key;
+    KeyExpansion();
+  }
+
+  if(iv != 0)
+  {
+    Iv = (uint8_t*)iv;
+  }
+
+  for(i = 0; i < length; i += KEYLEN)
+  {
+    XorWithIv(input);
+    BlockCopy(output, input);
+    state = (state_t*)output;
+    Cipher();
+    Iv = output;
+    input += KEYLEN;
+    output += KEYLEN;
+  }
+
+  if(remainders)
+  {
+    BlockCopy(output, input);
+    memset(output + remainders, 0, KEYLEN - remainders); /* add 0-padding */
+    state = (state_t*)output;
+    Cipher();
+  }
+}
+
+void AES128_CBC_decrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv)
+{
+  uintptr_t i;
+  uint8_t remainders = length % KEYLEN; /* Remaining bytes in the last non-full block */
+  
+  BlockCopy(output, input);
+  state = (state_t*)output;
+
+  // Skip the key expansion if key is passed as 0
+  if(0 != key)
+  {
+    Key = key;
+    KeyExpansion();
+  }
+
+  // If iv is passed as 0, we continue to encrypt without re-setting the Iv
+  if(iv != 0)
+  {
+    Iv = (uint8_t*)iv;
+  }
+
+  for(i = 0; i < length; i += KEYLEN)
+  {
+    BlockCopy(output, input);
+    state = (state_t*)output;
+    InvCipher();
+    XorWithIv(output);
+    Iv = input;
+    input += KEYLEN;
+    output += KEYLEN;
+  }
+
+  if(remainders)
+  {
+    BlockCopy(output, input);
+    memset(output+remainders, 0, KEYLEN - remainders); /* add 0-padding */
+    state = (state_t*)output;
+    InvCipher();
+  }
+}
+
+
+#endif // #if defined(CBC) && CBC
+

+ 252 - 0
BLE_Central.si4project/Backup/app_uart_fifo(502).c

@@ -0,0 +1,252 @@
+/**
+ * Copyright (c) 2015 - 2020, 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(APP_UART)
+#include "app_uart.h"
+#include "app_fifo.h"
+#include "nrf_drv_uart.h"
+#include "nrf_assert.h"
+
+static nrf_drv_uart_t app_uart_inst = NRF_DRV_UART_INSTANCE(APP_UART_DRIVER_INSTANCE);
+
+static __INLINE uint32_t fifo_length(app_fifo_t * const fifo)
+{
+  uint32_t tmp = fifo->read_pos;
+  return fifo->write_pos - tmp;
+}
+
+#define FIFO_LENGTH(F) fifo_length(&F)              /**< Macro to calculate length of a FIFO. */
+
+
+static app_uart_event_handler_t   m_event_handler;            /**< Event handler function. */
+static uint8_t tx_buffer[1];
+static uint8_t rx_buffer[1];
+static bool m_rx_ovf;
+
+static app_fifo_t                  m_rx_fifo;                               /**< RX FIFO buffer for storing data received on the UART until the application fetches them using app_uart_get(). */
+static app_fifo_t                  m_tx_fifo;                               /**< TX FIFO buffer for storing data to be transmitted on the UART when TXD is ready. Data is put to the buffer on using app_uart_put(). */
+
+static void uart_event_handler(nrf_drv_uart_event_t * p_event, void* p_context)
+{
+    app_uart_evt_t app_uart_event;
+    uint32_t err_code;
+
+    switch (p_event->type)
+    {
+        case NRF_DRV_UART_EVT_RX_DONE:
+            // If 0, then this is a RXTO event with no new bytes.
+            if(p_event->data.rxtx.bytes == 0)
+            {
+               // A new start RX is needed to continue to receive data
+               (void)nrf_drv_uart_rx(&app_uart_inst, rx_buffer, 1);
+               break;
+            }
+
+            // Write received byte to FIFO.
+            err_code = app_fifo_put(&m_rx_fifo, p_event->data.rxtx.p_data[0]);
+            if (err_code != NRF_SUCCESS)
+            {
+                app_uart_event.evt_type          = APP_UART_FIFO_ERROR;
+                app_uart_event.data.error_code   = err_code;
+                m_event_handler(&app_uart_event);
+            }
+            // Notify that there are data available.
+            else if (FIFO_LENGTH(m_rx_fifo) != 0)
+            {
+                app_uart_event.evt_type = APP_UART_DATA_READY;
+                m_event_handler(&app_uart_event);
+            }
+
+            // Start new RX if size in buffer.
+            if (FIFO_LENGTH(m_rx_fifo) <= m_rx_fifo.buf_size_mask)
+            {
+                (void)nrf_drv_uart_rx(&app_uart_inst, rx_buffer, 1);
+            }
+            else
+            {
+                // Overflow in RX FIFO.
+                m_rx_ovf = true;
+            }
+
+            break;
+
+        case NRF_DRV_UART_EVT_ERROR:
+            app_uart_event.evt_type                 = APP_UART_COMMUNICATION_ERROR;
+            app_uart_event.data.error_communication = p_event->data.error.error_mask;
+            (void)nrf_drv_uart_rx(&app_uart_inst, rx_buffer, 1);
+            m_event_handler(&app_uart_event);
+            break;
+
+        case NRF_DRV_UART_EVT_TX_DONE:
+            // Get next byte from FIFO.
+            if (app_fifo_get(&m_tx_fifo, tx_buffer) == NRF_SUCCESS)
+            {
+                (void)nrf_drv_uart_tx(&app_uart_inst, tx_buffer, 1);
+            }
+            else
+            {
+                // Last byte from FIFO transmitted, notify the application.
+                app_uart_event.evt_type = APP_UART_TX_EMPTY;
+                m_event_handler(&app_uart_event);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+uint32_t app_uart_init(const app_uart_comm_params_t * p_comm_params,
+                             app_uart_buffers_t *     p_buffers,
+                             app_uart_event_handler_t event_handler,
+                             app_irq_priority_t       irq_priority)
+{
+    uint32_t err_code;
+
+    m_event_handler = event_handler;
+
+    if (p_buffers == NULL)
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    // Configure buffer RX buffer.
+    err_code = app_fifo_init(&m_rx_fifo, p_buffers->rx_buf, p_buffers->rx_buf_size);
+    VERIFY_SUCCESS(err_code);
+
+    // Configure buffer TX buffer.
+    err_code = app_fifo_init(&m_tx_fifo, p_buffers->tx_buf, p_buffers->tx_buf_size);
+    VERIFY_SUCCESS(err_code);
+
+    nrf_drv_uart_config_t config = NRF_DRV_UART_DEFAULT_CONFIG;
+    config.baudrate = (nrf_uart_baudrate_t)p_comm_params->baud_rate;
+    config.hwfc = (p_comm_params->flow_control == APP_UART_FLOW_CONTROL_DISABLED) ?
+            NRF_UART_HWFC_DISABLED : NRF_UART_HWFC_ENABLED;
+    config.interrupt_priority = irq_priority;
+    config.parity = p_comm_params->use_parity ? NRF_UART_PARITY_INCLUDED : NRF_UART_PARITY_EXCLUDED;
+    config.pselcts = p_comm_params->cts_pin_no;
+    config.pselrts = p_comm_params->rts_pin_no;
+    config.pselrxd = p_comm_params->rx_pin_no;
+    config.pseltxd = p_comm_params->tx_pin_no;
+
+    err_code = nrf_drv_uart_init(&app_uart_inst, &config, uart_event_handler);
+    VERIFY_SUCCESS(err_code);
+    m_rx_ovf = false;
+
+    // Turn on receiver if RX pin is connected
+    if (p_comm_params->rx_pin_no != UART_PIN_DISCONNECTED)
+    {
+        return nrf_drv_uart_rx(&app_uart_inst, rx_buffer,1);
+    }
+    else
+    {
+        return NRF_SUCCESS;
+    }
+}
+
+
+uint32_t app_uart_flush(void)
+{
+    uint32_t err_code;
+
+    err_code = app_fifo_flush(&m_rx_fifo);
+    VERIFY_SUCCESS(err_code);
+
+    err_code = app_fifo_flush(&m_tx_fifo);
+    VERIFY_SUCCESS(err_code);
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t app_uart_get(uint8_t * p_byte)
+{
+    ASSERT(p_byte);
+    bool rx_ovf = m_rx_ovf;
+
+    ret_code_t err_code =  app_fifo_get(&m_rx_fifo, p_byte);
+
+    // If FIFO was full new request to receive one byte was not scheduled. Must be done here.
+    if (rx_ovf)
+    {
+        m_rx_ovf = false;
+        uint32_t uart_err_code = nrf_drv_uart_rx(&app_uart_inst, rx_buffer, 1);
+
+        // RX resume should never fail.
+        APP_ERROR_CHECK(uart_err_code);
+    }
+
+    return err_code;
+}
+
+
+uint32_t app_uart_put(uint8_t byte)
+{
+    uint32_t err_code;
+    err_code = app_fifo_put(&m_tx_fifo, byte);
+    if (err_code == NRF_SUCCESS)
+    {
+        // The new byte has been added to FIFO. It will be picked up from there
+        // (in 'uart_event_handler') when all preceding bytes are transmitted.
+        // But if UART is not transmitting anything at the moment, we must start
+        // a new transmission here.
+        if (!nrf_drv_uart_tx_in_progress(&app_uart_inst))
+        {
+            // This operation should be almost always successful, since we've
+            // just added a byte to FIFO, but if some bigger delay occurred
+            // (some heavy interrupt handler routine has been executed) since
+            // that time, FIFO might be empty already.
+            if (app_fifo_get(&m_tx_fifo, tx_buffer) == NRF_SUCCESS)
+            {
+                err_code = nrf_drv_uart_tx(&app_uart_inst, tx_buffer, 1);
+            }
+        }
+    }
+    return err_code;
+}
+
+
+uint32_t app_uart_close(void)
+{
+    nrf_drv_uart_uninit(&app_uart_inst);
+    return NRF_SUCCESS;
+}
+#endif //NRF_MODULE_ENABLED(APP_UART)

+ 1725 - 0
BLE_Central.si4project/Backup/main(1113).c

@@ -0,0 +1,1725 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+			if( SystemManager.DevType == DEV_IOS_PARK )
+			{
+				nrf_delay_ms(1000);
+				
+			//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+
+
+			}
+			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/09\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 25 - 0
BLE_Central.si4project/Backup/main(1397).h

@@ -0,0 +1,25 @@
+
+#ifndef __MAIN_H
+#define __MAIN_H
+
+// Central Main.h  (¼ö½Å±â)
+
+
+
+
+#define IES200_1ST_MAC	0x44
+#define IES200_2ST_MAC	0x33
+#define IES200_3ST_MAC	0xC0
+
+
+
+
+#define IES600RB_VER_HIGH	1
+#define IES600RB_VER_LOW	9
+
+
+
+#endif
+
+
+

+ 1420 - 0
BLE_Central.si4project/Backup/main(1399).c

@@ -0,0 +1,1420 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								NRF_LOG_INFO("Device Registration Disable");
+								PKLedOff();
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 
+
+								AliveTest();	
+							}
+						break;
+
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+							
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+int main(void)
+{
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/01/24\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(500);
+		PKLedOff();
+		nrf_delay_ms(500);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1576 - 0
BLE_Central.si4project/Backup/main(1438).c

@@ -0,0 +1,1576 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+	
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+	
+			}
+		
+
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+	}
+}
+
+
+
+int main(void)
+{
+
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/02\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1694 - 0
BLE_Central.si4project/Backup/main(1470).c

@@ -0,0 +1,1694 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t m_tx_buf[];           /**< TX buffer. */
+extern uint8_t m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    int i;
+    ret_code_t err_code;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{
+
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+									
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+									
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{								
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+							SystemManager.LedBlinkTimer = 2000;
+							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+		break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+		break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/08-1\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 25 - 0
BLE_Central.si4project/Backup/main(1582).h

@@ -0,0 +1,25 @@
+
+#ifndef __MAIN_H
+#define __MAIN_H
+
+// Central Main.h  (¼ö½Å±â)
+
+
+
+
+#define IES200_1ST_MAC	0x44
+#define IES200_2ST_MAC	0x33
+#define IES200_3ST_MAC	0xC0
+
+
+
+
+#define IES600RB_VER_HIGH	0
+#define IES600RB_VER_LOW	9
+
+
+
+#endif
+
+
+

+ 1425 - 0
BLE_Central.si4project/Backup/main(1735).c

@@ -0,0 +1,1425 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								NRF_LOG_INFO("Device Registration Disable");
+								PKLedOff();
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 
+
+								AliveTest();	
+							}
+						break;
+
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+							
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							//AliveTest();	
+							SendAlive();
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+
+
+          
+
+            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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+int main(void)
+{
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2021/12/22\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(500);
+		PKLedOff();
+		nrf_delay_ms(500);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1416 - 0
BLE_Central.si4project/Backup/main(174).c

@@ -0,0 +1,1416 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (   m_delete_all.delete_next
+        & !m_delete_all.pending)
+    {
+        NRF_LOG_INFO("Deleting next record.");
+
+        m_delete_all.delete_next = record_delete_next();
+        if (!m_delete_all.delete_next)
+        {
+            NRF_LOG_INFO("No records left to delete.");
+        }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+        
+
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+        USART_Handler();
+
+
+            break;
+		case APP_UART_DATA:
+		
+		 NRF_LOG_INFO("APP_UART_DATA");
+		
+			break;
+
+
+			
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+            //printf("Connected to device with Nordic UART Service.\r\n");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+            if( p_ble_nus_evt->p_data[12] == DEV_NUS_EMG)
+            {
+
+				NRF_LOG_INFO("Emergency");
+				if( SystemManager.RegRequst )
+				{
+					ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+					SystemManager.RegRequst = 0;
+					SystemManager.LedBlinkRun = 0;
+					NRF_LOG_INFO("Device Registration Disable");
+					PKLedOff();
+					break;
+				}
+
+				if( SystemManager.ServerCon == 0)
+				{
+					SystemManager.LedBlinkRun = 1;
+					SystemManager.LedBlinkTimer = 5000;
+					SystemTimer.LED_TOGGLE_TIMER = 0;
+					SystemManager.DevType = 0;
+			
+		              SendEmergency();				 
+				}
+            }else if( p_ble_nus_evt->p_data[12] == DEV_NUS_ALIVE )
+            {
+
+				NRF_LOG_INFO("Alive");
+
+				AliveTest();
+
+/*				
+				if( SystemManager.RegRequst )
+				{					
+					ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+					SystemManager.RegRequst = 0;
+					SystemManager.LedBlinkRun = 0;
+					NRF_LOG_INFO("Device Registration Disable");
+					PKLedOff();
+					break;
+				}
+              SystemManager.SwitchOn = 0;
+              PKBuzzerOff();
+              PKLedOff();
+*/
+
+
+				 
+            }else if( p_ble_nus_evt->p_data[12] == DEV_NUS_REG )
+            {
+              NRF_LOG_INFO("Device Registration");
+
+
+			  SystemTimer.DEV_REG_TIMER = 0;
+
+
+			  if( SystemManager.RegRequst )
+			  {
+
+			  	
+
+				//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+				SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+				SystemManager.LedBlinkTimer = 2000;
+				SystemTimer.LED_TOGGLE_TIMER = 0;
+
+				for( i=0; i<6; i++)
+				{
+					NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+
+				}
+
+
+				NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+				NRF_LOG_RAW_INFO("\n");
+
+
+				SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				NRF_LOG_INFO("Send tWESACK");
+
+				SendCurrentRegDev();
+
+
+
+			  }else{
+
+
+
+			  }
+			  
+            }else if( p_ble_nus_evt->p_data[0] == 0x73 )
+            {
+             	 NRF_LOG_RAW_INFO("Parking %d\n", p_ble_nus_evt->data_len);
+
+				 SystemManager.SecondData = 1;
+				 SystemManager.BandType = 0x73;
+				 memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+				 CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+
+				}
+
+				SystemManager.Site[0] = SystemManager.AesEncData[4];
+				SystemManager.Site[1] = SystemManager.AesEncData[5];
+				SystemManager.Site[2] = SystemManager.AesEncData[6];
+				SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+				SystemManager.Dong[0] = SystemManager.AesEncData[8];
+				SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+				SystemManager.Ho[0] = SystemManager.AesEncData[10];
+				SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				//NRF_LOG_RAW_INFO("---2------- \n");
+				break;
+
+			  
+            }else if( p_ble_nus_evt->p_data[0] == 0x72 )	
+            {
+             	 NRF_LOG_RAW_INFO("Alarm %d\n", p_ble_nus_evt->data_len);
+
+				 SystemManager.SecondData = 1;
+				 SystemManager.BandType = 0x72;
+				 memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+				 CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+
+				}
+
+				SystemManager.Site[0] = SystemManager.AesEncData[4];
+				SystemManager.Site[1] = SystemManager.AesEncData[5];
+				SystemManager.Site[2] = SystemManager.AesEncData[6];
+				SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+				SystemManager.Dong[0] = SystemManager.AesEncData[8];
+				SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+				SystemManager.Ho[0] = SystemManager.AesEncData[10];
+				SystemManager.Ho[1] = SystemManager.AesEncData[11];
+				
+
+				//NRF_LOG_RAW_INFO("---2------- \n");
+				break;
+
+			  
+            }
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+
+
+             	 //NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				 SystemManager.SecondData = 0;
+
+
+				 for( i=0; i<p_ble_nus_evt->data_len; i++)
+				 {
+				   
+				   //NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				 }
+
+				 memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+				 //NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+				  
+				  //NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				
+
+				//NRF_LOG_RAW_INFO("\n");
+				 CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+
+				}
+
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+
+				
+
+
+				if( SystemManager.BandType == 0x73 ) //Parking
+				{
+					
+						
+					if( SystemManager.ServerCon == 0)
+					{
+						SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+						SystemManager.LedBlinkTimer = 2000;
+						SystemTimer.LED_TOGGLE_TIMER = 0;
+						SystemManager.DevType = 0;
+					
+						  SendParkingBand();
+
+						  NRF_LOG_RAW_INFO("======== Send CARACK");
+					}
+
+				}else if( SystemManager.BandType == 0x72 ) //EMG
+				{
+					
+					
+					if( SystemManager.ServerCon == 0)
+					{
+						SystemManager.LedBlinkRun = 1;
+						SystemManager.LedBlinkTimer = 5000;
+						SystemTimer.LED_TOGGLE_TIMER = 0;
+						SystemManager.DevType = 0;
+					
+						  SendEmergencyBand();
+
+						  NRF_LOG_RAW_INFO("======== Send CAREMG");
+					}
+
+				}
+
+				
+
+				
+				CarEncryptEcbACK(SystemManager.BandType);
+				memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+				SystemManager.TmpBuff[0] = SystemManager.BandType;
+				
+				
+				//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 7);
+
+
+				
+
+				
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+							
+				 sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);				 
+			
+
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected.");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+
+
+          
+
+            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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+
+
+
+int main(void)
+{
+
+ret_code_t err_code;
+ble_gap_addr_t dd;
+  dd.addr_id_peer = 0;
+  dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+  dd.addr[0] = 0x44;
+  dd.addr[1] = 0x33;
+  dd.addr[2] = 0xc0;
+  dd.addr[3] = 0x33;
+  dd.addr[4] = 0x22;
+  dd.addr[5] = 0x01;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+    NRF_LOG_INFO("Initializing fds...");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	
+	sd_ble_gap_addr_get(&new_ble_addr);
+
+
+	
+
+	
+    gatt_init();
+    nus_c_init();
+    scan_init();
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+#if 0
+        nrf_drv_spi_config_t spi_config = NRF_DRV_SPI_DEFAULT_CONFIG;
+    spi_config.ss_pin   = SPI_SS_PIN;
+    spi_config.miso_pin = SPI_MISO_PIN;
+    spi_config.mosi_pin = SPI_MOSI_PIN;
+    spi_config.sck_pin  = SPI_SCK_PIN;
+    APP_ERROR_CHECK(nrf_drv_spi_init(&spi, &spi_config, spi_event_handler, NULL));
+
+
+    SC16IS750_ResetDevice();
+#endif
+
+     
+
+ PKLedOff();
+
+    //FlashTest();
+
+
+    LoadRegMac();
+
+	TestAES();
+	
+  //delete_all_begin();
+    // Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+}

+ 1648 - 0
BLE_Central.si4project/Backup/main(1771).c

@@ -0,0 +1,1648 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t m_tx_buf[];           /**< TX buffer. */
+extern uint8_t m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+// BLE Connect 이후 nus Event
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    int i;
+    ret_code_t err_code;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case TRANSFER_UNIT_EMG_SWITCH:		// 무선 비상벨 신호
+
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{
+
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+									
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+									
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									}
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+									
+									SendEmergency();
+								break;
+							}
+
+
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{								
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+
+								break;
+
+								case SYSTEM_NONE:
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+								
+									AliveTest();	
+								break;
+							}
+
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+							
+						break;
+					}
+				break;
+
+				// 밴드 주차
+				case TRANSFER_UNIT_BAND_PARKING:
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				// 밴드 비상 
+				case TRANSFER_UNIT_BAND_EMG:		
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					// BAND PARKING
+					case TRANSFER_UNIT_BAND_PARKING:
+						if( SystemManager.ServerCon == 0)
+						{
+
+							// CARACK ECB 암호화 전송 
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							// Disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = AES_ENC_NONE;
+
+							SendParkingBand();
+
+						}
+					break;
+
+					// BAND EMG
+					case TRANSFER_UNIT_BAND_EMG:
+	
+						if( SystemManager.ServerCon == 0)
+						{
+
+#if 0
+							// CARACK ECB 암호화 전송 
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+#endif
+							// Disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = AES_ENC_NONE;
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					// New iOS App
+					case TRANSFER_UNIT_NEW_IOS_PARKING:		
+					
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							// Disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = AES_ENC_NONE;
+
+							SendParkingApp();
+
+						}
+					break;
+					
+				}
+			}
+
+		break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+		break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/09-0\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1719 - 0
BLE_Central.si4project/Backup/main(1947).c

@@ -0,0 +1,1719 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+	2022/03/09 (Release V1.0)
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+	2022/03/24 (Release V1.1)
+	안드로이드 원패스 필터 수정
+	New iOS 원패스 추가 	
+
+
+*************************************************************************************/
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.Encryption_Mode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+							// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+
+#if 0
+			if( SystemManager.DevType == DEV_IOS_PARK &&  p_gap_evt->params.disconnected.reason != 0x16 )
+			{
+				NVIC_SystemReset();
+				//nrf_delay_ms(100);
+				
+				//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			}
+#endif			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 1.10  2022/03/20\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+	while(1)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+		}
+    }
+}
+

+ 1725 - 0
BLE_Central.si4project/Backup/main(2048).c

@@ -0,0 +1,1725 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+
+#if 0
+			if( SystemManager.DevType == DEV_IOS_PARK &&  p_gap_evt->params.disconnected.reason != 0x16 )
+			{
+				NVIC_SystemReset();
+				//nrf_delay_ms(100);
+				
+				//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			}
+#endif			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/20\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+	while(1)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+		}
+    }
+}
+

+ 1403 - 0
BLE_Central.si4project/Backup/main(2072).c

@@ -0,0 +1,1403 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("EMG SWITCH ---  Emergency");
+							if( SystemManager.RegRequst )
+							{
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								NRF_LOG_INFO("Device Registration Disable");
+								PKLedOff();
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+					              SendEmergency();				 
+							}
+						break;
+
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("EMG SWITCH ---  Alive");
+
+							if( SystemManager.RegRequst )	// 등록 설정 해제
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 
+
+								AliveTest();	
+							}
+						break;
+
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("EMG SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+							
+							if( SystemManager.RegRequst )
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+
+						break;
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+
+
+          
+
+            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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+
+
+
+int main(void)
+{
+
+ret_code_t err_code;
+ble_gap_addr_t dd;
+  dd.addr_id_peer = 0;
+  dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+  dd.addr[0] = 0x44;
+  dd.addr[1] = 0x33;
+  dd.addr[2] = 0xc0;
+  dd.addr[3] = 0x33;
+  dd.addr[4] = 0x22;
+  dd.addr[5] = 0x01;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 20211108\n");
+
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	
+    gatt_init();
+    nus_c_init();
+    scan_init();
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+	// Enter main loop.
+	
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1724 - 0
BLE_Central.si4project/Backup/main(2344).c

@@ -0,0 +1,1724 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+
+#if 0
+			if( SystemManager.DevType == DEV_IOS_PARK &&  p_gap_evt->params.disconnected.reason != 0x16 )
+			{
+				NVIC_SystemReset();
+				//nrf_delay_ms(100);
+				
+				//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			}
+#endif			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.93  2022/03/20\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+	while(1)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+		}
+    }
+}
+

+ 1730 - 0
BLE_Central.si4project/Backup/main(3159).c

@@ -0,0 +1,1730 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+
+#if 0
+			if( SystemManager.DevType == DEV_IOS_PARK &&  p_gap_evt->params.disconnected.reason != 0x16 )
+			{
+				NVIC_SystemReset();
+				//nrf_delay_ms(100);
+				
+				//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			}
+#endif			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/20\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1426 - 0
BLE_Central.si4project/Backup/main(3197).c

@@ -0,0 +1,1426 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+							
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+int main(void)
+{
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/01/24\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(500);
+		PKLedOff();
+		nrf_delay_ms(500);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 25 - 0
BLE_Central.si4project/Backup/main(3281).h

@@ -0,0 +1,25 @@
+
+#ifndef __MAIN_H
+#define __MAIN_H
+
+// Central Main.h  (¼ö½Å±â)
+
+
+
+
+#define IES200_1ST_MAC	0x44
+#define IES200_2ST_MAC	0x33
+#define IES200_3ST_MAC	0xC0
+
+
+
+
+#define IES600RB_VER_HIGH	1
+#define IES600RB_VER_LOW	0 
+
+
+
+#endif
+
+
+

+ 1724 - 0
BLE_Central.si4project/Backup/main(3414).c

@@ -0,0 +1,1724 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+	2022/03/09 (Release V1.0)
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+	2022/03/24 (Release V1.1)
+	안드로이드 원패스 필터 수정
+	New iOS 원패스 추가 	
+
+
+*************************************************************************************/
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.Encryption_Mode){
+				case AES_ENC_WES:
+					CarEncryptEcb( AES_ENC_WES );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+			
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+							// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+
+#if 0
+			if( SystemManager.DevType == DEV_IOS_PARK &&  p_gap_evt->params.disconnected.reason != 0x16 )
+			{
+				NVIC_SystemReset();
+				//nrf_delay_ms(100);
+				
+				//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			}
+#endif			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 1.10  2022/03/20\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+	while(1)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+		}
+    }
+}
+

+ 1717 - 0
BLE_Central.si4project/Backup/main(3466).c

@@ -0,0 +1,1717 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/09\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1713 - 0
BLE_Central.si4project/Backup/main(3685).c

@@ -0,0 +1,1713 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/09\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1698 - 0
BLE_Central.si4project/Backup/main(3897).c

@@ -0,0 +1,1698 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{
+
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+									
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+									
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{								
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+							SystemManager.LedBlinkTimer = 2000;
+							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+		break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+		break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/07\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 25 - 0
BLE_Central.si4project/Backup/main(3902).h

@@ -0,0 +1,25 @@
+
+#ifndef __MAIN_H
+#define __MAIN_H
+
+// Central Main.h  (¼ö½Å±â)
+
+
+
+
+#define IES200_1ST_MAC	0x44
+#define IES200_2ST_MAC	0x33
+#define IES200_3ST_MAC	0xC0
+
+
+
+
+#define IES600RB_VER_HIGH	0
+#define IES600RB_VER_LOW	1
+
+
+
+#endif
+
+
+

+ 1725 - 0
BLE_Central.si4project/Backup/main(3917).c

@@ -0,0 +1,1725 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+	2022/03/09 (Release V1.0)
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+	2022/03/24 (Release V1.1)
+	안드로이드 원패스 필터 수정
+	New iOS 원패스 추가 	
+
+
+*************************************************************************************/
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.Encryption_Mode){
+				case AES_ENC_WES:
+//					CarEncryptEcb( AES_ENC_WES );
+					Wes_Encryp_Ecb();
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+			
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+							// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+
+#if 0
+			if( SystemManager.DevType == DEV_IOS_PARK &&  p_gap_evt->params.disconnected.reason != 0x16 )
+			{
+				NVIC_SystemReset();
+				//nrf_delay_ms(100);
+				
+				//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			}
+#endif			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 1.10  2022/03/20\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+	while(1)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+		}
+    }
+}
+

+ 1420 - 0
BLE_Central.si4project/Backup/main(400).c

@@ -0,0 +1,1420 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								NRF_LOG_INFO("Device Registration Disable");
+								PKLedOff();
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 
+
+								AliveTest();	
+							}
+						break;
+
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+							
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							//AliveTest();	
+							SendAlive();
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+int main(void)
+{
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2021/12/28\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(500);
+		PKLedOff();
+		nrf_delay_ms(500);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1752 - 0
BLE_Central.si4project/Backup/main(4204).c

@@ -0,0 +1,1752 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+			if( SystemManager.DevType == DEV_IOS_PARK &&  p_gap_evt->params.disconnected.reason != 0x16 )
+			{
+			NVIC_SystemReset();
+				//nrf_delay_ms(100);
+				
+			//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			 //BLEINIT();
+
+
+			}
+			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+
+
+void BLEINIT()
+{
+
+	ble_gap_addr_t dd;
+	NRF_LOG_INFO("BLEINIT()\n");
+		
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+}
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/09\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 25 - 0
BLE_Central.si4project/Backup/main(4247).h

@@ -0,0 +1,25 @@
+
+#ifndef __MAIN_H
+#define __MAIN_H
+
+// Central Main.h  (¼ö½Å±â)
+
+
+
+
+#define IES200_1ST_MAC	0x44
+#define IES200_2ST_MAC	0x33
+#define IES200_3ST_MAC	0xC0
+
+
+
+
+#define IES600RB_VER_HIGH	1
+#define IES600RB_VER_LOW	1
+
+
+
+#endif
+
+
+

+ 1700 - 0
BLE_Central.si4project/Backup/main(5194).c

@@ -0,0 +1,1700 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									SystemManager.RegRequst = 0;
+									SystemManager.LedBlinkRun = 0;
+									
+									SystemManager.System_State = SYSTEM_NONE;
+								
+									ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								
+									NRF_LOG_INFO("Device Registration Disable");
+
+
+									//======================================>>>>>
+									// 등록된 맥일경우 등록모드 취소 
+									//======================================>>>>>
+
+								
+									SystemManager.SwitchOn = 0;
+									PKBuzzerOff();
+									PKLedOff();
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									SystemManager.RegRequst = 0;
+									SystemManager.LedBlinkRun = 0;
+									
+									SystemManager.System_State = SYSTEM_NONE;
+
+									ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+									NRF_LOG_INFO("Device Registration Disable");
+
+									//======================================>>>>>
+									// 등록된 맥일경우 등록모드 취소 
+									//======================================>>>>>
+
+
+									SystemManager.SwitchOn = 0;
+									PKBuzzerOff();
+									PKLedOff();
+
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+							SystemManager.LedBlinkTimer = 2000;
+							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+		break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+		break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/07\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1645 - 0
BLE_Central.si4project/Backup/main(530).c

@@ -0,0 +1,1645 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t m_tx_buf[];           /**< TX buffer. */
+extern uint8_t m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+// BLE Connect 이후 nus Event
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    int i;
+    ret_code_t err_code;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case TRANSFER_UNIT_EMG_SWITCH:		// 무선 비상벨 신호
+
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{
+
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+									
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+									
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									}
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+									
+									SendEmergency();
+								break;
+							}
+
+
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{								
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+
+								break;
+
+								case SYSTEM_NONE:
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+								
+									AliveTest();	
+								break;
+							}
+
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+							
+						break;
+					}
+				break;
+
+				// 밴드 주차
+				case TRANSFER_UNIT_BAND_PARKING:
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				// 밴드 비상 
+				case TRANSFER_UNIT_BAND_EMG:		
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					// BAND PARKING
+					case TRANSFER_UNIT_BAND_PARKING:
+						if( SystemManager.ServerCon == 0)
+						{
+
+							// CARACK ECB 암호화 전송 
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							// Disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = AES_ENC_NONE;
+
+							SendParkingBand();
+
+						}
+					break;
+
+					// BAND EMG
+					case TRANSFER_UNIT_BAND_EMG:
+	
+						if( SystemManager.ServerCon == 0)
+						{
+
+							// CARACK ECB 암호화 전송 
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							// Disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = AES_ENC_NONE;
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					// New iOS App
+					case TRANSFER_UNIT_NEW_IOS_PARKING:		
+					
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							// Disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = AES_ENC_NONE;
+
+							SendParkingApp();
+
+						}
+					break;
+					
+				}
+			}
+
+		break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+		break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/08-1\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 25 - 0
BLE_Central.si4project/Backup/main(5353).h

@@ -0,0 +1,25 @@
+
+#ifndef __MAIN_H
+#define __MAIN_H
+
+// Central Main.h  (¼ö½Å±â)
+
+
+
+
+#define IES200_1ST_MAC	0x44
+#define IES200_2ST_MAC	0x33
+#define IES200_3ST_MAC	0xC0
+
+
+
+
+#define IES600RB_VER_HIGH	0
+#define IES600RB_VER_LOW	9 
+
+
+
+#endif
+
+
+

+ 1428 - 0
BLE_Central.si4project/Backup/main(5379).c

@@ -0,0 +1,1428 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								NRF_LOG_INFO("Device Registration Disable");
+								PKLedOff();
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 
+
+								AliveTest();	
+							}
+						break;
+
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+							
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							//AliveTest();	
+							SendAlive();
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+
+
+          
+
+            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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+ 
+
+
+int main(void)
+{
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2021/12/19\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	for(i=0; i<4; i++){
+	
+		PKLedOn();
+		nrf_delay_ms(500);
+		PKLedOff();
+		nrf_delay_ms(500);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+	// Enter main loop.
+	
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1788 - 0
BLE_Central.si4project/Backup/main(5567).c

@@ -0,0 +1,1788 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+					//CarDecryptEcb( tmpData11, &SystemManager.AesEncData[0] );
+					NRF_LOG_RAW_INFO("WES ");
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					
+					memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+					
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{
+
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+									
+										ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									}
+
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);									
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+							SystemManager.DevType = 0;
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{								
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+
+										ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+
+
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+									
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+							SystemManager.DevType = 0;
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+								NRF_LOG_INFO("Send WESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+							SystemManager.DevType = 0;
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.DevType = 0;
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x75:		// 원패스앱 
+				
+					NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x75;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+				
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				//NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							
+							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+							SystemManager.LedBlinkTimer = 2000;
+							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+		break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+		break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/09\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1786 - 0
BLE_Central.si4project/Backup/main(5718).c

@@ -0,0 +1,1786 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+					//CarDecryptEcb( tmpData11, &SystemManager.AesEncData[0] );
+					NRF_LOG_RAW_INFO("WES ");
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					
+					memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+					
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{
+
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+									
+										ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									}
+
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);									
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+							SystemManager.DevType = 0;
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{								
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+
+										ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+
+
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+									
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+							SystemManager.DevType = 0;
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+								NRF_LOG_INFO("Send WESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+							SystemManager.DevType = 0;
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.DevType = 0;
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x75:		// 원패스앱 
+				
+					NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x75;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+				
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				//NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							
+							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+							SystemManager.LedBlinkTimer = 2000;
+							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+		break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+		break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/03/09\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1654 - 0
BLE_Central.si4project/Backup/main(5892).c

@@ -0,0 +1,1654 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t m_tx_buf[];           /**< TX buffer. */
+extern uint8_t m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    int i;
+    ret_code_t err_code;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{
+
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+									
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+									
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{								
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+
+										ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+							SystemManager.LedBlinkTimer = 2000;
+							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+			}
+
+		break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+		break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/08-1\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1714 - 0
BLE_Central.si4project/Backup/main(5937).c

@@ -0,0 +1,1714 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									SystemManager.RegRequst = 0;
+									SystemManager.LedBlinkRun = 0;
+									
+									SystemManager.System_State = SYSTEM_NONE;
+								
+									ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								
+									NRF_LOG_INFO("Device Registration Disable");
+								
+									SystemManager.SwitchOn = 0;
+									PKBuzzerOff();
+									PKLedOff();
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									SystemManager.RegRequst = 0;
+									SystemManager.LedBlinkRun = 0;
+									
+									SystemManager.System_State = SYSTEM_NONE;
+
+									ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+									NRF_LOG_INFO("Device Registration Disable");
+
+									SystemManager.SwitchOn = 0;
+									PKBuzzerOff();
+									PKLedOff();
+
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+							SystemManager.LedBlinkTimer = 2000;
+							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+	
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/05\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1741 - 0
BLE_Central.si4project/Backup/main(5997).c

@@ -0,0 +1,1741 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+					//CarDecryptEcb( tmpData11, &SystemManager.AesEncData[0] );
+					NRF_LOG_RAW_INFO("WES ");
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					
+					memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+					
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{
+
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+									
+										ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									}
+
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);									
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									if( FindRegMac(ScanHSBuff) == 1 )
+									{								
+										SystemManager.RegRequst = 0;
+										SystemManager.LedBlinkRun = 0;
+										
+										SystemManager.System_State = SYSTEM_NONE;
+
+										ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+										NRF_LOG_INFO("Device Registration Disable");
+
+										SystemManager.SwitchOn = 0;
+										PKBuzzerOff();
+										PKLedOff();
+									}
+
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+
+
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+									
+									err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+									APP_ERROR_CHECK(err_code);
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+								NRF_LOG_INFO("Send WESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+							SystemManager.LedBlinkTimer = 2000;
+							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+		break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+		break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/14\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1716 - 0
BLE_Central.si4project/Backup/main(6682).c

@@ -0,0 +1,1716 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+	SystemTimer.Delay_1ms_cnt++;
+   
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}else if( SystemManager.BandMode == AES_ENC_PCA )
+			{
+
+				CarEncryptEcb( AES_ENC_PCA );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	
+    		}
+
+		break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									SystemManager.RegRequst = 0;
+									SystemManager.LedBlinkRun = 0;
+									
+									SystemManager.System_State = SYSTEM_NONE;
+								
+									ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								
+									NRF_LOG_INFO("Device Registration Disable");
+								
+									SystemManager.SwitchOn = 0;
+									PKBuzzerOff();
+									PKLedOff();
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									SystemManager.RegRequst = 0;
+									SystemManager.LedBlinkRun = 0;
+									
+									SystemManager.System_State = SYSTEM_NONE;
+
+									ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+									NRF_LOG_INFO("Device Registration Disable");
+
+									SystemManager.SwitchOn = 0;
+									PKBuzzerOff();
+									PKLedOff();
+
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+							{
+//								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+							SystemManager.LedBlinkTimer = 2000;
+							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+	
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/05\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1419 - 0
BLE_Central.si4project/Backup/main(6900).c

@@ -0,0 +1,1419 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								NRF_LOG_INFO("Device Registration Disable");
+								PKLedOff();
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 
+
+								AliveTest();	
+							}
+						break;
+
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+							
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							SendAlive();
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+int main(void)
+{
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/01/21\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(500);
+		PKLedOff();
+		nrf_delay_ms(500);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1722 - 0
BLE_Central.si4project/Backup/main(7071).c

@@ -0,0 +1,1722 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+            if( p_gap_evt->params.disconnected.reason == 0x13)
+            {
+                    sd_ble_gap_disconnect(SystemManager.NusHandle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            }
+			
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/09\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1685 - 0
BLE_Central.si4project/Backup/main(7114).c

@@ -0,0 +1,1685 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+#if 1							
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									SystemManager.RegRequst = 0;
+									SystemManager.LedBlinkRun = 0;
+									
+									SystemManager.System_State = SYSTEM_NONE;
+								
+									ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								
+									NRF_LOG_INFO("Device Registration Disable");
+								
+									SystemManager.SwitchOn = 0;
+									PKBuzzerOff();
+									PKLedOff();
+								
+								break;
+								
+								case SYSTEM_NONE:
+									SystemManager.LedBlinkRun = 1;
+									SystemManager.LedBlinkTimer = 5000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+									SystemManager.DevType = 0;
+							
+									SendEmergency();
+								break;
+							}
+
+#else
+
+								
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+#endif
+
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+#if 1
+							switch(SystemManager.System_State){
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:	
+								case SYSTEM_SERVER_COMM_REQ:										
+
+								break;
+
+								case SYSTEM_REGISTER:
+									SystemManager.RegRequst = 0;
+									SystemManager.LedBlinkRun = 0;
+									
+									SystemManager.System_State = SYSTEM_NONE;
+
+									ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+									NRF_LOG_INFO("Device Registration Disable");
+
+									SystemManager.SwitchOn = 0;
+									PKBuzzerOff();
+									PKLedOff();
+
+								break;
+
+								case SYSTEM_NONE:
+									AliveTest();	
+								break;
+							}
+
+#else
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								
+								SystemManager.System_State = SYSTEM_NONE;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+#endif
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+	
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+	
+			}
+		
+
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d]\n", SystemTimer.SYSTEM_REGISTER_CNT);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT);
+			
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/02/04\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1444 - 0
BLE_Central.si4project/Backup/main(7218).c

@@ -0,0 +1,1444 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+int main(void)
+{
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/01/24\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(500);
+		PKLedOff();
+		nrf_delay_ms(500);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1468 - 0
BLE_Central.si4project/Backup/main(7242).c

@@ -0,0 +1,1468 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 무선 비상벨 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								PKLedOff();
+
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+							// 테스트 버튼 동작시 
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 							
+								AliveTest();	
+							}
+						break;
+
+							// 등록버튼 동작시
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+							// Alive 동작시 
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+							SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+							SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+							SendAlive();
+							
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+int main(void)
+{
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2022/01/24\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(500);
+		PKLedOff();
+		nrf_delay_ms(500);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1722 - 0
BLE_Central.si4project/Backup/main(7447).c

@@ -0,0 +1,1722 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SystemManager.NusHandle = p_ble_nus_c->conn_handle;
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+            if( p_gap_evt->params.disconnected.reason == 0x13)
+            {
+                    sd_ble_gap_disconnect(SystemManager.NusHandle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            }
+			
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/09\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1714 - 0
BLE_Central.si4project/Backup/main(7469).c

@@ -0,0 +1,1714 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.BandMode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK");
+						}
+					break;
+					
+				}
+			}
+
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.92  2022/03/09\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+
+		}
+
+		
+    }
+	
+}

+ 1420 - 0
BLE_Central.si4project/Backup/main(7722).c

@@ -0,0 +1,1420 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								NRF_LOG_INFO("Device Registration Disable");
+								PKLedOff();
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)		
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+								SendEmergency();				 
+							}
+						break;
+
+						case DEV_NUS_TEST:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+
+							if( SystemManager.RegRequst )	// 현재 등록모드일 경우    등록 모드  해제 
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 
+
+								AliveTest();	
+							}
+						break;
+
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+							
+							if( SystemManager.RegRequst )		// 현재 등록모드일 경우 
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+						break;
+
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+							SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+						
+							//AliveTest();	
+							SendAlive();
+						break;
+
+						
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+int main(void)
+{
+
+	uint8_t i;
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2021/12/22-1\n");
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(500);
+		PKLedOff();
+		nrf_delay_ms(500);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+
+	// Enter main loop.
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1403 - 0
BLE_Central.si4project/Backup/main(7788).c

@@ -0,0 +1,1403 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("EMG SWITCH ---  Emergency");
+							if( SystemManager.RegRequst )
+							{
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								NRF_LOG_INFO("Device Registration Disable");
+								PKLedOff();
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+					              SendEmergency();				 
+							}
+						break;
+
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("EMG SWITCH ---  Alive");
+
+							if( SystemManager.RegRequst )	// 등록 설정 해제
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 
+
+								AliveTest();	
+							}
+						break;
+
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("EMG SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+							
+							if( SystemManager.RegRequst )
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+
+						break;
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+
+
+          
+
+            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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+
+
+
+int main(void)
+{
+
+ret_code_t err_code;
+ble_gap_addr_t dd;
+  dd.addr_id_peer = 0;
+  dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+  dd.addr[0] = 0x44;
+  dd.addr[1] = 0x33;
+  dd.addr[2] = 0xc0;
+  dd.addr[3] = 0x33;
+  dd.addr[4] = 0x22;
+  dd.addr[5] = 0x01;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 2021/12/15\n");
+
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	
+    gatt_init();
+    nus_c_init();
+    scan_init();
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+	// Enter main loop.
+	
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1403 - 0
BLE_Central.si4project/Backup/main(7818).c

@@ -0,0 +1,1403 @@
+/**
+ * Copyright (c) 2016 - 2020, 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 <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "sysmgr.h"
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+   gTimeCounter++;
+   SystemTimer.MS_1++;
+  SystemTimer.UART_LAST_RECV_TIMER++;
+  SystemTimer.SEND_TEST_TIMER++;
+  SystemTimer.LED_TOGGLE_TIMER++;
+  SystemTimer.TMR_CON_START++;
+  SystemTimer.PARK_KEEP_TIMER++;
+
+  SystemTimer.DEV_REG_TIMER++;
+  SystemTimer.SVR_SEND_TIMER++;
+
+
+
+  SystemManager.LedBlinkTimer--;
+  
+
+  if( SystemTimer.TMR_CON_START == 10000 )
+  {
+	  sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+
+  }
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+            NRF_LOG_INFO("Discovery complete.");
+            //printf("Discovery complete.\r\n");
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+
+			if( SystemManager.BandMode == AES_ENC_CAR )
+			{
+
+				NRF_LOG_INFO("SystemManager.BandMode == AES_ENC_CAR\n");
+
+				CarEncryptEcb( AES_ENC_CAR );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+//				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 5);		
+
+
+			}else if( SystemManager.BandMode == AES_ENC_EMG )
+			{
+				CarEncryptEcb( AES_ENC_EMG );
+				ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);		
+			}
+
+			//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);			
+			//err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+
+            break;
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+            for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			SystemManager.NusData = p_ble_nus_evt->p_data[12];
+
+
+			switch(p_ble_nus_evt->p_data[0]){
+
+				case 0x74:		// 송신기 신호
+
+					switch(p_ble_nus_evt->p_data[12]){
+
+						case DEV_NUS_EMG: 
+							NRF_LOG_INFO("EMG SWITCH ---  Emergency");
+							if( SystemManager.RegRequst )
+							{
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+								NRF_LOG_INFO("Device Registration Disable");
+								PKLedOff();
+								break;
+							}
+
+							if( SystemManager.ServerCon == 0)
+							{
+								SystemManager.LedBlinkRun = 1;
+								SystemManager.LedBlinkTimer = 5000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+								SystemManager.DevType = 0;
+						
+					              SendEmergency();				 
+							}
+						break;
+
+						case DEV_NUS_ALIVE:
+							
+							NRF_LOG_INFO("EMG SWITCH ---  Alive");
+
+							if( SystemManager.RegRequst )	// 등록 설정 해제
+							{ 				  
+								SystemManager.RegRequst = 0;
+								SystemManager.LedBlinkRun = 0;
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+
+								NRF_LOG_INFO("Device Registration Disable");
+
+								SystemManager.SwitchOn = 0;
+								PKBuzzerOff();
+								PKLedOff();
+
+							}else{		// Alive Test 
+
+								AliveTest();	
+							}
+						break;
+
+						case DEV_NUS_REG:
+							
+							NRF_LOG_INFO("EMG SWITCH ---  Device Registration");
+												
+							SystemTimer.DEV_REG_TIMER = 0;
+							
+							if( SystemManager.RegRequst )
+							{
+								//SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+								SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG+1;
+
+								SystemManager.LedBlinkTimer = 2000;
+								SystemTimer.LED_TOGGLE_TIMER = 0;
+
+								for( i=0; i<6; i++)
+								{
+									NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+								}
+
+								NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+								NRF_LOG_RAW_INFO("\n");
+
+								SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+								ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+								NRF_LOG_INFO("Send tWESACK");
+
+								SendCurrentRegDev();
+							
+							}else{
+								;					
+							}
+
+						break;
+
+					}
+				break;
+
+				case 0x73:	// 밴드 주차 
+
+					NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x73;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+
+				case 0x72:		// 밴드 비상 
+				
+					NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+					SystemManager.SecondData = 1;
+					SystemManager.BandType = 0x72;
+					
+					memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+					CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+					
+					for( i=0; i<16; i++)
+					{
+						NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+					}
+
+					SystemManager.Site[0] = SystemManager.AesEncData[4];
+					SystemManager.Site[1] = SystemManager.AesEncData[5];
+					SystemManager.Site[2] = SystemManager.AesEncData[6];
+					SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+					SystemManager.Dong[0] = SystemManager.AesEncData[8];
+					SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+					SystemManager.Ho[0] = SystemManager.AesEncData[10];
+					SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+				break;
+			}
+
+
+
+            //err_code = sd_ble_gap_disconnect(m_conn_handle,
+             //                                BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+            //APP_ERROR_CHECK(err_code);
+   			//ble_nus_data_send(&m_ble_nus_c, data_array, &length, m_conn_handle);
+
+
+			if( SystemManager.SecondData )	// 두번째 Packet
+			{
+
+				NRF_LOG_RAW_INFO("======== DEV_BAND\n");
+
+				//NRF_LOG_RAW_INFO("======== Car Information Second %d\n", p_ble_nus_evt->data_len);
+				SystemManager.SecondData = 0;
+
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+//					NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+				}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				//nrf_delay_ms(100);
+				
+				switch(SystemManager.BandType){
+					case 0x73:	// BAND PARKING
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = COM_TYPE_SVR_PARKING;
+//							SystemManager.LedBlinkTimer = 2000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+						
+//							SendParkingBand();
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+//							memcpy( &SystemManager.TmpBuff[1], SystemManager.AesEncData, 16);
+//							SystemManager.TmpBuff[0] = SystemManager.BandType;
+							//ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 6);
+//							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.TmpBuff, 16);
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+							SendParkingBand();
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+//							SystemManager.LedBlinkRun = 1;
+//							SystemManager.LedBlinkTimer = 5000;
+//							SystemTimer.LED_TOGGLE_TIMER = 0;
+							SystemManager.DevType = 0;
+
+							SendEmergencyBand();
+
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.BandMode = 0;
+
+
+							// 추후 Disconnet 로 변경해야 함
+//							nrf_delay_ms(500);
+//							NRF_LOG_RAW_INFO("system Reboot\n");
+//							sd_nvic_SystemReset();
+						}
+					break;
+				}
+
+
+				//ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				// NRF_LOG_RAW_INFO("======== Send CARACK");
+
+
+				// jakuja
+//				err_code = sd_ble_gap_disconnect(p_ble_nus_evt->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+//				APP_ERROR_CHECK(err_code);
+
+			}
+
+
+#if 0
+			if( p_ble_nus_evt->p_data[0] == 0x73 )
+			{
+   				ble_nus_c_string_send(&m_ble_nus_c, "CARACK", 6);
+				 NRF_LOG_INFO("Send CARACK");
+			}else if( p_ble_nus_evt->p_data[0] == 0x72 )
+			{
+				ble_nus_c_string_send(&m_ble_nus_c, "EMGACK", 6);
+				 NRF_LOG_INFO("Send EMGACK");
+			}else{
+
+				ble_nus_c_string_send(&m_ble_nus_c, "tWESACK", 7);
+				 NRF_LOG_INFO("Send tWESACK");
+			}
+#endif
+
+			//sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+			
+            break;
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+           // printf("Disconnected.\r\n");
+            scan_start();
+            break;
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+
+
+          
+
+            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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+
+
+
+int main(void)
+{
+
+ret_code_t err_code;
+ble_gap_addr_t dd;
+  dd.addr_id_peer = 0;
+  dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+  dd.addr[0] = 0x44;
+  dd.addr[1] = 0x33;
+  dd.addr[2] = 0xc0;
+  dd.addr[3] = 0x33;
+  dd.addr[4] = 0x22;
+  dd.addr[5] = 0x01;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("BLE CENTRAL Program Start 20211115\n");
+
+
+    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();    
+    db_discovery_init();
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	
+    gatt_init();
+    nus_c_init();
+    scan_init();
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+//	TestAES();
+	
+	//delete_all_begin();
+	// Enter main loop.
+	
+    for (;;)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+
+		delete_all_process();
+    }
+	
+}

+ 1728 - 0
BLE_Central.si4project/Backup/main(8087).c

@@ -0,0 +1,1728 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+	2022/03/09 (Release V1.0)
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+	2022/03/24 (Release V1.1)
+	안드로이드 원패스 필터 수정
+	New iOS 원패스 추가 	
+
+
+*************************************************************************************/
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            NRF_LOG_INFO("=======================================================ble_nus_c_evt_handler -- BLE_NUS_C_EVT_DISCOVERY_COMPLETE");
+
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.Encryption_Mode){
+				case AES_ENC_WES:
+//					CarEncryptEcb( AES_ENC_WES );
+					Wes_Encryp_Ecb();
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+			
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+							// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+
+#if 0
+			if( SystemManager.DevType == DEV_IOS_PARK &&  p_gap_evt->params.disconnected.reason != 0x16 )
+			{
+				NVIC_SystemReset();
+				//nrf_delay_ms(100);
+				
+				//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			}
+#endif			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 1.10  2022/04/05\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+	while(1)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+		}
+    }
+}
+

+ 1724 - 0
BLE_Central.si4project/Backup/main(8160).c

@@ -0,0 +1,1724 @@
+/**
+ * Copyright (c) 2016 - 2020, 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.
+ *
+ */
+
+
+
+/*************************************************************************************
+
+	2022/01/26 
+    업데이트 후 바뀐 버전정보 확인을 위해 	부팅시 서버에 버전정보 전달
+
+
+
+	2022/03/09
+	비상벨 프로토콜 확인
+	안드로이드 원패스 필터 수정
+
+
+
+
+*************************************************************************************/
+
+
+
+
+
+
+
+
+
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_uart.h"
+#include "ble_db_discovery.h"
+#include "app_timer.h"
+#include "app_util.h"
+#include "bsp_btn_ble.h"
+#include "ble.h"
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "nrf_sdh.h"
+#include "nrf_sdh_ble.h"
+#include "nrf_sdh_soc.h"
+#include "ble_nus_c.h"
+#include "nrf_ble_gatt.h"
+#include "nrf_pwr_mgmt.h"
+#include "nrf_ble_scan.h"
+
+#include "peer_manager.h"
+
+#include "nrf_log.h"
+#include "nrf_log_ctrl.h"
+#include "nrf_log_default_backends.h"
+
+#include "our_service.h"
+
+#include "board_gpi.h"
+
+#include "nrf_spi.h"
+#include "nrf_drv_spi.h"
+#include "app_util_platform.h"
+#include "nrf_gpio.h"
+#include "nrf_delay.h"
+#include "boards.h"
+#include "app_error.h"
+#include <string.h>
+
+#include "main.h"
+#include "sysmgr.h"
+
+
+#define APP_BLE_CONN_CFG_TAG    1                                       /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
+#define APP_BLE_OBSERVER_PRIO   3                                       /**< BLE observer priority of the application. There is no need to modify this value. */
+
+#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
+#define UART_RX_BUF_SIZE        256                                     /**< UART RX buffer size. */
+
+#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN              /**< UUID type for the Nordic UART Service (vendor specific). */
+
+#define ECHOBACK_BLE_UART_DATA  1                                       /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
+
+
+BLE_NUS_C_DEF(m_ble_nus_c);                                             /**< BLE Nordic UART Service (NUS) client instance. */
+NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
+BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
+NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
+NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
+               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
+               NRF_BLE_GQ_QUEUE_SIZE);
+
+
+
+#define SPI_INSTANCE  0 /**< SPI instance index. */
+//const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);  /**< SPI instance. */
+//const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false };  /**< SPI instance. */
+volatile bool spi_xfer_done;  /**< Flag used to indicate that SPI instance completed the transfer. */
+
+APP_TIMER_DEF(m_our_char_timer_id);
+#define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
+
+
+
+static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
+
+
+static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; 
+
+unsigned int gTimeCounter = 0;
+/**@brief NUS UUID. */
+static ble_uuid_t const m_nus_uuid =
+{
+    .uuid = BLE_UUID_NUS_SERVICE,
+    .type = NUS_SERVICE_UUID_TYPE
+};
+
+
+//static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07};  C
+static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB};  //P
+//static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC};  //SAMPLE
+//static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD};  //P  TEST Bad-Mac
+static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd};  //SAMPLE bad-mac
+
+
+extern char ScanHSBuff[];
+
+
+extern uint8_t       m_tx_buf[];           /**< TX buffer. */
+extern uint8_t       m_rx_buf[];    /**< RX buffer. */
+extern uint8_t m_length;        /**< Transfer length. */
+
+
+/* Flag to check fds initialization. */
+static bool volatile m_fds_initialized;
+/* Array to map FDS events to strings. */
+static char const * fds_evt_str[] =
+{
+    "FDS_EVT_INIT",
+    "FDS_EVT_WRITE",
+    "FDS_EVT_UPDATE",
+    "FDS_EVT_DEL_RECORD",
+    "FDS_EVT_DEL_FILE",
+    "FDS_EVT_GC",
+};
+
+
+/* Keep track of the progress of a delete_all operation. */
+static struct
+{
+    bool delete_next;   //!< Delete next record.
+    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
+} m_delete_all;
+
+
+
+ble_gap_addr_t old_ble_addr;
+ble_gap_addr_t new_ble_addr;
+
+
+
+static void fds_evt_handler(fds_evt_t const * p_evt)
+{
+    if (p_evt->result == NRF_SUCCESS)
+    {
+        NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
+                      fds_evt_str[p_evt->id]);
+    }
+    else
+    {
+        NRF_LOG_INFO("Event: %s received (%s)",
+                      fds_evt_str[p_evt->id],
+                      fds_err_str(p_evt->result));
+    }
+
+    switch (p_evt->id)
+    {
+        case FDS_EVT_INIT:
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                m_fds_initialized = true;
+            }
+            break;
+
+        case FDS_EVT_WRITE:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
+            }
+        } break;
+
+        case FDS_EVT_DEL_RECORD:
+        {
+            if (p_evt->result == NRF_SUCCESS)
+            {
+                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
+                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
+                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
+            }
+            m_delete_all.pending = false;
+        } break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief   Begin deleting all records, one by one. */
+void delete_all_begin(void)
+{
+    m_delete_all.delete_next = true;
+}
+
+
+/**@brief   Process a delete all command.
+ *
+ * Delete records, one by one, until no records are left.
+ */
+void delete_all_process(void)
+{
+    if (m_delete_all.delete_next  & !m_delete_all.pending)
+    {
+	    NRF_LOG_INFO("Deleting next record.");
+
+	    m_delete_all.delete_next = record_delete_next();
+
+	    if (!m_delete_all.delete_next)
+	    {
+	        NRF_LOG_INFO("No records left to delete.");
+	    }
+    }
+}
+
+
+
+/**
+ * @brief SPI user event handler.
+ * @param event
+ */
+void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
+                       void *                    p_context)
+{
+    spi_xfer_done = true;
+    NRF_LOG_INFO("Transfer completed.");
+    if (m_rx_buf[0] != 0)
+    {
+        NRF_LOG_INFO(" Received:");
+        NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
+    }
+}
+
+
+
+ 
+// 1ms tick  (1ms interrupt)
+// ALREADY_DONE_FOR_YOU: This is a timer event handler
+static void timer_timeout_handler(void * p_context)
+{
+    // Step 3.F, Update temperature and characteristic value.
+   static int32_t sensor_value = 0;
+   // sd_temp_get(&sensor_value);                                       // *modify where sensor measurement function goes
+   // our_sensor_characteristic_update(&m_our_service, &sensor_value);  // make a call to characteristic update function 
+   // nrf_gpio_pin_toggle(LED_4);     
+  //printf("%d\r\n", sensor_value++);
+   //SendData();
+
+  
+	gTimeCounter++;
+	SystemTimer.MS_1++;
+	SystemTimer.UART_LAST_RECV_TIMER++;
+	SystemTimer.SEND_TEST_TIMER++;
+	SystemTimer.LED_TOGGLE_TIMER++;
+	SystemTimer.TMR_CON_START++;
+	SystemTimer.PARK_KEEP_TIMER++;
+
+	SystemTimer.DEV_REG_TIMER++;
+	SystemTimer.SVR_SEND_TIMER++;
+
+	SystemManager.LedBlinkTimer--;
+
+	if(!(SystemTimer.MS_1 % 10)){
+		SystemTimer.MS_10_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 100)){
+		SystemTimer.MS_100_TICK = 1;
+	}
+
+	if(!(SystemTimer.MS_1 % 1000)){
+		SystemTimer.MS_1000_TICK = 1;
+	}
+
+
+	if( SystemTimer.TMR_CON_START == 10000 )
+	{
+		sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
+	}
+}
+
+
+
+/**@brief Function for starting timers.
+ */
+static void application_timers_start(void)
+{
+    /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
+       ret_code_t err_code;
+       err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
+       APP_ERROR_CHECK(err_code); */
+    app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
+}
+
+
+
+
+/**@brief Function for handling asserts in the SoftDevice.
+ *
+ * @details This function is called in case of an assert in the SoftDevice.
+ *
+ * @warning This handler is only an example and is not meant for the final product. You need to analyze
+ *          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(0xDEADBEEF, line_num, p_file_name);
+}
+
+
+/**@brief Function for handling the Nordic UART Service Client errors.
+ *
+ * @param[in]   nrf_error   Error code containing information about what went wrong.
+ */
+static void nus_error_handler(uint32_t nrf_error)
+{
+    APP_ERROR_HANDLER(nrf_error);
+}
+
+
+/**@brief Function to start scanning. */
+static void scan_start(void)
+{
+    ret_code_t ret;
+
+    ret = nrf_ble_scan_start(&m_scan);
+    APP_ERROR_CHECK(ret);
+
+    ret = bsp_indication_set(BSP_INDICATE_SCANNING);
+    APP_ERROR_CHECK(ret);
+}
+
+
+/**@brief Function for handling Scanning Module events.
+ */
+static void scan_evt_handler(scan_evt_t const * p_scan_evt)
+{
+    ret_code_t err_code;
+
+    switch(p_scan_evt->scan_evt_id)
+    {
+         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
+         {
+              err_code = p_scan_evt->params.connecting_err.err_code;
+              APP_ERROR_CHECK(err_code);
+         } break;
+
+         case NRF_BLE_SCAN_EVT_CONNECTED:
+         {
+              ble_gap_evt_connected_t const * p_connected =
+                               p_scan_evt->params.connected.p_connected;
+             // Scan is automatically stopped by the connection.
+             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
+                      p_connected->peer_addr.addr[0],
+                      p_connected->peer_addr.addr[1],
+                      p_connected->peer_addr.addr[2],
+                      p_connected->peer_addr.addr[3],
+                      p_connected->peer_addr.addr[4],
+                      p_connected->peer_addr.addr[5]
+                      );
+         } break;
+
+         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
+         {
+             NRF_LOG_INFO("Scan timed out.");
+             scan_start();
+         } break;
+
+         default:
+             break;
+    }
+}
+
+
+/**@brief Function for initializing the scanning and setting the filters.
+ */
+static void scan_init(void)
+{
+    ret_code_t          err_code;
+    nrf_ble_scan_init_t init_scan;
+
+    memset(&init_scan, 0, sizeof(init_scan));
+
+    init_scan.connect_if_match = true;
+    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
+
+    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
+    APP_ERROR_CHECK(err_code);
+
+
+#if 0
+        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
+    APP_ERROR_CHECK(err_code);
+
+     err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+
+
+#if 1
+    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
+    APP_ERROR_CHECK(err_code);
+#endif
+}
+
+
+
+/**@brief Function for handling database discovery events.
+ *
+ * @details This function is a callback function to handle events from the database discovery module.
+ *          Depending on the UUIDs that are discovered, this function forwards the events
+ *          to their respective services.
+ *
+ * @param[in] p_event  Pointer to the database discovery event.
+ */
+static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
+{
+    ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
+}
+
+
+/**@brief Function for handling characters received by the Nordic UART Service (NUS).
+ *
+ * @details This function takes a list of characters of length data_len and prints the characters out on UART.
+ *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
+ */
+static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
+{
+    ret_code_t ret_val;
+
+    NRF_LOG_DEBUG("Receiving data.");
+    NRF_LOG_INFO("Receiving data.");
+	NRF_LOG_RAW_INFO("Receiving data.");
+    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
+
+    for (uint32_t i = 0; i < data_len; i++)
+    {
+        do
+        {
+            ret_val = app_uart_put(p_data[i]);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+    if (p_data[data_len-1] == '\r')
+    {
+        while (app_uart_put('\n') == NRF_ERROR_BUSY);
+    }
+    if (ECHOBACK_BLE_UART_DATA)
+    {
+        // Send data back to the peripheral.
+        do
+        {
+            ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
+            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
+            {
+                NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
+                APP_ERROR_CHECK(ret_val);
+            }
+        } while (ret_val == NRF_ERROR_BUSY);
+    }
+}
+
+
+
+void uart_event_handle(app_uart_evt_t * p_event)
+{
+    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
+    static uint16_t index = 0;
+    uint32_t ret_val;
+
+    switch (p_event->evt_type)
+    {
+        /**@snippet [Handling data from UART] */
+        case APP_UART_DATA_READY:
+
+         // SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	        USART_Handler();
+
+		break;
+
+		case APP_UART_DATA:
+		
+			NRF_LOG_INFO("APP_UART_DATA");
+		
+		break;
+
+		
+
+        /**@snippet [Handling data from UART] */
+        case APP_UART_COMMUNICATION_ERROR:
+            NRF_LOG_ERROR("Communication error occurred while handling UART.");
+            APP_ERROR_HANDLER(p_event->data.error_communication);
+            break;
+
+        case APP_UART_FIFO_ERROR:
+            NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
+            APP_ERROR_HANDLER(p_event->data.error_code);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Callback handling Nordic UART Service (NUS) client events.
+ *
+ * @details This function is called to notify the application of NUS client events.
+ *
+ * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
+ * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
+ */
+
+/**@snippet [Handling events from the ble_nus_c module] */
+//char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
+
+static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
+{
+    ret_code_t err_code;
+    int i;
+
+    switch (p_ble_nus_evt->evt_type)
+    {
+
+
+        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:		// Connecting 
+        
+			SystemManager.SecondData = 0;
+
+            NRF_LOG_INFO("Discovery complete.");
+
+            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
+            APP_ERROR_CHECK(err_code);
+			
+            NRF_LOG_INFO("Connected to device with Nordic UART Service.");
+
+			switch(SystemManager.Encryption_Mode){
+				case AES_ENC_CAR:
+					CarEncryptEcb( AES_ENC_CAR );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_EMG:
+					CarEncryptEcb( AES_ENC_EMG );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+				break;
+
+				case AES_ENC_PCA:
+					CarEncryptEcb( AES_ENC_PCA );
+					ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);	// PCAXX 전송
+				break;
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_NUS_TX_EVT:			// BLE NUS Data Rx
+        
+            //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
+            //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
+
+#if 0
+			for( i=0; i<p_ble_nus_evt->data_len; i++)
+            {
+              //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
+            }
+#endif
+
+			NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
+
+
+			if(SystemManager.SecondData == 0){
+
+
+				switch(p_ble_nus_evt->p_data[0]){
+
+					case 0x74:		// 무선 비상벨 신호
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
+
+						NRF_LOG_RAW_INFO("WES ");
+
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+
+						memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
+
+						switch(p_ble_nus_evt->p_data[12]){
+
+							// 비상벨 버튼 동작시
+							case DEV_NUS_EMG: 
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Emergency");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								
+
+
+								switch(SystemManager.System_State){
+									
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:	// 등록 모드일 경우 
+										
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{
+
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+										
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+										
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+
+											err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+											APP_ERROR_CHECK(err_code);
+
+										}
+
+									break;
+									
+									case SYSTEM_NONE:
+										SystemManager.LedBlinkRun = 1;
+										SystemManager.LedBlinkTimer = 5000;
+										SystemTimer.LED_TOGGLE_TIMER = 0;
+										SystemManager.DevType = 0;
+								
+										SendEmergency();
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);									
+									break;
+								}
+
+								SystemManager.DevType = 0;
+
+							break;
+
+								// 테스트 버튼 동작시 
+							case DEV_NUS_TEST:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  TEST");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								switch(SystemManager.System_State){
+									case SYSTEM_EMERGENCY_SIREN:
+									case SYSTEM_SERVER_COMM:	
+									case SYSTEM_SERVER_COMM_REQ:										
+
+									break;
+
+									case SYSTEM_REGISTER:
+										if( FindRegMac(ScanHSBuff) == 1 )
+										{								
+											SystemManager.RegRequst = 0;
+											SystemManager.LedBlinkRun = 0;
+											
+											SystemManager.System_State = SYSTEM_NONE;
+
+											ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+
+											NRF_LOG_INFO("Device Registration Disable");
+
+											SystemManager.SwitchOn = 0;
+											PKBuzzerOff();
+											PKLedOff();
+										}
+
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+
+									break;
+
+									case SYSTEM_NONE:
+										AliveTest();	
+										
+										err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+										APP_ERROR_CHECK(err_code);
+									break;
+								}
+
+								SystemManager.DevType = 0;
+							break;
+
+								// 등록버튼 동작시
+							case DEV_NUS_REG:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Device Registration");
+													
+								SystemTimer.DEV_REG_TIMER = 0;
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+
+								if(SystemManager.RegRequst)		// 현재 등록모드일 경우 
+								{
+									SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
+
+									SystemManager.LedBlinkTimer = 2000;
+									SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+									for( i=0; i<6; i++)
+									{
+										NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
+									}
+
+									NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
+									NRF_LOG_RAW_INFO("\n");
+
+									SaveRegMac(SystemManager.PtrPeerAddrStr);
+
+									ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
+									NRF_LOG_INFO("Send WESACK");
+
+									SendCurrentRegDev();
+								
+								}else{
+									;					
+								}
+								SystemManager.DevType = 0;
+							break;
+
+								// Alive 동작시 
+							case DEV_NUS_ALIVE:
+								
+								NRF_LOG_INFO("TRANSFER SWITCH ---  Alive");
+
+								SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
+
+								SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
+								SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
+
+								SendAlive();
+
+								err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+								APP_ERROR_CHECK(err_code);
+
+								SystemManager.DevType = 0;
+						    break;
+						}
+					break;
+
+					case 0x73:	// 밴드 주차 
+
+						NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x73;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+
+					break;
+
+					case 0x72:		// 밴드 비상 
+					
+						NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x72;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+						
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];						
+					break;
+
+					case 0x75:		// 신규 원패스앱 
+					
+						NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
+
+						SystemManager.SecondData = 1;
+						SystemManager.BandType = 0x75;
+						
+						memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+						CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
+
+						NRF_LOG_RAW_INFO("Nus First Data ==>");
+						
+						for( i=0; i<16; i++)
+						{
+							NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+						}
+						NRF_LOG_RAW_INFO("\n");
+
+						SystemManager.Site[0] = SystemManager.AesEncData[4];
+						SystemManager.Site[1] = SystemManager.AesEncData[5];
+						SystemManager.Site[2] = SystemManager.AesEncData[6];
+						SystemManager.Site[3] = SystemManager.AesEncData[7];
+
+						SystemManager.Dong[0] = SystemManager.AesEncData[8];
+						SystemManager.Dong[1] = SystemManager.AesEncData[9];
+
+						SystemManager.Ho[0] = SystemManager.AesEncData[10];
+						SystemManager.Ho[1] = SystemManager.AesEncData[11];
+
+						SystemManager.Key_Num = SystemManager.AesEncData[12];
+						SystemManager.Key_Type = SystemManager.AesEncData[13];
+
+						SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
+						SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
+					break;
+					
+				}
+			}else if( SystemManager.SecondData == 1 ){		//  두번째 Nus Packet
+
+				SystemManager.SecondData = 0;
+
+//					for( i=0; i<p_ble_nus_evt->data_len; i++)
+//					{
+//						NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
+//					}
+
+				memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
+
+#if 0
+				NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
+				for( i=0; i<p_ble_nus_evt->data_len; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+#endif
+
+				CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
+
+				NRF_LOG_RAW_INFO("Nus Secound Data ===>");
+
+				for( i=0; i<16; i++)
+				{
+					NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+
+				
+				switch(SystemManager.BandType){
+					
+					case 0x73:		// BAND PARKING
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+							SendParkingBand();
+
+							// jakuja	disconnect
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+						}
+					break;
+
+					case 0x72:		// BAND EMG
+	
+						if( SystemManager.ServerCon == 0)
+						{
+							CarEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							switch(SystemManager.System_State){
+								case SYSTEM_NONE:
+									SendEmergencyBand();
+								break;
+
+
+								case SYSTEM_REGISTER:
+								case SYSTEM_EMERGENCY_SIREN:
+								case SYSTEM_SERVER_COMM:
+								case SYSTEM_SERVER_COMM_REQ:
+
+								break;
+							}
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							SystemManager.Encryption_Mode = AES_ENC_NONE;
+
+						}
+					break;
+
+					case 0x75:		// New iOS App
+					
+						if( SystemManager.ServerCon == 0)
+						{
+
+							PcaEncryptEcbACK(SystemManager.BandType);
+							ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
+
+							SystemManager.DevType = 0;
+
+							SendParkingApp();
+
+							err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+							APP_ERROR_CHECK(err_code);
+
+							NRF_LOG_RAW_INFO("======== Send CARACK\n");
+						}
+					break;
+					
+				}
+			}
+		break;
+
+
+        case BLE_NUS_C_EVT_DISCONNECTED:
+            NRF_LOG_INFO("Disconnected --------------------\n");
+            scan_start();
+		break;
+
+    }
+}
+/**@snippet [Handling events from the ble_nus_c module] */
+
+
+/**
+ * @brief Function for handling shutdown events.
+ *
+ * @param[in]   event       Shutdown type.
+ */
+static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
+{
+    ret_code_t err_code;
+
+    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
+    APP_ERROR_CHECK(err_code);
+
+    switch (event)
+    {
+        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
+            // Prepare wakeup buttons.
+            err_code = bsp_btn_ble_sleep_mode_prepare();
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        default:
+            break;
+    }
+
+    return true;
+}
+
+NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
+
+
+/**@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)
+{
+
+    int i;
+    ret_code_t            err_code;
+    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_ADV_REPORT :
+            //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
+ 
+            //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
+   
+            break;
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+
+            NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
+
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
+            err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
+            APP_ERROR_CHECK(err_code);
+
+            // start discovery of services. The NUS Client waits for a discovery result
+            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+
+            NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
+                         p_gap_evt->conn_handle,
+                         p_gap_evt->params.disconnected.reason);
+
+
+#if 0
+			if( SystemManager.DevType == DEV_IOS_PARK &&  p_gap_evt->params.disconnected.reason != 0x16 )
+			{
+				NVIC_SystemReset();
+				//nrf_delay_ms(100);
+				
+				//UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			}
+#endif			 
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
+            {
+                NRF_LOG_INFO("Connection Request timed out.");
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            // Pairing not supported.
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            // Accepting parameters requested by peer.
+            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
+                                                    &p_gap_evt->params.conn_param_update_request.conn_params);
+            APP_ERROR_CHECK(err_code);
+            break;
+
+        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;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+            // Disconnect on GATT Client timeout event.
+            NRF_LOG_DEBUG("GATT Client Timeout.");
+            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.
+            NRF_LOG_DEBUG("GATT Server Timeout.");
+            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;
+
+        default:
+            break;
+    }
+}
+
+
+/**@brief Function for initializing the BLE stack.
+ *
+ * @details 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 (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
+    {
+        NRF_LOG_INFO("ATT MTU exchange completed.");
+
+        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
+        //m_ble_nus_max_data_len = 244;
+        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
+    }
+}
+
+
+/**@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_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling events from the BSP module.
+ *
+ * @param[in] event  Event generated by button press.
+ */
+void bsp_event_handler(bsp_event_t event)
+{
+    ret_code_t err_code;
+
+    switch (event)
+    {
+        case BSP_EVENT_SLEEP:
+            nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
+            break;
+
+        case BSP_EVENT_DISCONNECT:
+            err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
+                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
+            if (err_code != NRF_ERROR_INVALID_STATE)
+            {
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+
+        default:
+            break;
+    }
+}
+
+/**@brief Function for initializing the UART. */
+static void uart_init(void)
+{
+    ret_code_t err_code;
+
+    app_uart_comm_params_t const comm_params =
+    {
+        .rx_pin_no    = RX_PIN_NUMBER,
+        .tx_pin_no    = TX_PIN_NUMBER,
+        .rts_pin_no   = RTS_PIN_NUMBER,
+        .cts_pin_no   = CTS_PIN_NUMBER,
+        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
+        .use_parity   = false,
+        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud9600
+    };
+
+    APP_UART_FIFO_INIT(&comm_params,
+                       UART_RX_BUF_SIZE,
+                       UART_TX_BUF_SIZE,
+                       uart_event_handle,
+                       APP_IRQ_PRIORITY_LOWEST,
+                       err_code);
+
+    APP_ERROR_CHECK(err_code);
+}
+
+/**@brief Function for initializing the Nordic UART Service (NUS) client. */
+static void nus_c_init(void)
+{
+    ret_code_t       err_code;
+    ble_nus_c_init_t init;
+
+    init.evt_handler   = ble_nus_c_evt_handler;
+    init.error_handler = nus_error_handler;
+    init.p_gatt_queue  = &m_ble_gatt_queue;
+
+    err_code = ble_nus_c_init(&m_ble_nus_c, &init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing buttons and leds. */
+static void buttons_leds_init(void)
+{
+    ret_code_t err_code;
+    bsp_event_t startup_event;
+
+    err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = bsp_btn_ble_init(NULL, &startup_event);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for initializing the timer. */
+static void timer_init(void)
+{
+    ret_code_t err_code = app_timer_init();
+    APP_ERROR_CHECK(err_code);
+
+
+     app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
+
+}
+
+
+/**@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 initializing power management.
+ */
+static void power_management_init(void)
+{
+    ret_code_t err_code;
+    err_code = nrf_pwr_mgmt_init();
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/** @brief Function for initializing the database discovery module. */
+static void db_discovery_init(void)
+{
+    ble_db_discovery_init_t db_init;
+
+    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
+
+    db_init.evt_handler  = db_disc_handler;
+    db_init.p_gatt_queue = &m_ble_gatt_queue;
+
+    ret_code_t err_code = ble_db_discovery_init(&db_init);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+/**@brief Function for handling the idle state (main loop).
+ *
+ * @details Handles any pending log operations, then sleeps until the next event occurs.
+ */
+static void idle_state_handle(void)
+{
+    if (NRF_LOG_PROCESS() == false)
+    {
+        nrf_pwr_mgmt_run();
+    }
+}
+
+
+
+/**@brief Function for handling events from the button handler module.
+ *
+ * @param[in] pin_no        The pin that the event applies to.
+ * @param[in] button_action The button action (press/release).
+ */
+static void button_event_handler(uint8_t pin_no, uint8_t button_action)
+{
+    ret_code_t err_code;
+
+    uint32_t gpSts;
+
+    switch (pin_no)
+    {
+        case LEDBUTTON_BUTTON:
+            NRF_LOG_INFO("Send button data");
+            
+            gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
+            NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
+
+            if(gpSts == 0)   // BTN_PRESSED=0
+            {
+                nrf_gpio_pin_clear(LED_1);
+                NRF_LOG_INFO("PRESSED\r\n");
+
+                SystemManager.SwitchOn = 1;
+                SendEmergencyLocal();
+                  
+            }else{
+              nrf_gpio_pin_set(LED_1);
+              NRF_LOG_INFO("Released\r\n");
+                
+            }
+		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[] =
+    {
+        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
+    };
+
+    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
+                               BUTTON_DETECTION_DELAY);
+    APP_ERROR_CHECK(err_code);
+}
+
+
+
+
+static void GPOut_Init()
+{
+
+
+    uint32_t i;
+    for (i = 0; i < 4; ++i)
+    {
+        nrf_gpio_cfg_output(m_board_led_list[i]);
+    }
+  
+
+
+}
+
+
+void ble_get_mac(uint8_t addr[8])
+{
+  uint32_t err_code;
+  ble_gap_addr_t ble_addr;
+
+  err_code = sd_ble_gap_address_get(&ble_addr);
+  APP_ERROR_CHECK(err_code);
+
+  IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
+}
+
+
+
+
+void _1000ms_timer_handle()
+{
+
+//	NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
+
+
+	switch(SystemManager.System_State){
+
+		case SYSTEM_NONE:
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;		
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+		break;
+
+
+		case SYSTEM_EMERGENCY_SIREN:
+			
+			SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
+			
+			if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
+
+				SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+				PKBuzzerOff();
+				SystemManager.LedBlinkRun = 0;			
+
+				SystemManager.Emg_Ack_Flag = 0;
+				
+			}
+
+			if(SystemManager.Emg_Ack_Flag){
+
+				SystemManager.Emg_Resend_Cnt++;
+
+				if(SystemManager.Emg_Resend_Cnt >= 10){
+
+					SystemManager.Emg_Resend_Cnt = 0;
+
+					ReSendEmergency();
+				}
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM:
+
+			SystemTimer.SYSTEM_SERVER_COMM_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
+
+				SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+				
+				PKLedOff();
+
+				PKMicOff();
+				PKSpeakerOff();
+				
+				SystemManager.LedBlinkRun = 0;			
+			}
+		break;
+
+
+		case SYSTEM_REGISTER:
+			
+			SystemTimer.SYSTEM_REGISTER_CNT++;
+
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
+
+
+			if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
+
+				SystemTimer.SYSTEM_REGISTER_CNT = 0;
+
+				SystemManager.RegRequst = 0;
+
+				SystemManager.System_State = SYSTEM_NONE;
+
+				PKLedOff();
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		case SYSTEM_SERVER_COMM_REQ:
+
+			SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
+			
+			NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
+			
+			if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
+			
+				SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
+			
+				SystemManager.RegRequst = 0;
+			
+				SystemManager.System_State = SYSTEM_NONE;
+			
+				PKLedOff();
+				PKBuzzerOff();
+				
+				SystemManager.LedBlinkRun = 0;
+			}
+		break;
+
+		
+	}
+}
+
+
+
+
+
+
+int main(void)
+{
+
+ 
+	uint8_t i; 
+	ret_code_t err_code;
+	ble_gap_addr_t dd;
+	dd.addr_id_peer = 0;
+	dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
+
+    // Initialize.
+    log_init();
+
+    /* Register first to receive an event when initialization is complete. */
+    (void) fds_register(fds_evt_handler);
+
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+	NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 0.93  2022/03/20\n"); 
+	NRF_LOG_RAW_INFO("\n===========================================================\n\n");
+
+//    NRF_LOG_RAW_INFO("Initializing fds...\n");
+
+    err_code = fds_init();
+    APP_ERROR_CHECK(err_code);
+    timer_init();
+    uart_init();
+    buttons_init();
+    GPOut_Init();     
+    db_discovery_init();
+
+    power_management_init();
+
+	//sd_ble_gap_addr_get(&old_ble_addr);
+
+    ble_stack_init();
+	sd_ble_gap_addr_get(&old_ble_addr);
+
+	dd.addr[0] = IES200_1ST_MAC;
+	dd.addr[1] = IES200_2ST_MAC;
+	dd.addr[2] = IES200_3ST_MAC;
+	dd.addr[3] = old_ble_addr.addr[3];
+	dd.addr[4] = old_ble_addr.addr[4];
+	dd.addr[5] = old_ble_addr.addr[5];
+    sd_ble_gap_addr_set(&dd);
+
+	sd_ble_gap_addr_get(&new_ble_addr);
+	 
+    gatt_init();
+    nus_c_init();
+    scan_init();
+	
+	for(i=0; i<3; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+    // Start execution.
+    //printf("BLE UART central example started.=====\r\n");
+    NRF_LOG_INFO("BLE UART central example started.");
+    scan_start();
+
+    application_timers_start();
+
+	// Enabling the buttons.										
+    err_code = app_button_enable();
+    APP_ERROR_CHECK(err_code);
+
+	PKLedOff();
+
+    //FlashTest();
+
+	LoadRegMac();
+
+	//delete_all_begin();
+
+	Server_Answer_Version();
+
+	nrf_delay_ms(1000);
+	
+	Server_Answer_Version();
+
+	while(1)
+    {
+        idle_state_handle();
+        USART_DataCheck();
+        ParseEventServer();   
+        LedToggle();  
+		delete_all_process();
+
+		if(SystemTimer.MS_1000_TICK){
+
+			SystemTimer.MS_1000_TICK = 0;
+
+			_1000ms_timer_handle();
+		}
+    }
+}
+

+ 1814 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(1154).c

@@ -0,0 +1,1814 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+     ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+
+			
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+		}
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+
+
+
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+  int len, validLen;
+  char* pData;
+  int i;
+  int j;
+  int v=0;
+  int result;
+
+
+  pData = data;
+  validLen = dataLen;
+
+#if 1
+  if( flag )
+  {
+      // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+      while(1)
+      {
+
+          result = HS_AdParser(pData);
+         // if( result == 0 )
+         //     break;
+
+          len = *pData;
+          validLen -= len+1;
+
+          //printf("len:%d  validLen:%d\n", len, validLen);
+          if( validLen <= 0 )
+            break;
+
+          pData += len+1;
+
+      }
+     
+  }
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (¾Èµå·ÎÀ̵å)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+	}
+
+
+
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+	if( SystemManager.RegRequst == 1 )
+	{
+		//SystemManager.LedBlinkRun = 0;
+		//SystemManager.RegRequst = 0;
+
+		//goto SCAN_GOING; 
+	}
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER>6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+     // goto SCAN_GOING; 
+     goto BAND_CONNECT; 
+
+		
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{
+	
+		if( SystemManager.RegRequst == 1 )
+		{
+			//SystemManager.LedBlinkRun = 0;
+			//SystemManager.RegRequst = 0;
+	
+			//goto SCAN_GOING; 
+		}
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+
+	}
+	
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+  
+
+  if( ISCPacket == 1)
+  {
+    int i;
+
+    if( FindRegMac(ScanHSBuff) == 0 )
+    {
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+	  if( SystemManager.RegRequst==0 )
+      	return;
+    }
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else if( ISCPacket == 2)
+  {
+    int i;
+
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else{
+
+
+SCAN_GOING:
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+    return;  
+  }
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1828 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(1206).c

@@ -0,0 +1,1828 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+	ISCPacket = 0;
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+		}		
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+//			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+//			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+			{
+//				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			
+			for(i=0; i<13; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			  // ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			  // SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			ISCPacket = 5;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSWES\n");
+
+			if( SystemManager.RegRequst == 1 )	// 등록모드면 
+			{	
+				ISCPacket = 1;
+				SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<13; i++){
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}	
+			
+			SystemManager.BandMode = AES_ENC_WES;
+			
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+//			char* pData = data;
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   //ISCPacket = 1;
+			   //SystemManager.DevType = DEV_IOS_PARK;
+			}
+
+			ISCPacket = 2;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSPCA\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				ISCPacket = 5;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.BandMode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+
+	}else if( SystemManager.DevType == DEV_WES_ADV )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		ISCPacket = 1;
+
+	}else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		ISCPacket = 5;
+
+	}
+  
+
+
+
+	
+
+
+	
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto BAND_CONNECT; 
+		}
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1807 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(1597).c

@@ -0,0 +1,1807 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_Advertise_Parser(char* data)
+{
+    int len;
+    int j;
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_CAR;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				NRF_LOG_RAW_INFO("ICSCAR -- Connect Request\n");
+
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}else{
+				NRF_LOG_RAW_INFO("ICSCAR - ADV\n");
+			}
+        }
+		// BAND EMG
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				NRF_LOG_RAW_INFO("==> ICSEMG -- Connect Request\n");
+				
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}else{
+				NRF_LOG_RAW_INFO("ICSEMG - ADV\n");
+			}
+        }
+		// BAND	SCAN
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+		}
+		// 무선 비상벨 
+        else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			NRF_LOG_RAW_INFO("ICSWES\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }	
+		// New ioS PARKING
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_PCA;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				NRF_LOG_RAW_INFO("ICSPCA -- Connect Request\n");
+
+				SystemManager.DevType = DEV_NEW_IOS_PARK;
+				ISCPacket = 5;
+			}else{
+				NRF_LOG_RAW_INFO("ICSPCA -- ADV\n");	
+			}
+		}
+
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+    }
+
+    return 0;
+}
+
+void HS_AdvertisePacket_Parser(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_Advertise_Parser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja  수신데이타 DBG 확인
+
+	// 알수없는 장치 Filtering
+	if(p_adv_report->data.p_data[0] == 0x1E && p_adv_report->data.p_data[1] == 0xFF){
+		goto SCAN_GOING;
+	}
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+		goto SCAN_GOING;
+	}else{
+		//NRF_LOG_RAW_INFO("NOT Android APP PARKING\n");
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+		goto SCAN_GOING;
+	}else{
+
+		//NRF_LOG_RAW_INFO("NOT iOS APP PARKING\n");
+	}
+
+
+	HS_AdvertisePacket_Parser(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+	else if (SystemManager.DevType == DEV_NEW_IOS_PARK )
+	{
+
+
+	}
+
+
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1975 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(1684).c

@@ -0,0 +1,1975 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+
+#if 0
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+	ISCPacket = 0;
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+		}		
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+//			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+//			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+			{
+//				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			
+			for(i=0; i<13; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			  // ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			  // SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			ISCPacket = 5;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSWES\n");
+
+			if( SystemManager.RegRequst == 1 )	// 등록모드면 
+			{	
+				ISCPacket = 1;
+				SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<13; i++){
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}	
+			
+			SystemManager.BandMode = AES_ENC_WES;
+			
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+//			char* pData = data;
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   //ISCPacket = 1;
+			   //SystemManager.DevType = DEV_IOS_PARK;
+			}
+
+			ISCPacket = 2;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSPCA\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				ISCPacket = 5;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.BandMode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+}
+
+#else
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+		char* pData = data;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		
+#if 0	// jakuja
+			for(i=0; i<len; i++)
+				NRF_LOG_RAW_INFO("%02X, ", data[i]);
+		
+			NRF_LOG_RAW_INFO("\n");
+#endif
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+               
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> DEV_IOS_PARK\n");
+				ISCPacket = 5;
+			}					
+
+			SystemManager.BandMode = AES_ENC_PCA;
+
+
+//			if( SystemManager.LedBlinkTimer < 0 )
+//			{
+//			   ISCPacket = 1;
+//			   //SystemTimer.TMR_CON_START = 0; 
+//			   SystemManager.DevType = DEV_IOS_PARK;
+//			}
+		}
+
+    }
+
+    return 0;
+}
+
+
+
+
+#endif
+
+
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx, ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+//	NRF_LOG_RAW_INFO("m_nrf_sdh_continue : %d, m_nrf_sdh_enabled : %d ", m_nrf_sdh_continue, m_nrf_sdh_enabled);
+
+//	nrf_sdh_disable_request();
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+
+	}else if( SystemManager.DevType == DEV_WES_ADV )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		ISCPacket = 1;
+
+	}else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+	
+		for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+		{
+			
+			NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+	
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;
+
+
+		 // goto SCAN_GOING; 
+		 goto BAND_CONNECT; 
+
+	}
+  	
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto BAND_CONNECT; 
+		}
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+
+	if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+		if( memcmp( SystemManager.TmpPtr, p_adv_report->peer_addr, 6) != 0 )
+		{
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			return;  
+		}	
+	}
+
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("<------------------- BLE_GAP_EVT_DISCONNECTED ------------------->\n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_TIMEOUT \n" );
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1920 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(206).c

@@ -0,0 +1,1920 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+
+#if 0
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+	ISCPacket = 0;
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+		}		
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+//			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+//			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+			{
+//				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			
+			for(i=0; i<13; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			  // ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			  // SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			ISCPacket = 5;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSWES\n");
+
+			if( SystemManager.RegRequst == 1 )	// 등록모드면 
+			{	
+				ISCPacket = 1;
+				SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<13; i++){
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}	
+			
+			SystemManager.BandMode = AES_ENC_WES;
+			
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+//			char* pData = data;
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   //ISCPacket = 1;
+			   //SystemManager.DevType = DEV_IOS_PARK;
+			}
+
+			ISCPacket = 2;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSPCA\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				ISCPacket = 5;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.BandMode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+}
+
+#else
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_IOS_PARK;
+			}
+		}
+
+    }
+
+    return 0;
+}
+
+
+
+
+#endif
+
+
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx, ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+//	NRF_LOG_RAW_INFO("m_nrf_sdh_continue : %d, m_nrf_sdh_enabled : %d ", m_nrf_sdh_continue, m_nrf_sdh_enabled);
+
+//	nrf_sdh_disable_request();
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+
+	}else if( SystemManager.DevType == DEV_WES_ADV )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		ISCPacket = 1;
+
+	}else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		ISCPacket = 5;
+
+	}
+  	
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto BAND_CONNECT; 
+		}
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("<------------------- BLE_GAP_EVT_DISCONNECTED ------------------->\n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_TIMEOUT \n" );
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1962 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(2207).c

@@ -0,0 +1,1962 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+
+#if 0
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+	ISCPacket = 0;
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+		}		
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+//			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+//			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+			{
+//				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			
+			for(i=0; i<13; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			  // ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			  // SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			ISCPacket = 5;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSWES\n");
+
+			if( SystemManager.RegRequst == 1 )	// 등록모드면 
+			{	
+				ISCPacket = 1;
+				SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<13; i++){
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}	
+			
+			SystemManager.BandMode = AES_ENC_WES;
+			
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+//			char* pData = data;
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   //ISCPacket = 1;
+			   //SystemManager.DevType = DEV_IOS_PARK;
+			}
+
+			ISCPacket = 2;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSPCA\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				ISCPacket = 5;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.BandMode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+}
+
+#else
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+		char* pData = data;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		
+#if 0	// jakuja
+			for(i=0; i<len; i++)
+				NRF_LOG_RAW_INFO("%02X, ", data[i]);
+		
+			NRF_LOG_RAW_INFO("\n");
+#endif
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+               
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> DEV_IOS_PARK\n");
+				ISCPacket = 5;
+			}					
+
+			SystemManager.BandMode = AES_ENC_PCA;
+
+
+//			if( SystemManager.LedBlinkTimer < 0 )
+//			{
+//			   ISCPacket = 1;
+//			   //SystemTimer.TMR_CON_START = 0; 
+//			   SystemManager.DevType = DEV_IOS_PARK;
+//			}
+		}
+
+    }
+
+    return 0;
+}
+
+
+
+
+#endif
+
+
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx, ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+//	NRF_LOG_RAW_INFO("m_nrf_sdh_continue : %d, m_nrf_sdh_enabled : %d ", m_nrf_sdh_continue, m_nrf_sdh_enabled);
+
+//	nrf_sdh_disable_request();
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+
+	}else if( SystemManager.DevType == DEV_WES_ADV )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		ISCPacket = 1;
+
+	}else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+	
+		for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+		{
+			
+			NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+	
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;
+	
+		 // goto SCAN_GOING; 
+		 goto BAND_CONNECT; 
+
+	}
+  	
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto BAND_CONNECT; 
+		}
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("<------------------- BLE_GAP_EVT_DISCONNECTED ------------------->\n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_TIMEOUT \n" );
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1812 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(2457).c

@@ -0,0 +1,1812 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+     ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+
+			
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+		}
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+
+
+
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+  int len, validLen;
+  char* pData;
+  int i;
+  int j;
+  int v=0;
+  int result;
+
+
+  pData = data;
+  validLen = dataLen;
+
+#if 1
+  if( flag )
+  {
+      // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+      while(1)
+      {
+
+          result = HS_AdParser(pData);
+         // if( result == 0 )
+         //     break;
+
+          len = *pData;
+          validLen -= len+1;
+
+          //printf("len:%d  validLen:%d\n", len, validLen);
+          if( validLen <= 0 )
+            break;
+
+          pData += len+1;
+
+      }
+     
+  }
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+	AppParkingCheck(p_adv_report->data.p_data);
+
+
+#if 0
+	SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	for( i=0; i<6; i++)
+	{
+	
+	  //NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+	}
+	//NRF_LOG_RAW_INFO("\n");
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+	if( SystemManager.RegRequst == 1 )
+	{
+		//SystemManager.LedBlinkRun = 0;
+		//SystemManager.RegRequst = 0;
+
+		//goto SCAN_GOING; 
+	}
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER>6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+     // goto SCAN_GOING; 
+     goto BAND_CONNECT; 
+
+		
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{
+	
+		if( SystemManager.RegRequst == 1 )
+		{
+			//SystemManager.LedBlinkRun = 0;
+			//SystemManager.RegRequst = 0;
+	
+			//goto SCAN_GOING; 
+		}
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+
+	}
+	
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+  
+
+  if( ISCPacket == 1)
+  {
+    int i;
+
+    if( FindRegMac(ScanHSBuff) == 0 )
+    {
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+	  if( SystemManager.RegRequst==0 )
+      	return;
+    }
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else if( ISCPacket == 2)
+  {
+    int i;
+
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else{
+
+
+SCAN_GOING:
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+    return;  
+  }
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1973 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(2531).c

@@ -0,0 +1,1973 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+
+#if 0
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+	ISCPacket = 0;
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+		}		
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+//			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+//			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+			{
+//				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			
+			for(i=0; i<13; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			  // ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			  // SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			ISCPacket = 5;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSWES\n");
+
+			if( SystemManager.RegRequst == 1 )	// 등록모드면 
+			{	
+				ISCPacket = 1;
+				SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<13; i++){
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}	
+			
+			SystemManager.BandMode = AES_ENC_WES;
+			
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+//			char* pData = data;
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   //ISCPacket = 1;
+			   //SystemManager.DevType = DEV_IOS_PARK;
+			}
+
+			ISCPacket = 2;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSPCA\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				ISCPacket = 5;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.BandMode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+}
+
+#else
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+		char* pData = data;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		
+#if 0	// jakuja
+			for(i=0; i<len; i++)
+				NRF_LOG_RAW_INFO("%02X, ", data[i]);
+		
+			NRF_LOG_RAW_INFO("\n");
+#endif
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+               
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> DEV_IOS_PARK\n");
+				ISCPacket = 5;
+
+				SystemManager.LocalNameAddr[0] = new_ble_addr.addr[0];
+				SystemManager.LocalNameAddr[1] = new_ble_addr.addr[1];
+				SystemManager.LocalNameAddr[2] = new_ble_addr.addr[2];
+				SystemManager.LocalNameAddr[3] = new_ble_addr.addr[3];
+				SystemManager.LocalNameAddr[4] = new_ble_addr.addr[4];
+				SystemManager.LocalNameAddr[5] = new_ble_addr.addr[5];
+
+	  
+			}					
+
+			SystemManager.BandMode = AES_ENC_PCA;
+
+
+//			if( SystemManager.LedBlinkTimer < 0 )
+//			{
+//			   ISCPacket = 1;
+//			   //SystemTimer.TMR_CON_START = 0; 
+//			   SystemManager.DevType = DEV_IOS_PARK;
+//			}
+		}
+
+    }
+
+    return 0;
+}
+
+
+
+
+#endif
+
+
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx, ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+//	NRF_LOG_RAW_INFO("m_nrf_sdh_continue : %d, m_nrf_sdh_enabled : %d ", m_nrf_sdh_continue, m_nrf_sdh_enabled);
+
+//	nrf_sdh_disable_request();
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+
+	}else if( SystemManager.DevType == DEV_WES_ADV )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		ISCPacket = 1;
+
+	}else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+	
+		for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+		{
+			
+			NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+	
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;
+
+
+		 // goto SCAN_GOING; 
+		 goto BAND_CONNECT; 
+
+	}
+  	
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto BAND_CONNECT; 
+		}
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("<------------------- BLE_GAP_EVT_DISCONNECTED ------------------->\n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_TIMEOUT \n" );
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1939 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(2974).c

@@ -0,0 +1,1939 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include "nrf_sdh.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,        nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+
+#if 1
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer > 0 )
+			{
+				//NRF_LOG_RAW_INFO(" <<  Transfer Busy  >>\n");	
+
+				return 0;
+				
+			}else{
+				SystemManager.DevType = DEV_BAND_ADV;	
+			}
+		}
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			if( SystemManager.LedBlinkTimer > 0 )
+			{
+				NRF_LOG_RAW_INFO(" <<  Transfer Busy  >>\n");
+				
+				return 0;
+				
+			}else{
+
+				SystemManager.TmpPtr = data+7;
+
+				if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+				{
+					SystemManager.DevType = DEV_BAND_PARK;
+					SystemManager.Encryption_Mode = AES_ENC_CAR;
+				}
+				else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+				{
+					;
+				}
+			}
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			if( SystemManager.LedBlinkTimer < 0 ){
+
+				SystemManager.TmpPtr = data+7;
+
+				if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+				{
+					SystemManager.DevType = DEV_BAND_EMG;
+					SystemManager.Encryption_Mode = AES_ENC_EMG;
+				}
+				else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+				{
+					;
+				}
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			NRF_LOG_RAW_INFO("==> ICSWES : ");
+
+			for(i=0; i<len; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			SystemManager.DevType = DEV_WES_ADV;
+
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			NRF_LOG_RAW_INFO("==> ICSPCA : ");
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				NRF_LOG_RAW_INFO(" <<  Transfer Busy  >>\n");	
+				return 0;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.Encryption_Mode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+	
+}
+
+#else
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+#if 0	// jakuja
+			for(i=0; i<len; i++)
+				NRF_LOG_RAW_INFO("%02X, ", data[i]);
+		
+			NRF_LOG_RAW_INFO("\n");
+#endif
+
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+               
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> DEV_IOS_PARK\n");
+				ISCPacket = 5;
+
+				SystemManager.LocalNameAddr[0] = new_ble_addr.addr[0];
+				SystemManager.LocalNameAddr[1] = new_ble_addr.addr[1];
+				SystemManager.LocalNameAddr[2] = new_ble_addr.addr[2];
+				SystemManager.LocalNameAddr[3] = new_ble_addr.addr[3];
+				SystemManager.LocalNameAddr[4] = new_ble_addr.addr[4];
+				SystemManager.LocalNameAddr[5] = new_ble_addr.addr[5];
+			}					
+
+			SystemManager.BandMode = AES_ENC_PCA;
+
+		}
+
+    }
+
+    return 0;
+}
+
+
+
+
+#endif
+
+
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+	pData = data;
+	validLen = dataLen;
+
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+	  }
+	}
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx, ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+
+	uint32_t err_code;
+	
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+	SystemManager.DevType = DEV_NONE;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+	if( SystemTimer.SVR_SEND_TIMER < 1000 )
+		goto SCAN_GOING; 
+
+#if 0
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+
+	NRF_LOG_RAW_INFO("m_nrf_sdh_continue : %d, m_nrf_sdh_enabled : %d ", m_nrf_sdh_continue, m_nrf_sdh_enabled);
+#endif
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[5] == 0x31 && p_adv_report->data.p_data[6] == 0x01 && p_adv_report->data.p_data[7] == 0x02 && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck_Android(p_adv_report->data.p_data);
+
+		goto SCAN_GOING; 
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[3] == 0x02 && p_adv_report->data.p_data[4] == 0x0A && p_adv_report->data.p_data[5] == 0x0C && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 ){
+
+		//NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+
+		goto SCAN_GOING; 
+	}
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	memset(ScanHSBuff, 0x00, sizeof(ScanHSBuff));
+	
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+							                          p_adv_report->peer_addr.addr[1],
+							                          p_adv_report->peer_addr.addr[2],
+							                          p_adv_report->peer_addr.addr[3],
+							                          p_adv_report->peer_addr.addr[4],
+							                          p_adv_report->peer_addr.addr[5]);
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+  
+	SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+
+
+	if( SystemManager.DevType == DEV_BAND_ADV){
+
+		SystemManager.DevType = DEV_NONE;
+		goto SCAN_GOING; 
+
+	}
+	else if( SystemManager.DevType == DEV_BAND_PARK || SystemManager.DevType == DEV_BAND_EMG)
+	{
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 5000)
+		{
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+			SystemManager.DevType = DEV_NONE;
+
+#if 1
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+			}
+			NRF_LOG_RAW_INFO("\n");
+#endif
+		}
+
+	     goto GOTO_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_WES_ADV )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		SystemManager.DevType = DEV_NONE;
+
+
+		if( SystemManager.RegRequst == 1 )	// 등록모드면 
+		{	
+			NRF_LOG_RAW_INFO("Reciver Mode is Register\n");
+
+			SystemManager.Encryption_Mode = AES_ENC_WES;
+			
+			goto GOTO_CONNECT; 
+		}
+		
+		if( FindRegMac(ScanHSBuff) == 1 )	// MAC이 등록되어있지 않으면
+		{
+			goto GOTO_CONNECT; 
+
+		}else{
+			goto SCAN_GOING; 
+		}
+
+	}
+	else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+	
+		for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		 // goto SCAN_GOING; 
+		 goto GOTO_CONNECT; 
+	}
+  	
+
+#if 0
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+	}
+	else if( ISCPacket == 2)
+
+
+
+	if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto GOTO_CONNECT; 
+		}
+
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+
+#endif
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+
+		return;  
+	
+
+GOTO_CONNECT:
+
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("<------------------- BLE_GAP_EVT_DISCONNECTED ------------------->\n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_TIMEOUT \n" );
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1984 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(3374).c

@@ -0,0 +1,1984 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include "nrf_sdh.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+
+#if 0
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+	ISCPacket = 0;
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+		}		
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+//			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+//			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+			{
+//				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			
+			for(i=0; i<13; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			  // ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			  // SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			ISCPacket = 5;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSWES\n");
+
+			if( SystemManager.RegRequst == 1 )	// 등록모드면 
+			{	
+				ISCPacket = 1;
+				SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<13; i++){
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}	
+			
+			SystemManager.BandMode = AES_ENC_WES;
+			
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+//			char* pData = data;
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   //ISCPacket = 1;
+			   //SystemManager.DevType = DEV_IOS_PARK;
+			}
+
+			ISCPacket = 2;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSPCA\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				ISCPacket = 5;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.BandMode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+}
+
+#else
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+		char* pData = data;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		
+#if 0	// jakuja
+			for(i=0; i<len; i++)
+				NRF_LOG_RAW_INFO("%02X, ", data[i]);
+		
+			NRF_LOG_RAW_INFO("\n");
+#endif
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+               
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> DEV_IOS_PARK\n");
+				ISCPacket = 5;
+
+				SystemManager.LocalNameAddr[0] = new_ble_addr.addr[0];
+				SystemManager.LocalNameAddr[1] = new_ble_addr.addr[1];
+				SystemManager.LocalNameAddr[2] = new_ble_addr.addr[2];
+				SystemManager.LocalNameAddr[3] = new_ble_addr.addr[3];
+				SystemManager.LocalNameAddr[4] = new_ble_addr.addr[4];
+				SystemManager.LocalNameAddr[5] = new_ble_addr.addr[5];
+
+	  
+			}					
+
+			SystemManager.BandMode = AES_ENC_PCA;
+
+
+//			if( SystemManager.LedBlinkTimer < 0 )
+//			{
+//			   ISCPacket = 1;
+//			   //SystemTimer.TMR_CON_START = 0; 
+//			   SystemManager.DevType = DEV_IOS_PARK;
+//			}
+		}
+
+    }
+
+    return 0;
+}
+
+
+
+
+#endif
+
+
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx, ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+
+	uint32_t err_code;
+	
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+
+	if( SystemTimer.SVR_SEND_TIMER < 1500 )
+		goto SCAN_GOING; 
+
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+//	NRF_LOG_RAW_INFO("m_nrf_sdh_continue : %d, m_nrf_sdh_enabled : %d ", m_nrf_sdh_continue, m_nrf_sdh_enabled);
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[5] == 0x31 && p_adv_report->data.p_data[6] == 0x01 && p_adv_report->data.p_data[7] == 0x02 && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck_Android(p_adv_report->data.p_data);
+
+		goto SCAN_GOING; 
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[3] == 0x02 && p_adv_report->data.p_data[4] == 0x0A && p_adv_report->data.p_data[5] == 0x0C && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 ){
+
+		//NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+
+		goto SCAN_GOING; 
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+
+	}else if( SystemManager.DevType == DEV_WES_ADV )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		ISCPacket = 1;
+
+	}else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+	
+		for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+		{
+			
+			NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+	
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;
+
+
+		 // goto SCAN_GOING; 
+		 goto BAND_CONNECT; 
+
+	}
+  	
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto BAND_CONNECT; 
+		}
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("<------------------- BLE_GAP_EVT_DISCONNECTED ------------------->\n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_TIMEOUT \n" );
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1939 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(3645).c

@@ -0,0 +1,1939 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include "nrf_sdh.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,        nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+
+#if 1
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer > 0 )
+			{
+				//NRF_LOG_RAW_INFO(" <<  Transfer Busy  >>\n");	
+
+				return 0;
+				
+			}else{
+				SystemManager.DevType = DEV_BAND_ADV;	
+			}
+		}
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			if( SystemManager.LedBlinkTimer > 0 )
+			{
+				NRF_LOG_RAW_INFO(" <<  Transfer Busy  >>\n");
+				
+				return 0;
+				
+			}else{
+
+				SystemManager.TmpPtr = data+7;
+
+				if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+				{
+					SystemManager.DevType = DEV_BAND_PARK;
+					SystemManager.Encryption_Mode = AES_ENC_CAR;
+				}
+				else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+				{
+					;
+				}
+			}
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			if( SystemManager.LedBlinkTimer < 0 ){
+
+				SystemManager.TmpPtr = data+7;
+
+				if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+				{
+					SystemManager.DevType = DEV_BAND_EMG;
+					SystemManager.Encryption_Mode = AES_ENC_EMG;
+				}
+				else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+				{
+					;
+				}
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			NRF_LOG_RAW_INFO("==> ICSWES : ");
+
+			for(i=0; i<len; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			SystemManager.DevType = DEV_WES_ADV;
+
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			NRF_LOG_RAW_INFO("==> ICSPCA : ");
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				NRF_LOG_RAW_INFO(" <<  Transfer Busy  >>\n");	
+				return 0;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.Encryption_Mode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+	
+}
+
+#else
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+#if 0	// jakuja
+			for(i=0; i<len; i++)
+				NRF_LOG_RAW_INFO("%02X, ", data[i]);
+		
+			NRF_LOG_RAW_INFO("\n");
+#endif
+
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+               
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> DEV_IOS_PARK\n");
+				ISCPacket = 5;
+
+				SystemManager.LocalNameAddr[0] = new_ble_addr.addr[0];
+				SystemManager.LocalNameAddr[1] = new_ble_addr.addr[1];
+				SystemManager.LocalNameAddr[2] = new_ble_addr.addr[2];
+				SystemManager.LocalNameAddr[3] = new_ble_addr.addr[3];
+				SystemManager.LocalNameAddr[4] = new_ble_addr.addr[4];
+				SystemManager.LocalNameAddr[5] = new_ble_addr.addr[5];
+			}					
+
+			SystemManager.BandMode = AES_ENC_PCA;
+
+		}
+
+    }
+
+    return 0;
+}
+
+
+
+
+#endif
+
+
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+	pData = data;
+	validLen = dataLen;
+
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+	  }
+	}
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx, ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+
+	uint32_t err_code;
+	
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+	SystemManager.DevType = DEV_NONE;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+	if( SystemTimer.SVR_SEND_TIMER < 1000 )
+		goto SCAN_GOING; 
+
+#if 0
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+
+//	NRF_LOG_RAW_INFO("m_nrf_sdh_continue : %d, m_nrf_sdh_enabled : %d ", m_nrf_sdh_continue, m_nrf_sdh_enabled);
+#endif
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[5] == 0x31 && p_adv_report->data.p_data[6] == 0x01 && p_adv_report->data.p_data[7] == 0x02 && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck_Android(p_adv_report->data.p_data);
+
+		goto SCAN_GOING; 
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[3] == 0x02 && p_adv_report->data.p_data[4] == 0x0A && p_adv_report->data.p_data[5] == 0x0C && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 ){
+
+		//NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+
+		goto SCAN_GOING; 
+	}
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	memset(ScanHSBuff, 0x00, sizeof(ScanHSBuff));
+	
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+							                          p_adv_report->peer_addr.addr[1],
+							                          p_adv_report->peer_addr.addr[2],
+							                          p_adv_report->peer_addr.addr[3],
+							                          p_adv_report->peer_addr.addr[4],
+							                          p_adv_report->peer_addr.addr[5]);
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+  
+	SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+
+
+	if( SystemManager.DevType == DEV_BAND_ADV){
+
+		SystemManager.DevType = DEV_NONE;
+		goto SCAN_GOING; 
+
+	}
+	else if( SystemManager.DevType == DEV_BAND_PARK || SystemManager.DevType == DEV_BAND_EMG)
+	{
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 5000)
+		{
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+			SystemManager.DevType = DEV_NONE;
+
+#if 1
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+			}
+			NRF_LOG_RAW_INFO("\n");
+#endif
+		}
+
+	     goto GOTO_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_WES_ADV )
+	{	
+	
+//		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		SystemManager.DevType = DEV_NONE;
+
+
+		if( SystemManager.RegRequst == 1 )	// 등록모드면 
+		{	
+			NRF_LOG_RAW_INFO("Reciver Mode is Register\n");
+
+			SystemManager.Encryption_Mode = AES_ENC_WES;
+			
+			goto GOTO_CONNECT; 
+		}
+		
+		if( FindRegMac(ScanHSBuff) == 1 )	// MAC이 등록되어있지 않으면
+		{
+			goto GOTO_CONNECT; 
+
+		}else{
+			goto SCAN_GOING; 
+		}
+
+	}
+	else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+	
+		for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		 // goto SCAN_GOING; 
+		 goto GOTO_CONNECT; 
+	}
+  	
+
+#if 0
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+	}
+	else if( ISCPacket == 2)
+
+
+
+	if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto GOTO_CONNECT; 
+		}
+
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+
+#endif
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+
+		return;  
+	
+
+GOTO_CONNECT:
+
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("<------------------- BLE_GAP_EVT_DISCONNECTED ------------------->\n" );
+            break;
+#if 1
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_TIMEOUT \n" );
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1806 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(394).c

@@ -0,0 +1,1806 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_IOS_PARK;
+			}
+		}
+
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (¾Èµå·ÎÀ̵å)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+	if( SystemManager.RegRequst == 1 )
+	{
+		//SystemManager.LedBlinkRun = 0;
+		//SystemManager.RegRequst = 0;
+
+		//goto SCAN_GOING; 
+	}
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+		if( SystemManager.RegRequst == 1 )
+		{
+			//SystemManager.LedBlinkRun = 0;
+			//SystemManager.RegRequst = 0;
+	
+			//goto SCAN_GOING; 
+		}
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+  
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst==0 )
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1925 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(4424).c

@@ -0,0 +1,1925 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			int i;
+			char* pData = data;
+
+			
+			for(i=0; i<13; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			  // ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			  // SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			ISCPacket = 5;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSWES\n");
+
+			if( SystemManager.RegRequst == 1 )	// 등록모드면 
+			{	
+				ISCPacket = 1;
+				SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+	
+				for(i=0; i<13; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}	
+
+#if 0			
+			if( FindRegMac(ScanHSBuff) == 1 )
+			{
+	
+				for(i=0; i<13; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+			
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}else{
+				///SystemManager.DevType = 0;
+
+
+			}
+#endif
+			
+			SystemManager.BandMode = AES_ENC_WES;
+
+			
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+			int i;
+			char* pData = data;
+
+			
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   //ISCPacket = 1;
+			   //SystemManager.DevType = DEV_IOS_PARK;
+			}
+
+			ISCPacket = 2;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSPCA\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				ISCPacket = 5;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.BandMode = AES_ENC_PCA;
+		}
+
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}else if( SystemManager.DevType == DEV_WES_ADV )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+		
+  
+		//return;
+	}else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		ISCPacket = 5;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+		
+  
+		//return;
+	}
+  
+
+
+
+	
+
+
+	
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto BAND_CONNECT; 
+		}
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1795 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(4605).c

@@ -0,0 +1,1795 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_IOS_PARK;
+			}
+		}
+
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+  
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1939 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(4867).c

@@ -0,0 +1,1939 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include "nrf_sdh.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,        nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+
+#if 1
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer > 0 )
+			{
+				//NRF_LOG_RAW_INFO(" <<  Transfer Busy  >>\n");	
+
+				return 0;
+				
+			}else{
+				SystemManager.DevType = DEV_BAND_ADV;	
+			}
+		}
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			if( SystemManager.LedBlinkTimer > 0 )
+			{
+				NRF_LOG_RAW_INFO(" <<  Transfer Busy  >>\n");
+				
+				return 0;
+				
+			}else{
+
+				SystemManager.TmpPtr = data+7;
+
+				if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+				{
+					SystemManager.DevType = DEV_BAND_PARK;
+					SystemManager.Encryption_Mode = AES_ENC_CAR;
+				}
+				else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+				{
+					;
+				}
+			}
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			if( SystemManager.LedBlinkTimer < 0 ){
+
+				SystemManager.TmpPtr = data+7;
+
+				if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+				{
+					SystemManager.DevType = DEV_BAND_EMG;
+					SystemManager.Encryption_Mode = AES_ENC_EMG;
+				}
+				else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+				{
+					;
+				}
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			NRF_LOG_RAW_INFO("==> ICSWES : ");
+
+			for(i=0; i<len; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			SystemManager.DevType = DEV_WES_ADV;
+
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			NRF_LOG_RAW_INFO("==> ICSPCA : ");
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				NRF_LOG_RAW_INFO(" <<  Transfer Busy  >>\n");	
+				return 0;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.Encryption_Mode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+	
+}
+
+#else
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+#if 0	// jakuja
+			for(i=0; i<len; i++)
+				NRF_LOG_RAW_INFO("%02X, ", data[i]);
+		
+			NRF_LOG_RAW_INFO("\n");
+#endif
+
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+               
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> DEV_IOS_PARK\n");
+				ISCPacket = 5;
+
+				SystemManager.LocalNameAddr[0] = new_ble_addr.addr[0];
+				SystemManager.LocalNameAddr[1] = new_ble_addr.addr[1];
+				SystemManager.LocalNameAddr[2] = new_ble_addr.addr[2];
+				SystemManager.LocalNameAddr[3] = new_ble_addr.addr[3];
+				SystemManager.LocalNameAddr[4] = new_ble_addr.addr[4];
+				SystemManager.LocalNameAddr[5] = new_ble_addr.addr[5];
+			}					
+
+			SystemManager.BandMode = AES_ENC_PCA;
+
+		}
+
+    }
+
+    return 0;
+}
+
+
+
+
+#endif
+
+
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+	pData = data;
+	validLen = dataLen;
+
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+	  }
+	}
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx, ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+
+	uint32_t err_code;
+	
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+	SystemManager.DevType = DEV_NONE;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+	if( SystemTimer.SVR_SEND_TIMER < 1000 )
+		goto SCAN_GOING; 
+
+#if 1
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+
+//	NRF_LOG_RAW_INFO("m_nrf_sdh_continue : %d, m_nrf_sdh_enabled : %d ", m_nrf_sdh_continue, m_nrf_sdh_enabled);
+#endif
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[5] == 0x31 && p_adv_report->data.p_data[6] == 0x01 && p_adv_report->data.p_data[7] == 0x02 && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck_Android(p_adv_report->data.p_data);
+
+		goto SCAN_GOING; 
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[3] == 0x02 && p_adv_report->data.p_data[4] == 0x0A && p_adv_report->data.p_data[5] == 0x0C && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 ){
+
+		//NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+
+		goto SCAN_GOING; 
+	}
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	memset(ScanHSBuff, 0x00, sizeof(ScanHSBuff));
+	
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+							                          p_adv_report->peer_addr.addr[1],
+							                          p_adv_report->peer_addr.addr[2],
+							                          p_adv_report->peer_addr.addr[3],
+							                          p_adv_report->peer_addr.addr[4],
+							                          p_adv_report->peer_addr.addr[5]);
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+  
+	SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+
+
+	if( SystemManager.DevType == DEV_BAND_ADV){
+
+		SystemManager.DevType = DEV_NONE;
+		goto SCAN_GOING; 
+
+	}
+	else if( SystemManager.DevType == DEV_BAND_PARK || SystemManager.DevType == DEV_BAND_EMG)
+	{
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 5000)
+		{
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+			SystemManager.DevType = DEV_NONE;
+
+#if 1
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+			}
+			NRF_LOG_RAW_INFO("\n");
+#endif
+		}
+
+	     goto GOTO_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_WES_ADV )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		SystemManager.DevType = DEV_NONE;
+
+
+		if( SystemManager.RegRequst == 1 )	// 등록모드면 
+		{	
+			NRF_LOG_RAW_INFO("Reciver Mode is Register\n");
+
+			SystemManager.Encryption_Mode = AES_ENC_WES;
+			
+			goto GOTO_CONNECT; 
+		}
+		
+		if( FindRegMac(ScanHSBuff) == 1 )	// MAC이 등록되어있지 않으면
+		{
+			goto GOTO_CONNECT; 
+
+		}else{
+			goto SCAN_GOING; 
+		}
+
+	}
+	else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+	
+		for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		 // goto SCAN_GOING; 
+		 goto GOTO_CONNECT; 
+	}
+  	
+
+#if 0
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+	}
+	else if( ISCPacket == 2)
+
+
+
+	if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto GOTO_CONNECT; 
+		}
+
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+
+#endif
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+
+		return;  
+	
+
+GOTO_CONNECT:
+
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("<------------------- BLE_GAP_EVT_DISCONNECTED ------------------->\n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_TIMEOUT \n" );
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1791 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(5076).c

@@ -0,0 +1,1791 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_IOS_PARK;
+			}
+		}
+
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+  
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1961 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(5257).c

@@ -0,0 +1,1961 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+
+#if 0
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+	char* pData = data;
+
+	uint8_t temp_buf[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+
+	ISCPacket = 0;
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		if( strncmp("ICSB", data+1, 4) == 0 )
+		{	
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+		}		
+        else if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Respons 
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+//			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+//			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )		// Response
+			{
+//				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}
+			else if(memcmp( SystemManager.TmpPtr, temp_buf, 6) == 0 )			// Advertise
+			{
+				ISCPacket = 5;
+			}
+        }
+		else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			
+			for(i=0; i<13; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			  // ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			  // SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			ISCPacket = 5;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSWES\n");
+
+			if( SystemManager.RegRequst == 1 )	// 등록모드면 
+			{	
+				ISCPacket = 1;
+				SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<13; i++){
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				}
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}	
+			
+			SystemManager.BandMode = AES_ENC_WES;
+			
+        }
+		else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+//			char* pData = data;
+
+			for(i=0; i<17; i++){
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			}
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   //ISCPacket = 1;
+			   //SystemManager.DevType = DEV_IOS_PARK;
+			}
+
+			ISCPacket = 2;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSPCA\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				ISCPacket = 5;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.BandMode = AES_ENC_PCA;
+		}
+    }
+
+    return 0;
+}
+
+#else
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+	int i;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+
+		
+#if 1	// jakuja
+			for(i=0; i<len; i++)
+				NRF_LOG_RAW_INFO("%02X, ", data[i]);
+		
+			NRF_LOG_RAW_INFO("\n");
+#endif
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+                int i;
+
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_IOS_PARK;
+				NRF_LOG_RAW_INFO("==> DEV_IOS_PARK\n");
+				ISCPacket = 5;
+			}					
+
+			SystemManager.BandMode = AES_ENC_PCA;
+
+
+//			if( SystemManager.LedBlinkTimer < 0 )
+//			{
+//			   ISCPacket = 1;
+//			   //SystemTimer.TMR_CON_START = 0; 
+//			   SystemManager.DevType = DEV_IOS_PARK;
+//			}
+		}
+
+    }
+
+    return 0;
+}
+
+
+
+
+#endif
+
+
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx, ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+//	NRF_LOG_RAW_INFO("m_nrf_sdh_continue : %d, m_nrf_sdh_enabled : %d ", m_nrf_sdh_continue, m_nrf_sdh_enabled);
+
+//	nrf_sdh_disable_request();
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+
+	}else if( SystemManager.DevType == DEV_WES_ADV )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		ISCPacket = 1;
+
+	}else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+	
+		for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+		{
+			
+			NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+	
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;
+	
+		 // goto SCAN_GOING; 
+		 goto BAND_CONNECT; 
+
+	}
+  	
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto BAND_CONNECT; 
+		}
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("<------------------- BLE_GAP_EVT_DISCONNECTED ------------------->\n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_TIMEOUT \n" );
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("<--------------------- BLE_GAP_EVT_CONNECTED ---------------------> \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1809 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(5821).c

@@ -0,0 +1,1809 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_IOS_PARK;
+			}
+		}
+
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja  수신데이타 DBG 확인
+
+	// 알수없는 장치 Filtering
+	if(p_adv_report->data.p_data[0] == 0x1E && p_adv_report->data.p_data[1] == 0xFF){
+		goto SCAN_GOING;
+	}
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+		goto SCAN_GOING;
+	}else{
+		//NRF_LOG_RAW_INFO("NOT Android APP PARKING\n");
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+		goto SCAN_GOING;
+	}else{
+
+		//NRF_LOG_RAW_INFO("NOT iOS APP PARKING\n");
+	}
+
+
+	HS_AdvertisePacket_Parser(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+	else if (SystemManager.DevType == DEV_NEW_IOS_PARK )
+	{
+
+
+	}
+
+
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1814 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(585).c

@@ -0,0 +1,1814 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+     ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+
+			
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+		}
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+
+
+
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+  int len, validLen;
+  char* pData;
+  int i;
+  int j;
+  int v=0;
+  int result;
+
+
+  pData = data;
+  validLen = dataLen;
+
+#if 1
+  if( flag )
+  {
+      // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+      while(1)
+      {
+
+          result = HS_AdParser(pData);
+         // if( result == 0 )
+         //     break;
+
+          len = *pData;
+          validLen -= len+1;
+
+          //printf("len:%d  validLen:%d\n", len, validLen);
+          if( validLen <= 0 )
+            break;
+
+          pData += len+1;
+
+      }
+     
+  }
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 1
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (¾Èµå·ÎÀ̵å)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+	}
+
+
+
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+	if( SystemManager.RegRequst == 1 )
+	{
+		//SystemManager.LedBlinkRun = 0;
+		//SystemManager.RegRequst = 0;
+
+		//goto SCAN_GOING; 
+	}
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER>6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+     // goto SCAN_GOING; 
+     goto BAND_CONNECT; 
+
+		
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{
+	
+		if( SystemManager.RegRequst == 1 )
+		{
+			//SystemManager.LedBlinkRun = 0;
+			//SystemManager.RegRequst = 0;
+	
+			//goto SCAN_GOING; 
+		}
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+
+	}
+	
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+  
+
+  if( ISCPacket == 1)
+  {
+    int i;
+
+    if( FindRegMac(ScanHSBuff) == 0 )
+    {
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+	  if( SystemManager.RegRequst==0 )
+      	return;
+    }
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else if( ISCPacket == 2)
+  {
+    int i;
+
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else{
+
+
+SCAN_GOING:
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+    return;  
+  }
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1814 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(605).c

@@ -0,0 +1,1814 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+     ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+
+			
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+		}
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+
+
+
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+  int len, validLen;
+  char* pData;
+  int i;
+  int j;
+  int v=0;
+  int result;
+
+
+  pData = data;
+  validLen = dataLen;
+
+#if 1
+  if( flag )
+  {
+      // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+      while(1)
+      {
+
+          result = HS_AdParser(pData);
+         // if( result == 0 )
+         //     break;
+
+          len = *pData;
+          validLen -= len+1;
+
+          //printf("len:%d  validLen:%d\n", len, validLen);
+          if( validLen <= 0 )
+            break;
+
+          pData += len+1;
+
+      }
+     
+  }
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (¾Èµå·ÎÀ̵å)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+	}
+
+
+
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+	if( SystemManager.RegRequst == 1 )
+	{
+		//SystemManager.LedBlinkRun = 0;
+		//SystemManager.RegRequst = 0;
+
+		//goto SCAN_GOING; 
+	}
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+     // goto SCAN_GOING; 
+     goto BAND_CONNECT; 
+
+		
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{
+	
+		if( SystemManager.RegRequst == 1 )
+		{
+			//SystemManager.LedBlinkRun = 0;
+			//SystemManager.RegRequst = 0;
+	
+			//goto SCAN_GOING; 
+		}
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+
+	}
+	
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+  
+
+  if( ISCPacket == 1)
+  {
+    int i;
+
+    if( FindRegMac(ScanHSBuff) == 0 )
+    {
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+	  if( SystemManager.RegRequst==0 )
+      	return;
+    }
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else if( ISCPacket == 2)
+  {
+    int i;
+
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else{
+
+
+SCAN_GOING:
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+    return;  
+  }
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1926 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(6747).c

@@ -0,0 +1,1926 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+			int i;
+			char* pData = data;
+
+			
+			for(i=0; i<13; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+
+	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			  // ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			  // SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			ISCPacket = 5;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSWES\n");
+
+			if( SystemManager.RegRequst == 1 )	// 등록모드면 
+			{	
+				ISCPacket = 1;
+				SystemManager.DevType = DEV_WES_ADV;
+			}
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+	
+				for(i=0; i<13; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}	
+
+#if 0			
+			if( FindRegMac(ScanHSBuff) == 1 )
+			{
+	
+				for(i=0; i<13; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+			
+				SystemManager.DevType = DEV_WES_ADV;
+				ISCPacket = 1;
+				NRF_LOG_RAW_INFO("==> ICSWES_MAC\n");
+			}else{
+				///SystemManager.DevType = 0;
+
+
+			}
+#endif
+			
+			SystemManager.BandMode = AES_ENC_WES;
+
+			
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+			int i;
+			char* pData = data;
+
+			
+			for(i=0; i<17; i++)
+				NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+			NRF_LOG_RAW_INFO("\n");
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   //ISCPacket = 1;
+			   //SystemManager.DevType = DEV_IOS_PARK;
+			}
+
+			ISCPacket = 2;
+			SystemManager.DevType = 0;
+			NRF_LOG_RAW_INFO("==> ICSPCA\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+
+	
+				for(i=0; i<17; i++)
+					NRF_LOG_RAW_INFO("%02X, ", pData[i]);
+				NRF_LOG_RAW_INFO("\n");
+				
+				SystemManager.DevType = DEV_IOS_PARK;
+				ISCPacket = 5;
+				NRF_LOG_RAW_INFO("==> ICSPCA_MAC\n");
+			}
+			
+			SystemManager.BandMode = AES_ENC_PCA;
+		}
+
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}else if( SystemManager.DevType == DEV_WES_ADV )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_WES_ADV\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+		
+  
+		//return;
+	}else if( SystemManager.DevType == DEV_IOS_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_IOS_PARK\n");
+
+		ISCPacket = 5;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+		
+  
+		//return;
+	}
+  
+
+
+
+	
+
+
+	
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+
+		if( SystemManager.DevType == DEV_IOS_PARK )
+		{
+			NRF_LOG_RAW_INFO("================= One Pass Connect\n");
+			goto BAND_CONNECT; 
+		}
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1830 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(7374).c

@@ -0,0 +1,1830 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+     ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+
+			
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+		}
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+
+
+
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+  int len, validLen;
+  char* pData;
+  int i;
+  int j;
+  int v=0;
+  int result;
+
+
+  pData = data;
+  validLen = dataLen;
+
+#if 1
+  if( flag )
+  {
+      // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+      while(1)
+      {
+
+          result = HS_AdParser(pData);
+         // if( result == 0 )
+         //     break;
+
+          len = *pData;
+          validLen -= len+1;
+
+          //printf("len:%d  validLen:%d\n", len, validLen);
+          if( validLen <= 0 )
+            break;
+
+          pData += len+1;
+
+      }
+     
+  }
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+	AppParkingCheck(p_adv_report->data.p_data);
+
+
+
+#if 0
+	SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	for( i=0; i<6; i++)
+	{
+	
+	  //NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+	}
+	//NRF_LOG_RAW_INFO("\n");
+
+
+
+  HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+  sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+                              p_adv_report->peer_addr.addr[1],
+                              p_adv_report->peer_addr.addr[2],
+                              p_adv_report->peer_addr.addr[3],
+                              p_adv_report->peer_addr.addr[4],
+                              p_adv_report->peer_addr.addr[5]);
+  ScanHSBuff[12] = 0;
+
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+  SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+	if( SystemManager.RegRequst == 1 )
+	{
+		//SystemManager.LedBlinkRun = 0;
+		//SystemManager.RegRequst = 0;
+
+		//goto SCAN_GOING; 
+
+	}
+
+
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER>6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+     // goto SCAN_GOING; 
+     goto BAND_CONNECT; 
+
+	  
+
+		
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{
+
+	
+		if( SystemManager.RegRequst == 1 )
+		{
+			//SystemManager.LedBlinkRun = 0;
+			//SystemManager.RegRequst = 0;
+	
+			//goto SCAN_GOING; 
+	
+		}
+	
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+
+	  
+		//return;
+
+	}
+	
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+	
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+			//SystemManager.DevType = 0;
+
+		}
+
+
+	  
+		//return;
+
+	}
+
+
+  
+
+  if( ISCPacket == 1)
+  {
+    int i;
+
+    if( FindRegMac(ScanHSBuff) == 0 )
+    {
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+	  if( SystemManager.RegRequst==0 )
+      	return;
+    }
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else if( ISCPacket == 2)
+  {
+    int i;
+
+    
+     //NRF_LOG_RAW_INFO("================= Emergency\n");
+    for( i=0; i<6; i++)
+    {
+    
+      NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+    }
+    NRF_LOG_RAW_INFO("\n");
+
+    ISCPacket = 0;  
+  
+
+  }
+  else{
+
+
+SCAN_GOING:
+
+      scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+      scan_evt.params.p_not_found = p_adv_report;
+
+      // If the event handler is not NULL, notify the main application.
+      if (p_scan_ctx->evt_handler != NULL)
+      {
+          //p_scan_ctx->evt_handler(&scan_evt);
+      }
+
+      // Resume the scanning.
+      UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+      ISCPacket = 0;
+
+    return;  
+  }
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1786 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(7773).c

@@ -0,0 +1,1786 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_Advertise_Parser(char* data)
+{
+    int len;
+    int j;
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_CAR;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				NRF_LOG_RAW_INFO("ICSCAR -- Connect Request\n");
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}else{
+				NRF_LOG_RAW_INFO("ICSCAR - ADV\n");
+			}
+        }
+		// BAND EMG
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				NRF_LOG_RAW_INFO("==> ICSEMG -- Connect Request\n");
+				
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}else{
+				NRF_LOG_RAW_INFO("ICSEMG - ADV\n");
+			}
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_NEW_IOS_PARK;
+			}
+		}
+
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+    }
+
+    return 0;
+}
+
+void HS_AdvertisePacket_Parser(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja  수신데이타 DBG 확인
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+		goto SCAN_GOING;
+	}else{
+		//NRF_LOG_RAW_INFO("NOT Android APP PARKING\n");
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+		goto SCAN_GOING;
+	}else{
+
+		//NRF_LOG_RAW_INFO("NOT iOS APP PARKING\n");
+	}
+
+
+	HS_AdvertisePacket_Parser(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+  
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 1791 - 0
BLE_Central.si4project/Backup/nrf_ble_scan(88).c

@@ -0,0 +1,1791 @@
+/**
+ * Copyright (c) 2018 - 2020, 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(NRF_BLE_SCAN)
+
+#include "sdk_config.h"
+#include <stdlib.h>
+
+#include "nrf_ble_scan.h"
+
+#include <string.h>
+#include "app_error.h"
+#include "nrf_assert.h"
+#include "sdk_macros.h"
+#include "ble_advdata.h"
+
+#define NRF_LOG_MODULE_NAME ble_scan
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+#include <stdio.h>
+
+#include "our_service.h"
+
+#include "sysmgr.h"
+
+
+/**@brief Function for establishing the connection with a device.
+ *
+ * @details Connection is established if @ref NRF_BLE_SCAN_EVT_FILTER_MATCH
+ *          or @ref NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT occurs and the module was
+ *          initialized in the automatic connection mode. This function can generate an event
+ *          to the main application when @ref sd_ble_gap_connect is used inside the function and it returns value
+ *          that is different than @ref NRF_SUCCESS.
+ *
+ * @param[in] p_scan_ctx   Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report Advertising data.
+ */
+static void nrf_ble_scan_connect_with_target(nrf_ble_scan_t           const * const p_scan_ctx,
+                                             ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    // For readability.
+    ble_gap_addr_t const        * p_addr        = &p_adv_report->peer_addr;
+    ble_gap_scan_params_t const * p_scan_params = &p_scan_ctx->scan_params;
+    ble_gap_conn_params_t const * p_conn_params = &p_scan_ctx->conn_params;
+    uint8_t                       con_cfg_tag   = p_scan_ctx->conn_cfg_tag;
+
+    // Return if the automatic connection is disabled.
+    if (!p_scan_ctx->connect_if_match)
+    {
+        return;
+    }
+
+    // Stop scanning.
+    nrf_ble_scan_stop();
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    // Establish connection.
+    err_code = sd_ble_gap_connect(p_addr,
+                                  p_scan_params,
+                                  p_conn_params,
+                                  con_cfg_tag);
+
+    NRF_LOG_DEBUG("Connecting");
+
+    scan_evt.scan_evt_id                    = NRF_BLE_SCAN_EVT_CONNECTING_ERROR;
+    scan_evt.params.connecting_err.err_code = err_code;
+
+    NRF_LOG_DEBUG("Connection status: %d", err_code);
+
+    // If an error occurred, send an event to the event handler.
+    if ((err_code != NRF_SUCCESS) && (p_scan_ctx->evt_handler != NULL))
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+}
+
+
+/**@brief Function for decoding the BLE address type.
+ *
+ * @param[in] p_addr 	The BLE address.
+ *
+ * @return    			Address type, or an error if the address type is incorrect, that is it does not match @ref BLE_GAP_ADDR_TYPES.
+ *
+ */
+static uint16_t nrf_ble_scan_address_type_decode(uint8_t const * p_addr)
+{
+    uint8_t addr_type = p_addr[0];
+
+    // See Bluetooth Core Specification Vol 6, Part B, section 1.3.
+    addr_type  = addr_type >> 6;
+    addr_type &= 0x03;
+
+    // Check address type.
+    switch (addr_type)
+    {
+        case 0:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
+        }
+
+        case 1:
+        {
+            return BLE_GAP_ADDR_TYPE_PUBLIC;
+        }
+
+        case 2:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+        }
+
+        case 3:
+        {
+            return BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
+        }
+
+        default:
+        {
+            return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+        }
+    }
+}
+
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+
+/**@brief Function for searching for the provided address in the advertisement packets.
+ *
+ * @details Use this function to parse the received advertising data for the provided address.
+ *        
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_addr         Address to search for. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ *
+ * @return   True if the provided address was found, false otherwise.
+ */
+static bool find_peer_addr(ble_gap_evt_adv_report_t const * const p_adv_report,
+                           ble_gap_addr_t const                 * p_addr)
+{
+    if (p_addr->addr_type == p_adv_report->peer_addr.addr_type)
+    {
+        // Compare addresses.
+        if (memcmp(p_addr->addr,
+                   p_adv_report->peer_addr.addr,
+                   sizeof(p_adv_report->peer_addr.addr)) == 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/** @brief Function for comparing the provided address with the addresses of the advertising devices.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the address matches with the addresses of the advertising devices. False otherwise.
+ */
+static bool adv_addr_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t const * const           p_scan_ctx)
+{
+    ble_gap_addr_t const * p_addr  = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t                counter = p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+
+    for (uint8_t index = 0; index < counter; index++)
+    {
+        // Search for address.
+        if (find_peer_addr(p_adv_report, &p_addr[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding target address to the scanning filter.
+ *
+ * @param[in]     p_addr            Target address in the format required by the SoftDevice. If you need to convert the address, use @ref nrf_ble_scan_copy_addr_to_sd_gap_addr. The address length must correspond to @ref BLE_GAP_ADDR_LEN.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS                    If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY            If the number of available filters is exceeded.
+ * @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address type is invalid.
+ */
+static ret_code_t nrf_ble_scan_addr_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               uint8_t        const * p_addr)
+{
+    ble_gap_addr_t * p_addr_filter = p_scan_ctx->scan_filters.addr_filter.target_addr;
+    uint8_t        * p_counter     = &p_scan_ctx->scan_filters.addr_filter.addr_cnt;
+    uint8_t          index;
+    uint16_t         addr_type;
+    uint8_t          temp_addr[BLE_GAP_ADDR_LEN];
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_ADDRESS_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_ADDRESS_CNT; index++)
+    {
+        if (!memcmp(p_addr_filter[index].addr, p_addr, BLE_GAP_ADDR_LEN))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Inverting the address.
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        temp_addr[i] = p_addr[(BLE_GAP_ADDR_LEN - 1) - i];
+    }
+
+    // Decode address type.
+    addr_type = nrf_ble_scan_address_type_decode(temp_addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    // Add target address to filter.
+    p_addr_filter[*p_counter].addr_type = (uint8_t)addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; i++)
+    {
+        p_addr_filter[*p_counter].addr[i] = p_addr[i];
+    }
+
+    NRF_LOG_DEBUG("Filter set on address type %i, address 0x",
+                  p_addr_filter[*p_counter].addr_type);
+
+    for (index = 0; index < BLE_GAP_ADDR_LEN; index++)
+    {
+        NRF_LOG_DEBUG("%x", p_addr_filter[*p_counter].addr[index]);
+    }
+
+    NRF_LOG_DEBUG("\n\r");
+
+    // Increase the address filter counter.
+    *p_counter += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_ADDRESS_CNT
+
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+/** @brief Function for comparing the provided name with the advertised name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_name_compare(ble_gap_evt_adv_report_t const * p_adv_report,
+                             nrf_ble_scan_t     const * const p_scan_ctx)
+{
+    nrf_ble_scan_name_filter_t const * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    uint8_t                            counter       =
+        p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filter.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_name_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  p_name_filter->target_name[index]))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_name            Peripheral name.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_name_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               char           const * p_name)
+{
+    uint8_t   index;
+    uint8_t * counter  = &p_scan_ctx->scan_filters.name_filter.name_cnt;
+    uint8_t   name_len = strlen(p_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*counter >= NRF_BLE_SCAN_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_NAME_CNT; index++)
+    {
+        if (!strcmp(p_scan_ctx->scan_filters.name_filter.target_name[index], p_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to filter.
+    memcpy(p_scan_ctx->scan_filters.name_filter.target_name[(*counter)++],
+           p_name,
+           strlen(p_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_NAME_CNT
+
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+/** @brief Function for comparing the provided short name with the advertised short name.
+ *
+ * @param[in] p_adv_report    Advertising data to parse.
+ * @param[in] p_scan_ctx      Pointer to the Scanning Module instance.
+ *
+ * @retval True when the names match. False otherwise.
+ */
+static bool adv_short_name_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_short_name_filter_t const * p_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t  counter = p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Compare the name found with the name filters.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_short_name_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        p_name_filter->short_name[index].short_target_name,
+                                        p_name_filter->short_name[index].short_name_min_len))
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding the short name of the peripheral to the scanning filter.
+ *
+ * @param[in]     p_short_name      Short name of the peripheral.
+ * @param[in,out] p_scan_ctx        Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL           If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_DATA_SIZE      If the name filter length is too long. The maximum filter name length corresponds to @ref NRF_BLE_SCAN_SHORT_NAME_MAX_LEN.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_short_name_filter_add(nrf_ble_scan_t            * const p_scan_ctx,
+                                                     nrf_ble_scan_short_name_t const * p_short_name)
+{
+    uint8_t   index;
+    uint8_t * p_counter =
+        &p_scan_ctx->scan_filters.short_name_filter.name_cnt;
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    uint8_t name_len = strlen(p_short_name->p_short_name);
+
+    // Check the name length.
+    if ((name_len == 0) || (name_len > NRF_BLE_SCAN_SHORT_NAME_MAX_LEN))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // If no memory for filter.
+    if (*p_counter >= NRF_BLE_SCAN_SHORT_NAME_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_SHORT_NAME_CNT; index++)
+    {
+        if (!strcmp(p_short_name_filter->short_name[index].short_target_name,
+                    p_short_name->p_short_name))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add name to the filter.
+    p_short_name_filter->short_name[(*p_counter)].short_name_min_len =
+        p_short_name->short_name_min_len;
+    memcpy(p_short_name_filter->short_name[(*p_counter)++].short_target_name,
+           p_short_name->p_short_name,
+           strlen(p_short_name->p_short_name));
+
+    NRF_LOG_DEBUG("Adding filter on %s name", p_short_name->p_short_name);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif
+
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+/**@brief Function for comparing the provided UUID with the UUID in the advertisement packets.
+ *
+ * @param[in]   p_adv_report   Advertising data to parse.
+ * @param[in]   p_scan_ctx     Pointer to the Scanning Module instance.
+ *
+ * @return      True if the UUIDs match. False otherwise.
+ */
+static bool adv_uuid_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                             nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_uuid_filter_t const * p_uuid_filter    = &p_scan_ctx->scan_filters.uuid_filter;
+    bool const                         all_filters_mode = p_scan_ctx->scan_filters.all_filters_mode;
+    uint8_t const                      counter          =
+        p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+    uint8_t  uuid_match_cnt = 0;
+
+    data_len = p_adv_report->data.len;
+
+    for (index = 0; index < counter; index++)
+    {
+
+        if (ble_advdata_uuid_find(p_adv_report->data.p_data,
+                                  data_len,
+                                  &p_uuid_filter->uuid[index]))
+        {
+            uuid_match_cnt++;
+
+            // In the normal filter mode, only one UUID is needed to match.
+            if (!all_filters_mode)
+            {
+                break;
+            }
+        }
+        else if (all_filters_mode)
+        {
+            break;
+        }
+        else
+        {
+            // Do nothing.
+        }
+    }
+
+    // In the multifilter mode, all UUIDs must be found in the advertisement packets.
+    if ((all_filters_mode && (uuid_match_cnt == counter)) ||
+        ((!all_filters_mode) && (uuid_match_cnt > 0)))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for adding UUID to the scanning filter.
+ *
+ * @param[in]     uuid       UUID, 16-bit size.
+ * @param[in,out] p_scan_ctx Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS              If the scanning started. Otherwise, an error code is returned, also if you tried to add a filter that was already added before.
+ * @retval NRF_ERROR_NO_MEMORY      If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_uuid_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                               ble_uuid_t     const * p_uuid)
+{
+    ble_uuid_t * p_uuid_filter = p_scan_ctx->scan_filters.uuid_filter.uuid;
+    uint8_t    * p_counter     = &p_scan_ctx->scan_filters.uuid_filter.uuid_cnt;
+    uint8_t      index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_UUID_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for (index = 0; index < NRF_BLE_SCAN_UUID_CNT; index++)
+    {
+        if (p_uuid_filter[index].uuid == p_uuid->uuid)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add UUID to the filter.
+    p_uuid_filter[(*p_counter)++] = *p_uuid;
+    NRF_LOG_DEBUG("Added filter on UUID %x", p_uuid->uuid);
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_UUID_CNT
+
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT)
+/**@brief Function for comparing the provided appearance with the appearance in the advertisement packets.
+ *
+ * @param[in]     p_adv_report Advertising data to parse.
+ * @param[in,out] p_scan_ctx   Pointer to the Scanning Module instance.
+ *
+ * @return      True if the appearances match. False otherwise.
+ */
+static bool adv_appearance_compare(ble_gap_evt_adv_report_t const * const p_adv_report,
+                                   nrf_ble_scan_t           const * const p_scan_ctx)
+{
+    nrf_ble_scan_appearance_filter_t const * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    uint8_t const counter =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t  index;
+    uint16_t data_len;
+
+    data_len = p_adv_report->data.len;
+
+    // Verify if the advertised appearance matches the provided appearance.
+    for (index = 0; index < counter; index++)
+    {
+        if (ble_advdata_appearance_find(p_adv_report->data.p_data,
+                                        data_len,
+                                        &p_appearance_filter->appearance[index]))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for adding appearance to the scanning filter.
+ *
+ * @param[in]     appearance       Appearance to be added.
+ * @param[in,out] p_scan_ctx       Pointer to the Scanning Module instance.
+ *
+ * @retval NRF_SUCCESS             If the filter is added successfully or if you try to add a filter that was already added before.
+ * @retval NRF_ERROR_NULL          If a NULL pointer is passed as input.
+ * @retval NRF_ERROR_NO_MEMORY     If the number of available filters is exceeded.
+ */
+static ret_code_t nrf_ble_scan_appearance_filter_add(nrf_ble_scan_t * const p_scan_ctx,
+                                                     uint16_t               appearance)
+{
+    uint16_t * p_appearance_filter = p_scan_ctx->scan_filters.appearance_filter.appearance;
+    uint8_t  * p_counter           = &p_scan_ctx->scan_filters.appearance_filter.appearance_cnt;
+    uint8_t    index;
+
+    // If no memory.
+    if (*p_counter >= NRF_BLE_SCAN_APPEARANCE_CNT)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    // Check for duplicated filter.
+    for ( index = 0; index < NRF_BLE_SCAN_APPEARANCE_CNT; index++)
+    {
+        if (p_appearance_filter[index] == appearance)
+        {
+            return NRF_SUCCESS;
+        }
+    }
+
+    // Add appearance to the filter.
+    p_appearance_filter[(*p_counter)++] = appearance;
+    NRF_LOG_DEBUG("Added filter on appearance %x", appearance);
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_APPEARANCE_CNT
+
+
+ret_code_t nrf_ble_scan_filter_set(nrf_ble_scan_t     * const p_scan_ctx,
+                                   nrf_ble_scan_filter_type_t type,
+                                   void const               * p_data)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    switch (type)
+    {
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+        case SCAN_NAME_FILTER:
+        {
+            char * p_name = (char *)p_data;
+            return nrf_ble_scan_name_filter_add(p_scan_ctx, p_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+        case SCAN_SHORT_NAME_FILTER:
+        {
+            nrf_ble_scan_short_name_t * p_short_name = (nrf_ble_scan_short_name_t *)p_data;
+            return nrf_ble_scan_short_name_filter_add(p_scan_ctx, p_short_name);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+        case SCAN_ADDR_FILTER:
+        {
+            uint8_t * p_addr = (uint8_t *)p_data;
+            return nrf_ble_scan_addr_filter_add(p_scan_ctx, p_addr);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+        case SCAN_UUID_FILTER:
+        {
+            ble_uuid_t * p_uuid = (ble_uuid_t *)p_data;
+            return nrf_ble_scan_uuid_filter_add(p_scan_ctx, p_uuid);
+        }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+        case SCAN_APPEARANCE_FILTER:
+        {
+            uint16_t appearance = *((uint16_t *)p_data);
+            return nrf_ble_scan_appearance_filter_add(p_scan_ctx, appearance);
+        }
+#endif
+
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+ret_code_t nrf_ble_scan_all_filter_remove(nrf_ble_scan_t * const p_scan_ctx)
+{
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    nrf_ble_scan_name_filter_t * p_name_filter = &p_scan_ctx->scan_filters.name_filter;
+    memset(p_name_filter->target_name, 0, sizeof(p_name_filter->target_name));
+    p_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    nrf_ble_scan_short_name_filter_t * p_short_name_filter =
+        &p_scan_ctx->scan_filters.short_name_filter;
+    memset(p_short_name_filter->short_name, 0, sizeof(p_short_name_filter->short_name));
+    p_short_name_filter->name_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    nrf_ble_scan_addr_filter_t * p_addr_filter = &p_scan_ctx->scan_filters.addr_filter;
+    memset(p_addr_filter->target_addr, 0, sizeof(p_addr_filter->target_addr));
+    p_addr_filter->addr_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    nrf_ble_scan_uuid_filter_t * p_uuid_filter = &p_scan_ctx->scan_filters.uuid_filter;
+    memset(p_uuid_filter->uuid, 0, sizeof(p_uuid_filter->uuid));
+    p_uuid_filter->uuid_cnt = 0;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    nrf_ble_scan_appearance_filter_t * p_appearance_filter =
+        &p_scan_ctx->scan_filters.appearance_filter;
+    memset(p_appearance_filter->appearance, 0, sizeof(p_appearance_filter->appearance));
+    p_appearance_filter->appearance_cnt = 0;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_enable(nrf_ble_scan_t * const p_scan_ctx,
+                                       uint8_t                mode,
+                                       bool                   match_all)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Check if the mode is correct.
+    if ((!(mode & NRF_BLE_SCAN_ADDR_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_UUID_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)) &&
+        (!(mode & NRF_BLE_SCAN_APPEARANCE_FILTER)))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    ret_code_t err_code;
+
+    // Disable filters.
+    err_code = nrf_ble_scan_filters_disable(p_scan_ctx);
+    ASSERT(err_code == NRF_SUCCESS);
+
+    nrf_ble_scan_filters_t * p_filters = &p_scan_ctx->scan_filters;
+
+    // Turn on the filters of your choice.
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    if (mode & NRF_BLE_SCAN_ADDR_FILTER)
+    {
+        p_filters->addr_filter.addr_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_NAME_FILTER)
+    {
+        p_filters->name_filter.name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (mode & NRF_BLE_SCAN_SHORT_NAME_FILTER)
+    {
+        p_filters->short_name_filter.short_name_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    if (mode & NRF_BLE_SCAN_UUID_FILTER)
+    {
+        p_filters->uuid_filter.uuid_filter_enabled = true;
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    if (mode & NRF_BLE_SCAN_APPEARANCE_FILTER)
+    {
+        p_filters->appearance_filter.appearance_filter_enabled = true;
+    }
+#endif
+
+    // Select the filter mode.
+    p_filters->all_filters_mode = match_all;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filters_disable(nrf_ble_scan_t * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    // Disable all filters.
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool * p_name_filter_enabled = &p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+    *p_name_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool * p_addr_filter_enabled = &p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+    *p_addr_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool * p_uuid_filter_enabled = &p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+    *p_uuid_filter_enabled = false;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool * p_appearance_filter_enabled =
+        &p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+    *p_appearance_filter_enabled = false;
+#endif
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_filter_get(nrf_ble_scan_t * const   p_scan_ctx,
+                                   nrf_ble_scan_filters_t * p_status)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+    VERIFY_PARAM_NOT_NULL(p_status);
+
+    *p_status = p_scan_ctx->scan_filters;
+
+    return NRF_SUCCESS;
+}
+
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+int ISCPacket;
+
+int HS_AdParser(char* data)
+{
+    int len;
+    int j;
+
+
+    if( *(data+1) == 0xff )
+        return 0;
+
+
+    len = *data;
+    //NRF_LOG_RAW_INFO("Len:%d ", len );
+    data++;
+    //NRF_LOG_RAW_INFO("Flag:0x%02x \n", *data );
+
+	SystemManager.PtrLocalNameLen = len;
+	ISCPacket = 0;
+
+
+
+
+#if 1
+    if( *data == 9)
+    {
+    	SystemManager.PtrLocalName = data+1;
+
+		
+        if( strncmp("ICSCAR", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSCAR\n");
+
+			SystemManager.TmpPtr = data+7;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_BAND_PARK;
+				ISCPacket = 5;
+			}
+			
+			SystemManager.BandMode = AES_ENC_CAR;
+        }
+		else if( strncmp("ICSEMG", data+1, 6) == 0 )
+        {   
+			NRF_LOG_RAW_INFO("ICSEMG\n");
+
+			SystemManager.TmpPtr = data+7;
+			SystemManager.BandMode = AES_ENC_EMG;
+
+			if( memcmp( SystemManager.TmpPtr, new_ble_addr.addr, 6) == 0 )
+			{
+				SystemManager.DevType = DEV_EMG_BAND;
+				NRF_LOG_RAW_INFO("==> DEV_EMG_BAND\n");
+				ISCPacket = 5;
+			}					
+        }
+		else if( strncmp("ICSB", data+1, 4) == 0 )
+        {   
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+	           ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_BAND_ADV;
+			}
+        }else if( strncmp("ICSWES", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_WES_ADV;
+			}
+        }else if( strncmp("ICSPCA", data+1, 6) == 0 )
+		{	
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+			   ISCPacket = 1;
+			   //SystemTimer.TMR_CON_START = 0; 
+			   SystemManager.DevType = DEV_IOS_PARK;
+			}
+		}
+
+
+		   
+/*
+		else if( strncmp("ICSDEVREG", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 2;
+        }else if( strncmp("ICSDEVDEL", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 3;
+        }else if( strncmp("ICSDEVDSP", data+1, 9) == 0 )
+        {
+            //return 0;
+             ISCPacket = 4;
+        }
+*/
+
+#if 0
+
+	if( ISCPacket > 0 )
+	{
+        for(j=1; j<len; j++)
+        {
+            data++;
+
+            if( (*(data)>= 0x41&& *(data)<=0x5a) || (*(data)>= 0x61&& *(data)<=0x7a) )
+            {
+                NRF_LOG_RAW_INFO("%c ", *(data) );
+            }else{
+                NRF_LOG_RAW_INFO("0x%02x ", *(data) );
+            }
+
+
+        }
+        NRF_LOG_RAW_INFO("\n") ;
+	}
+#endif
+
+
+    }
+#endif
+
+    return 0;
+}
+
+void HS_ParseAdvPacket(char* data, int dataLen, int flag)
+{
+  
+	int len, validLen;
+	char* pData;
+	int i;
+	int j;
+	int v=0;
+	int result;
+
+
+	pData = data;
+	validLen = dataLen;
+
+#if 1
+	if( flag )
+	{
+	  // NRF_LOG_RAW_INFO("MEM : %08x ==> ", pData) ;        
+	  while(1)
+	  {
+
+	      result = HS_AdParser(pData);
+	     // if( result == 0 )
+	     //     break;
+
+	      len = *pData;
+	      validLen -= len+1;
+
+	      //printf("len:%d  validLen:%d\n", len, validLen);
+	      if( validLen <= 0 )
+	        break;
+
+	      pData += len+1;
+
+	  }
+	 
+	}
+
+#endif
+  
+  
+
+
+
+
+}
+
+
+
+
+/**@brief Function for calling the BLE_GAP_EVT_ADV_REPORT event to check whether the received
+ *        scanning data matches the scan configuration.
+ *
+ * @param[in] p_scan_ctx    Pointer to the Scanning Module instance.
+ * @param[in] p_adv_report  Advertising report.
+ */
+char ScanHSBuff[15];
+uint8_t *pAdvRep;
+
+// jakuja  
+static void nrf_ble_scan_on_adv_report(nrf_ble_scan_t           const * const p_scan_ctx,
+                                       ble_gap_evt_adv_report_t const * const p_adv_report)
+{
+    scan_evt_t scan_evt;
+    int i;
+    uint8_t *pdata;
+	uint8_t addr[6];
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    uint8_t filter_cnt       = 0;
+    uint8_t filter_match_cnt = 0;
+#endif
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    scan_evt.p_scan_params = &p_scan_ctx->scan_params;
+    pdata = p_adv_report->data.p_data;
+	pAdvRep = p_adv_report->data.p_data;;
+
+#if 0	// jakuja
+	for(i=0; i<p_adv_report->data.len; i++)
+		NRF_LOG_RAW_INFO("%02X, ", p_adv_report->data.p_data[i]);
+
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+
+	// ONE PASS APP (안드로이드)
+	if(p_adv_report->data.p_data[3] == 0x19 && p_adv_report->data.p_data[4] == 0xFF && p_adv_report->data.p_data[8] == 0xEE){
+
+		AppParkingCheck(p_adv_report->data.p_data);
+
+	}
+
+	// ONE PASS APP (IOS)
+	if(p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07 && p_adv_report->data.p_data[6] == 0x11 && p_adv_report->data.p_data[7] == 0x07){
+
+		NRF_LOG_RAW_INFO("IOS APP PARKING\n");
+
+		AppParkingCheck_IOS(p_adv_report->data.p_data);
+		
+	}
+
+
+	HS_ParseAdvPacket(p_adv_report->data.p_data, p_adv_report->data.len, 1);
+
+	if( SystemManager.DevType == DEV_NONE )
+		goto SCAN_GOING; 
+
+	sprintf(ScanHSBuff, "%02x%02x%02x%02x%02x%02x", p_adv_report->peer_addr.addr[0],
+	                          p_adv_report->peer_addr.addr[1],
+	                          p_adv_report->peer_addr.addr[2],
+	                          p_adv_report->peer_addr.addr[3],
+	                          p_adv_report->peer_addr.addr[4],
+	                          p_adv_report->peer_addr.addr[5]);
+	ScanHSBuff[12] = 0;
+
+  
+#if 1
+	  SystemManager.PeerAddr[0] = p_adv_report->peer_addr.addr[0];
+	  SystemManager.PeerAddr[1] = p_adv_report->peer_addr.addr[1];
+	  SystemManager.PeerAddr[2] = p_adv_report->peer_addr.addr[2];
+	  SystemManager.PeerAddr[3] = p_adv_report->peer_addr.addr[3];
+	  SystemManager.PeerAddr[4] = p_adv_report->peer_addr.addr[4];
+	  SystemManager.PeerAddr[5] = p_adv_report->peer_addr.addr[5];
+#endif
+
+
+	SystemManager.PtrPeerAddrStr = ScanHSBuff;
+
+
+
+	if( SystemManager.DevType == DEV_BAND_PARK )
+	{
+
+		NRF_LOG_RAW_INFO("=================  Send Park\n");
+
+		if( SystemManager.LedBlinkTimer && SystemTimer.PARK_KEEP_TIMER > 6000)
+		{
+		
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 3000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemTimer.PARK_KEEP_TIMER = 0;
+
+			SystemManager.DevType = 0;
+	        ISCPacket = 0;  
+
+  			NRF_LOG_RAW_INFO("name len is %d ", SystemManager.PtrLocalNameLen);
+
+			for( i=0; i<SystemManager.PtrLocalNameLen; i++)
+			{
+				
+				NRF_LOG_RAW_INFO("%02x ", *(SystemManager.PtrLocalName+i) );
+
+			}
+			NRF_LOG_RAW_INFO("\n");
+		}
+
+	     // goto SCAN_GOING; 
+	     goto BAND_CONNECT; 
+
+	}
+	else if( SystemManager.DevType == DEV_EMG_BUTTON )
+	{	
+	
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BUTTON\n");
+
+		ISCPacket = 1;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			SystemManager.LedBlinkRun = 1;
+			SystemManager.LedBlinkTimer = 5000;
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			SystemManager.DevType = 0;
+			//ISCPacket = 0;  
+		}
+
+		//return;
+	}
+	else if( SystemManager.DevType == DEV_EMG_BAND )
+	{
+
+		NRF_LOG_RAW_INFO("=================  DEV_EMG_BAND\n");
+
+		ISCPacket = 2;
+		//if( SystemManager.LedBlinkTimer < 0 )
+		{
+
+			//SystemManager.LedBlinkRun = 1;
+			//SystemManager.LedBlinkTimer = 5000;
+			//SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			//SystemManager.DevType = 0;
+		}
+  
+		//return;
+	}
+  
+
+	if( ISCPacket == 1)
+	{
+		int i;
+
+		if( FindRegMac(ScanHSBuff) == 0 )
+		{
+
+			scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+			scan_evt.params.p_not_found = p_adv_report;
+
+			// If the event handler is not NULL, notify the main application.
+			if (p_scan_ctx->evt_handler != NULL)
+			{
+			  	//p_scan_ctx->evt_handler(&scan_evt);
+			}
+
+			// Resume the scanning.
+			UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+			ISCPacket = 0;
+
+			if( SystemManager.RegRequst == 0 )	// 등록모드가 아니면 
+				return;
+		}
+
+		 //NRF_LOG_RAW_INFO("================= Emergency\n");
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+
+
+	}
+	else if( ISCPacket == 2)
+	{
+		int i;
+
+//		NRF_LOG_RAW_INFO("================= Emergency\n");
+
+		for( i=0; i<6; i++)
+		{
+			NRF_LOG_RAW_INFO("%02x ", p_adv_report->peer_addr.addr[i]);
+		}
+		NRF_LOG_RAW_INFO("\n");
+
+		ISCPacket = 0;  
+ 	}else{
+
+
+SCAN_GOING:
+
+		scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_NOT_FOUND;
+		scan_evt.params.p_not_found = p_adv_report;
+
+		// If the event handler is not NULL, notify the main application.
+		if (p_scan_ctx->evt_handler != NULL)
+		{
+		  //p_scan_ctx->evt_handler(&scan_evt);
+		}
+
+		// Resume the scanning.
+		UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+		ISCPacket = 0;
+
+		return;  
+	}
+    
+
+BAND_CONNECT:
+    // If the whitelist is used, do not check the filters and return.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT;
+        scan_evt.params.p_not_found = p_adv_report;
+        p_scan_ctx->evt_handler(&scan_evt);
+
+        UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+
+        return;
+    }
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    bool const all_filter_mode   = p_scan_ctx->scan_filters.all_filters_mode;
+    bool       is_filter_matched = false;
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    bool const addr_filter_enabled = p_scan_ctx->scan_filters.addr_filter.addr_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    bool const name_filter_enabled = p_scan_ctx->scan_filters.name_filter.name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    bool const short_name_filter_enabled =
+        p_scan_ctx->scan_filters.short_name_filter.short_name_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    bool const uuid_filter_enabled = p_scan_ctx->scan_filters.uuid_filter.uuid_filter_enabled;
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    bool const appearance_filter_enabled =
+        p_scan_ctx->scan_filters.appearance_filter.appearance_filter_enabled;
+#endif
+
+
+#if (NRF_BLE_SCAN_ADDRESS_CNT > 0)
+    // Check the address filter.
+    if (addr_filter_enabled)
+    {
+        // Number of active filters.
+        filter_cnt++;
+        if (adv_addr_compare(p_adv_report, p_scan_ctx))
+        {
+            // Number of filters matched.
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.address_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_NAME_CNT > 0)
+    // Check the name filter.
+    if (name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_SHORT_NAME_CNT > 0)
+    if (short_name_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_short_name_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.short_name_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_UUID_CNT > 0)
+    // Check the UUID filter.
+    if (uuid_filter_enabled)
+    {
+        filter_cnt++;
+        //if (adv_uuid_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.uuid_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+#endif
+
+#if (NRF_BLE_SCAN_APPEARANCE_CNT > 0)
+    // Check the appearance filter.
+    if (appearance_filter_enabled)
+    {
+        filter_cnt++;
+        if (adv_appearance_compare(p_adv_report, p_scan_ctx))
+        {
+            filter_match_cnt++;
+            // Information about the filters matched.
+            scan_evt.params.filter_match.filter_match.appearance_filter_match = true;
+            is_filter_matched = true;
+        }
+    }
+
+    scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+#endif
+
+    scan_evt.params.filter_match.p_adv_report = p_adv_report;
+
+    // In the multifilter mode, the number of the active filters must equal the number of the filters matched to generate the notification.
+    if (all_filter_mode && (filter_match_cnt == filter_cnt))
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    // In the normal filter mode, only one filter match is needed to generate the notification to the main application.
+    else if ((!all_filter_mode) && is_filter_matched)
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_FILTER_MATCH;
+        nrf_ble_scan_connect_with_target(p_scan_ctx, p_adv_report);
+    }
+    else
+    {
+        scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_NOT_FOUND;
+        scan_evt.params.p_not_found = p_adv_report;
+    }
+
+    // If the event handler is not NULL, notify the main application.
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+
+#endif // NRF_BLE_SCAN_FILTER_ENABLE
+
+    // Resume the scanning.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
+}
+
+
+
+
+
+/**@brief Function for checking whether the whitelist is used.
+ *
+ * @param[in] p_scan_ctx   Scanning Module instance.
+ */
+bool is_whitelist_used(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    if (p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST ||
+        p_scan_ctx->scan_params.filter_policy == BLE_GAP_SCAN_FP_WHITELIST_NOT_RESOLVED_DIRECTED)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+
+
+
+
+/**@brief Function for restoring the default scanning parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    // Set the default parameters.
+    p_scan_ctx->scan_params.active        = 1;
+#if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.interval_us   = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS;
+    p_scan_ctx->scan_params.window_us     = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS;
+#else
+    p_scan_ctx->scan_params.interval      = NRF_BLE_SCAN_SCAN_INTERVAL;
+    p_scan_ctx->scan_params.window        = NRF_BLE_SCAN_SCAN_WINDOW;
+#endif // #if (NRF_SD_BLE_API_VERSION > 7)
+    p_scan_ctx->scan_params.timeout       = NRF_BLE_SCAN_SCAN_DURATION;
+    p_scan_ctx->scan_params.filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
+    p_scan_ctx->scan_params.scan_phys     = BLE_GAP_PHY_1MBPS;
+}
+
+
+/**@brief Function for setting the default connection parameters.
+ *
+ * @param[out] p_scan_ctx    Pointer to the Scanning Module instance.
+ */
+static void nrf_ble_scan_default_conn_param_set(nrf_ble_scan_t * const p_scan_ctx)
+{
+    p_scan_ctx->conn_params.conn_sup_timeout =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_SUPERVISION_TIMEOUT, UNIT_10_MS);
+    p_scan_ctx->conn_params.min_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MIN_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.max_conn_interval =
+        (uint16_t)MSEC_TO_UNITS(NRF_BLE_SCAN_MAX_CONNECTION_INTERVAL, UNIT_1_25_MS);
+    p_scan_ctx->conn_params.slave_latency =
+        (uint16_t)NRF_BLE_SCAN_SLAVE_LATENCY;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_TIMEOUT event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap       GAP event structure.
+ */
+static void nrf_ble_scan_on_timeout(nrf_ble_scan_t const * const p_scan_ctx,
+                                    ble_gap_evt_t  const * const p_gap)
+{
+    ble_gap_evt_timeout_t const * p_timeout = &p_gap->params.timeout;
+    scan_evt_t                    scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    if (p_timeout->src == BLE_GAP_TIMEOUT_SRC_SCAN)
+    {
+        NRF_LOG_DEBUG("BLE_GAP_SCAN_TIMEOUT");
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id        = NRF_BLE_SCAN_EVT_SCAN_TIMEOUT;
+            scan_evt.p_scan_params      = &p_scan_ctx->scan_params;
+            scan_evt.params.timeout.src = p_timeout->src;
+
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+}
+
+
+/**@brief Function for stopping the scanning.
+ */
+void nrf_ble_scan_stop(void)
+{
+    // It is ok to ignore the function return value here, because this function can return NRF_SUCCESS or
+    // NRF_ERROR_INVALID_STATE, when app is not in the scanning state.
+    UNUSED_RETURN_VALUE(sd_ble_gap_scan_stop());
+}
+
+
+ret_code_t nrf_ble_scan_init(nrf_ble_scan_t            * const p_scan_ctx,
+                             nrf_ble_scan_init_t const * const p_init,
+                             nrf_ble_scan_evt_handler_t        evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    p_scan_ctx->evt_handler = evt_handler;
+
+#if (NRF_BLE_SCAN_FILTER_ENABLE == 1)
+    // Disable all scanning filters.
+    memset(&p_scan_ctx->scan_filters, 0, sizeof(p_scan_ctx->scan_filters));
+#endif
+
+    // If the pointer to the initialization structure exist, use it to scan the configuration.
+    if (p_init != NULL)
+    {
+        p_scan_ctx->connect_if_match = p_init->connect_if_match;
+        p_scan_ctx->conn_cfg_tag     = p_init->conn_cfg_tag;
+
+        if (p_init->p_scan_param != NULL)
+        {
+            p_scan_ctx->scan_params = *p_init->p_scan_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_param_set(p_scan_ctx);
+        }
+
+        if (p_init->p_conn_param != NULL)
+        {
+            p_scan_ctx->conn_params = *p_init->p_conn_param;
+        }
+        else
+        {
+            // Use the default static configuration.
+            nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+        }
+    }
+    // If pointer is NULL, use the static default configuration.
+    else
+    {
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+        nrf_ble_scan_default_conn_param_set(p_scan_ctx);
+
+        p_scan_ctx->connect_if_match = false;
+    }
+
+    // Assign a buffer where the advertising reports are to be stored by the SoftDevice.
+    p_scan_ctx->scan_buffer.p_data = p_scan_ctx->scan_buffer_data;
+    p_scan_ctx->scan_buffer.len    = NRF_BLE_SCAN_BUFFER;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_start(nrf_ble_scan_t const * const p_scan_ctx)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    ret_code_t err_code;
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+
+    nrf_ble_scan_stop();
+
+    // If the whitelist is used and the event handler is not NULL, send the whitelist request to the main application.
+    if (is_whitelist_used(p_scan_ctx))
+    {
+        if (p_scan_ctx->evt_handler != NULL)
+        {
+            scan_evt.scan_evt_id = NRF_BLE_SCAN_EVT_WHITELIST_REQUEST;
+            p_scan_ctx->evt_handler(&scan_evt);
+        }
+    }
+
+    // Start the scanning.
+    err_code = sd_ble_gap_scan_start(&p_scan_ctx->scan_params, &p_scan_ctx->scan_buffer);
+
+    // It is okay to ignore this error, because the scan stopped earlier.
+    if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_SUCCESS))
+    {
+        NRF_LOG_ERROR("sd_ble_gap_scan_start returned 0x%x", err_code);
+        return (err_code);
+    }
+    NRF_LOG_DEBUG("Scanning");
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_ble_scan_params_set(nrf_ble_scan_t              * const p_scan_ctx,
+                                   ble_gap_scan_params_t const * const p_scan_param)
+{
+    VERIFY_PARAM_NOT_NULL(p_scan_ctx);
+
+    nrf_ble_scan_stop();
+
+    if (p_scan_param != NULL)
+    {
+        // Assign new scanning parameters.
+        p_scan_ctx->scan_params = *p_scan_param;
+    }
+    else
+    {
+        // If NULL, use the default static configuration.
+        nrf_ble_scan_default_param_set(p_scan_ctx);
+    }
+
+    NRF_LOG_DEBUG("Scanning parameters have been changed successfully");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for calling the BLE_GAP_EVT_CONNECTED event.
+ *
+ * @param[in] p_scan_ctx  Pointer to the Scanning Module instance.
+ * @param[in] p_gap_evt   GAP event structure.
+ */
+static void nrf_ble_scan_on_connected_evt(nrf_ble_scan_t const * const p_scan_ctx,
+                                          ble_gap_evt_t  const * const p_gap_evt)
+{
+    scan_evt_t scan_evt;
+
+    memset(&scan_evt, 0, sizeof(scan_evt));
+    scan_evt.scan_evt_id                  = NRF_BLE_SCAN_EVT_CONNECTED;
+    scan_evt.params.connected.p_connected = &p_gap_evt->params.connected;
+    scan_evt.params.connected.conn_handle = p_gap_evt->conn_handle;
+    scan_evt.p_scan_params                = &p_scan_ctx->scan_params;
+
+    if (p_scan_ctx->evt_handler != NULL)
+    {
+        p_scan_ctx->evt_handler(&scan_evt);
+    }
+}
+
+
+ret_code_t nrf_ble_scan_copy_addr_to_sd_gap_addr(ble_gap_addr_t * p_gap_addr,
+                                                 const uint8_t    addr[BLE_GAP_ADDR_LEN])
+{
+    uint16_t addr_type;
+
+    addr_type = nrf_ble_scan_address_type_decode(addr);
+
+    if (addr_type == BLE_ERROR_GAP_INVALID_BLE_ADDR)
+    {
+        return BLE_ERROR_GAP_INVALID_BLE_ADDR;
+    }
+
+    p_gap_addr->addr_type = addr_type;
+
+    for (uint8_t i = 0; i < BLE_GAP_ADDR_LEN; ++i)
+    {
+        p_gap_addr->addr[i] = addr[BLE_GAP_ADDR_LEN - (i + 1)];
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+void nrf_ble_scan_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_contex)
+{
+    nrf_ble_scan_t                 * p_scan_data  = (nrf_ble_scan_t *)p_contex;
+    ble_gap_evt_adv_report_t const * p_adv_report = &p_ble_evt->evt.gap_evt.params.adv_report;
+    ble_gap_evt_t const            * p_gap_evt    = &p_ble_evt->evt.gap_evt;
+
+    switch (p_ble_evt->header.evt_id)
+    {
+
+#if 1
+        case BLE_GAP_EVT_DISCONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DISCONNECTED \n" );
+            break;
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE \n" );
+            break;
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_PARAMS_REQUEST \n" );
+            break;
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_INFO_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PASSKEY_DISPLAY \n" );
+            break;
+        
+        case BLE_GAP_EVT_KEY_PRESSED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_KEY_PRESSED \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_KEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_AUTH_STATUS:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_AUTH_STATUS \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE \n" );
+            break;
+        
+        case BLE_GAP_EVT_RSSI_CHANGED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_RSSI_CHANGED \n" );
+            break;
+ 
+       
+        case BLE_GAP_EVT_SEC_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SEC_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST \n" );
+            break;
+
+        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_PHY_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_PHY_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST \n" );
+            break;
+        
+        case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_DATA_LENGTH_UPDATE \n" );
+            break;
+
+        case BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT \n" );
+            break;
+        
+        case BLE_GAP_EVT_ADV_SET_TERMINATED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_ADV_SET_TERMINATED \n" );
+            break;
+
+
+#endif
+
+
+
+
+        case BLE_GAP_EVT_SCAN_REQ_REPORT:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT \n" );
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT:
+            //NRF_LOG_RAW_INFO("===BLE_GAP_EVT_ADV_REPORT \n" );
+            nrf_ble_scan_on_adv_report(p_scan_data, p_adv_report);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            nrf_ble_scan_on_timeout(p_scan_data, p_gap_evt);
+            break;
+
+        case BLE_GAP_EVT_CONNECTED:
+            NRF_LOG_RAW_INFO("BLE_GAP_EVT_CONNECTED \n" );
+            nrf_ble_scan_on_connected_evt(p_scan_data, p_gap_evt);
+            break;
+
+        default:
+            break;
+    }
+}
+
+
+#endif // NRF_BLE_SCAN_ENABLED
+

+ 305 - 0
BLE_Central.si4project/Backup/nrf_sdh(5646).h

@@ -0,0 +1,305 @@
+/**
+ * Copyright (c) 2017 - 2020, 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 nrf_sdh SoftDevice Handler
+ * @{
+ * @ingroup  app_common
+ * @brief    API for initializing and disabling the SoftDevice.
+ */
+
+#ifndef NRF_SDH_H__
+#define NRF_SDH_H__
+
+#include <stdbool.h>
+#include "sdk_config.h"
+#include "sdk_errors.h"
+#include "nrf_section_iter.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @name Softdevice Handler dispatch models
+ * @{
+ * @ingroup  nrf_sdh */
+
+/**@brief   SoftDevice events are passed to the application from the interrupt context. */
+#define NRF_SDH_DISPATCH_MODEL_INTERRUPT  0
+
+/**@brief   SoftDevice events are passed to the application using @ref app_scheduler.
+ *
+ * @note    @ref app_scheduler must be initialized before enabling the SoftDevice handler.
+ */
+#define NRF_SDH_DISPATCH_MODEL_APPSH      1
+
+/**@brief   SoftDevice events are polled manually using @ref nrf_sdh_evts_poll().
+ *
+ * @note    In this mode, a user application can also implement SD_EVT_IRQHandler() to receive a
+ *          notification about incoming events.
+ */
+#define NRF_SDH_DISPATCH_MODEL_POLLING    2
+
+/** @} */
+
+/**
+ * @name SoftDevice Handler state change requests
+ * @{
+ * @ingroup  nrf_sdh */
+
+/**@brief   SoftDevice Handler state requests. */
+typedef enum
+{
+    NRF_SDH_EVT_ENABLE_REQUEST,     //!< Request to enable the SoftDevice.
+    NRF_SDH_EVT_DISABLE_REQUEST,    //!< Request to disable the SoftDevice.
+} nrf_sdh_req_evt_t;
+
+/**@brief   SoftDevice Handler state request handler.
+ *
+ * @retval  true    If ready for the SoftDevice to change state.
+ * @retval  false   If not ready for the SoftDevice to change state.
+ *                  If false is returned, the state change is aborted.
+ */
+typedef bool (*nrf_sdh_req_evt_handler_t)(nrf_sdh_req_evt_t request, void * p_context);
+
+/**@brief   SoftDevice Handler state request observer. */
+typedef struct
+{
+    nrf_sdh_req_evt_handler_t handler;      //!< Request handler.
+    void *                    p_context;    //!< A parameter to the handler function.
+} const nrf_sdh_req_observer_t;
+
+/**@brief   Macro for registering a SoftDevice state change request observer.
+ *
+ * An observer of SoftDevice state change requests receives requests to change the state of the
+ * SoftDevice from enabled to disabled and vice versa. These requests may or may not be acknowledged
+ * by the observer, depending on the value returned by its request handler function. Thus, a
+ * request observer has the capability to defer the change of state of the SoftDevice. If it does
+ * so, it has the responsibility to call @ref nrf_sdh_request_continue when it is ready to let the
+ * SoftDevice change its state. If such capability is not necessary and you only need to be informed
+ * about changes of the SoftDevice state, use the @ref NRF_SDH_STATE_OBSERVER macro instead.
+ *
+ * @note    This macro places the observer in a section named "sdh_req_observers".
+ *
+ * @param[in]   _observer   Name of the observer.
+ * @param[in]   _prio       Priority of the observer's event handler.
+ *                          The smaller the number, the higher the priority.
+ * @hideinitializer
+ */
+#define NRF_SDH_REQUEST_OBSERVER(_observer, _prio)                                                  \
+STATIC_ASSERT(NRF_SDH_ENABLED, "NRF_SDH_ENABLED not set!");                                         \
+STATIC_ASSERT(_prio < NRF_SDH_REQ_OBSERVER_PRIO_LEVELS, "Priority level unavailable.");             \
+/*lint -esym(528,*_observer) -esym(529,*_observer) : Symbol not referenced. */                      \
+NRF_SECTION_SET_ITEM_REGISTER(sdh_req_observers, _prio, nrf_sdh_req_observer_t const _observer)
+
+/** @} */
+
+/**
+ * @name SoftDevice Handler state events
+ * @{
+ * @ingroup  nrf_sdh */
+
+/**@brief   SoftDevice Handler state events. */
+typedef enum
+{
+    NRF_SDH_EVT_STATE_ENABLE_PREPARE,   //!< SoftDevice is going to be enabled.
+    NRF_SDH_EVT_STATE_ENABLED,          //!< SoftDevice is enabled.
+    NRF_SDH_EVT_STATE_DISABLE_PREPARE,  //!< SoftDevice is going to be disabled.
+    NRF_SDH_EVT_STATE_DISABLED,         //!< SoftDevice is disabled.
+} nrf_sdh_state_evt_t;
+
+/**@brief   SoftDevice Handler state event handler. */
+typedef void (*nrf_sdh_state_evt_handler_t)(nrf_sdh_state_evt_t state, void * p_context);
+
+/**@brief   SoftDevice Handler state observer. */
+typedef struct
+{
+    nrf_sdh_state_evt_handler_t   handler;      //!< State event handler.
+    void                        * p_context;    //!< A parameter to the event handler.
+} const nrf_sdh_state_observer_t;
+
+/**@brief   Macro for registering a SoftDevice state observer.
+ *
+ * A SoftDevice state observer receives events when the SoftDevice state has changed or is
+ * about to change. These events are only meant to inform the state observer, which, contrary
+ * to a state change request observer, does not have the capability to defer the change of state.
+ * If such capability is required, use the @ref NRF_SDH_REQUEST_OBSERVER macro instead.
+ *
+ *  This macro places the observer in a section named "sdh_state_observers".
+ *
+ * @param[in]   _observer   Name of the observer.
+ * @param[in]   _prio       Priority of the observer's event handler.
+ *                          The smaller the number, the higher the priority.
+ * @hideinitializer
+ */
+#define NRF_SDH_STATE_OBSERVER(_observer, _prio)                                                           \
+STATIC_ASSERT(NRF_SDH_ENABLED, "NRF_SDH_ENABLED not set!");                                                \
+STATIC_ASSERT(_prio < NRF_SDH_STATE_OBSERVER_PRIO_LEVELS, "Priority level unavailable.");                  \
+/*lint -esym(528,*_observer) -esym(529,*_observer) : Symbol not referenced. */                             \
+NRF_SECTION_SET_ITEM_REGISTER(sdh_state_observers, _prio, static nrf_sdh_state_observer_t const _observer)
+
+/** @} */
+
+/**
+ * @name SoftDevice stack events
+ * @{
+ * @ingroup  nrf_sdh */
+
+/**@brief   SoftDevice stack event handler. */
+typedef void (*nrf_sdh_stack_evt_handler_t)(void * p_evt);
+
+/**@brief   SoftDevice stack event observer. */
+typedef struct
+{
+    nrf_sdh_stack_evt_handler_t handler;    //!< SoftDevice event handler.
+    void *                      p_context;  //!< A parameter to the event handler.
+} const nrf_sdh_stack_observer_t;
+
+/**@brief   Macro for registering a SoftDevice stack events observer.
+ *
+ * A SoftDevice stack event observer receives all events from the SoftDevice. These events can be
+ * either BLE, ANT, or SoC events. If you need to receive BLE, ANT, or SoC events separately, use the
+ * @ref NRF_SDH_BLE_OBSERVER, @ref NRF_SDH_ANT_OBSERVER, or @ref NRF_SDH_SOC_OBSERVER macros
+ * respectively.
+ *
+ * @note    This macro places the observer in a section named "sdh_stack_observers".
+ *
+ * @param[in]   _observer   Name of the observer.
+ * @param[in]   _prio       Priority of the observer's event handler.
+ *                          The smaller the number, the higher the priority.
+ ** @hideinitializer
+ */
+#define NRF_SDH_STACK_OBSERVER(_observer, _prio)                                                          \
+STATIC_ASSERT(NRF_SDH_ENABLED, "NRF_SDH_ENABLED not set!");                                               \
+STATIC_ASSERT(_prio < NRF_SDH_STACK_OBSERVER_PRIO_LEVELS, "Priority level unavailable.");                 \
+/*lint -esym(528,*_observer) -esym(529,*_observer) : Symbol not referenced. */                            \
+NRF_SECTION_SET_ITEM_REGISTER(sdh_stack_observers, _prio, static nrf_sdh_stack_observer_t const _observer)
+
+/** @} */
+
+/**@brief   Function for requesting to enable the SoftDevice.
+ *
+ * This function issues a @ref NRF_SDH_EVT_ENABLE_REQUEST request to all observers that
+ * were registered using the @ref NRF_SDH_REQUEST_OBSERVER macro. The observers may or
+ * may not acknowledge the request. If all observers acknowledge the request, the
+ * SoftDevice will be enabled. Otherwise, the process will be stopped and the observers
+ * that did not acknowledge have the responsibility to restart it by calling
+ * @ref nrf_sdh_request_continue when they are ready for the SoftDevice to change state.
+ *
+ * @retval  NRF_SUCCESS                 The process is started.
+ * @retval  NRF_ERROR_INVALID_STATE     The SoftDevice is already enabled.
+ */
+ret_code_t nrf_sdh_enable_request(void);
+
+
+/**@brief   Function for requesting to disable the SoftDevice.
+ *
+ * This function issues a @ref NRF_SDH_EVT_DISABLE_REQUEST request to all observers that
+ * were registered using the @ref NRF_SDH_REQUEST_OBSERVER macro. The observers may or
+ * may not acknowledge the request. If all observers acknowledge the request, the
+ * SoftDevice will be disabled. Otherwise, the process will be stopped and the observers
+ * that did not acknowledge have the responsibility to restart it by calling
+ * @ref nrf_sdh_request_continue when they are ready for the SoftDevice to change state.
+ *
+ * @retval  NRF_SUCCESS                 The process is started.
+ * @retval  NRF_ERROR_INVALID_STATE     The SoftDevice is already disabled.
+ */
+ret_code_t nrf_sdh_disable_request(void);
+
+
+/**@brief   Function for restarting the SoftDevice Enable/Disable process.
+ *
+ * Modules which did not acknowledge a @ref NRF_SDH_EVT_ENABLE_REQUEST or
+ * @ref NRF_SDH_EVT_DISABLE_REQUEST request must call this function to restart the
+ * SoftDevice state change process.
+ *
+ * @retval  NRF_SUCCESS                 The process is restarted.
+ * @retval  NRF_ERROR_INVALID_STATE     No state change request was pending.
+ */
+ret_code_t nrf_sdh_request_continue(void);
+
+
+/**@brief   Function for retrieving the SoftDevice state.
+ *
+ * @retval  true    If the SoftDevice is enabled.
+ * @retval  false   If the SoftDevice is disabled.
+ */
+bool nrf_sdh_is_enabled(void);
+
+
+/**@brief   Function for stopping the incoming stack events.
+ *
+ * This function disables the SoftDevice interrupt. To resume polling for events,
+ * call @ref nrf_sdh_resume.
+ */
+void nrf_sdh_suspend(void);
+
+
+/**@brief   Function for resuming polling incoming events from the SoftDevice. */
+void nrf_sdh_resume(void);
+
+
+/**@brief   Function for retrieving the information about the module state.
+ *
+ * @retval  true    The SoftDevice handler is paused, and it will not fetch events from the stack.
+ * @retval  false   The SoftDevice handler is running, and it will fetch and dispatch events from
+ *                  the stack to the registered stack observers.
+ */
+bool nrf_sdh_is_suspended(void);
+
+
+/**@brief   Function for polling stack events from the SoftDevice.
+ *
+ * The events are passed to the application using the registered event handlers.
+ *
+ * @note    @ref NRF_SDH_DISPATCH_MODEL_POLLING must be selected to use this function.
+ */
+void nrf_sdh_evts_poll(void);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // NRF_SDH_H__
+
+/** @} */

+ 402 - 0
BLE_Central.si4project/Backup/nrf_sdh(7960).c

@@ -0,0 +1,402 @@
+/**
+ * Copyright (c) 2017 - 2020, 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(NRF_SDH)
+
+#include "nrf_sdh.h"
+
+#include <stdint.h>
+
+#include "nrf_sdm.h"
+#include "nrf_nvic.h"
+#include "sdk_config.h"
+#include "app_error.h"
+#include "app_util_platform.h"
+
+
+#define NRF_LOG_MODULE_NAME nrf_sdh
+#if NRF_SDH_LOG_ENABLED
+    #define NRF_LOG_LEVEL       NRF_SDH_LOG_LEVEL
+    #define NRF_LOG_INFO_COLOR  NRF_SDH_INFO_COLOR
+    #define NRF_LOG_DEBUG_COLOR NRF_SDH_DEBUG_COLOR
+#else
+    #define NRF_LOG_LEVEL       0
+#endif // NRF_SDH_LOG_ENABLED
+#include "nrf_log.h"
+NRF_LOG_MODULE_REGISTER();
+
+
+// Validate configuration options.
+
+#if (NRF_SDH_DISPATCH_MODEL == NRF_SDH_DISPATCH_MODEL_APPSH)
+    #if (!APP_SCHEDULER_ENABLED)
+        #error app_scheduler is required when NRF_SDH_DISPATCH_MODEL is set to NRF_SDH_DISPATCH_MODEL_APPSH
+    #endif
+    #include "app_scheduler.h"
+#endif
+
+#if (   (NRF_SDH_CLOCK_LF_SRC      == NRF_CLOCK_LF_SRC_RC)          \
+     && (NRF_SDH_CLOCK_LF_ACCURACY != NRF_CLOCK_LF_ACCURACY_500_PPM))
+    #warning Please select NRF_CLOCK_LF_ACCURACY_500_PPM when using NRF_CLOCK_LF_SRC_RC
+#endif
+
+
+// Create section "sdh_req_observers".
+NRF_SECTION_SET_DEF(sdh_req_observers, nrf_sdh_req_observer_t, NRF_SDH_REQ_OBSERVER_PRIO_LEVELS);
+
+// Create section "sdh_state_observers".
+NRF_SECTION_SET_DEF(sdh_state_observers, nrf_sdh_state_observer_t, NRF_SDH_STATE_OBSERVER_PRIO_LEVELS);
+
+// Create section "sdh_stack_observers".
+NRF_SECTION_SET_DEF(sdh_stack_observers, nrf_sdh_stack_observer_t, NRF_SDH_STACK_OBSERVER_PRIO_LEVELS);
+
+
+static bool m_nrf_sdh_enabled;   /**< Variable to indicate whether the SoftDevice is enabled. */
+static bool m_nrf_sdh_suspended; /**< Variable to indicate whether this module is suspended. */
+static bool m_nrf_sdh_continue;  /**< Variable to indicate whether enable/disable process was started. */
+
+
+/**@brief   Function for notifying request observers.
+ *
+ * @param[in]   evt     Type of request event.
+ */
+static ret_code_t sdh_request_observer_notify(nrf_sdh_req_evt_t req)
+{
+    nrf_section_iter_t iter;
+
+    NRF_LOG_DEBUG("State request: 0x%08X", req);
+
+    for (nrf_section_iter_init(&iter, &sdh_req_observers);
+         nrf_section_iter_get(&iter) != NULL;
+         nrf_section_iter_next(&iter))
+    {
+        nrf_sdh_req_observer_t    * p_observer;
+        nrf_sdh_req_evt_handler_t   handler;
+
+        p_observer = (nrf_sdh_req_observer_t *) nrf_section_iter_get(&iter);
+        handler    = p_observer->handler;
+
+        if (handler(req, p_observer->p_context))
+        {
+            NRF_LOG_DEBUG("Notify observer 0x%08X => ready", p_observer);
+        }
+        else
+        {
+            // Process is stopped.
+            NRF_LOG_DEBUG("Notify observer 0x%08X => blocking", p_observer);
+            return NRF_ERROR_BUSY;
+        }
+    }
+    return NRF_SUCCESS;
+}
+
+
+/**@brief   Function for stage request observers.
+ *
+ * @param[in]   evt Type of stage event.
+ */
+static void sdh_state_observer_notify(nrf_sdh_state_evt_t evt)
+{
+    nrf_section_iter_t iter;
+
+    NRF_LOG_DEBUG("State change: 0x%08X", evt);
+
+    for (nrf_section_iter_init(&iter, &sdh_state_observers);
+         nrf_section_iter_get(&iter) != NULL;
+         nrf_section_iter_next(&iter))
+    {
+        nrf_sdh_state_observer_t    * p_observer;
+        nrf_sdh_state_evt_handler_t   handler;
+
+        p_observer = (nrf_sdh_state_observer_t *) nrf_section_iter_get(&iter);
+        handler    = p_observer->handler;
+
+        handler(evt, p_observer->p_context);
+    }
+}
+
+
+static void softdevices_evt_irq_enable(void)
+{
+#ifdef SOFTDEVICE_PRESENT
+    ret_code_t ret_code = sd_nvic_EnableIRQ((IRQn_Type)SD_EVT_IRQn);
+    APP_ERROR_CHECK(ret_code);
+#else
+    // In case of serialization, NVIC must be accessed directly.
+    NVIC_EnableIRQ(SD_EVT_IRQn);
+#endif
+}
+
+
+static void softdevice_evt_irq_disable(void)
+{
+#ifdef SOFTDEVICE_PRESENT
+    ret_code_t ret_code = sd_nvic_DisableIRQ((IRQn_Type)SD_EVT_IRQn);
+    APP_ERROR_CHECK(ret_code);
+#else
+    // In case of serialization, NVIC must be accessed directly.
+    NVIC_DisableIRQ(SD_EVT_IRQn);
+#endif
+}
+
+
+ret_code_t nrf_sdh_enable_request(void)
+{
+    ret_code_t ret_code;
+
+    if (m_nrf_sdh_enabled)
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    m_nrf_sdh_continue = true;
+
+    // Notify observers about SoftDevice enable request.
+    if (sdh_request_observer_notify(NRF_SDH_EVT_ENABLE_REQUEST) == NRF_ERROR_BUSY)
+    {
+        // Enable process was stopped.
+        return NRF_SUCCESS;
+    }
+
+    // Notify observers about starting SoftDevice enable process.
+    sdh_state_observer_notify(NRF_SDH_EVT_STATE_ENABLE_PREPARE);
+
+    nrf_clock_lf_cfg_t const clock_lf_cfg =
+    {
+        .source       = NRF_SDH_CLOCK_LF_SRC,
+        .rc_ctiv      = NRF_SDH_CLOCK_LF_RC_CTIV,
+        .rc_temp_ctiv = NRF_SDH_CLOCK_LF_RC_TEMP_CTIV,
+        .accuracy     = NRF_SDH_CLOCK_LF_ACCURACY
+    };
+
+    CRITICAL_REGION_ENTER();
+#ifdef ANT_LICENSE_KEY
+    ret_code = sd_softdevice_enable(&clock_lf_cfg, app_error_fault_handler, ANT_LICENSE_KEY);
+#else
+    ret_code = sd_softdevice_enable(&clock_lf_cfg, app_error_fault_handler);
+#endif
+    m_nrf_sdh_enabled = (ret_code == NRF_SUCCESS);
+    CRITICAL_REGION_EXIT();
+
+    if (ret_code != NRF_SUCCESS)
+    {
+        return ret_code;
+    }
+
+    m_nrf_sdh_continue  = false;
+    m_nrf_sdh_suspended = false;
+
+    // Enable event interrupt.
+    // Interrupt priority has already been set by the stack.
+    softdevices_evt_irq_enable();
+
+    // Notify observers about a finished SoftDevice enable process.
+    sdh_state_observer_notify(NRF_SDH_EVT_STATE_ENABLED);
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_sdh_disable_request(void)
+{
+    ret_code_t ret_code;
+
+    if (!m_nrf_sdh_enabled)
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    m_nrf_sdh_continue = true;
+
+    // Notify observers about SoftDevice disable request.
+    if (sdh_request_observer_notify(NRF_SDH_EVT_DISABLE_REQUEST) == NRF_ERROR_BUSY)
+    {
+        // Disable process was stopped.
+        return NRF_SUCCESS;
+    }
+
+    // Notify observers about starting SoftDevice disable process.
+    sdh_state_observer_notify(NRF_SDH_EVT_STATE_DISABLE_PREPARE);
+
+    CRITICAL_REGION_ENTER();
+    ret_code          = sd_softdevice_disable();
+    m_nrf_sdh_enabled = false;
+    CRITICAL_REGION_EXIT();
+
+    if (ret_code != NRF_SUCCESS)
+    {
+        return ret_code;
+    }
+
+    m_nrf_sdh_continue = false;
+
+    softdevice_evt_irq_disable();
+
+    // Notify observers about a finished SoftDevice enable process.
+    sdh_state_observer_notify(NRF_SDH_EVT_STATE_DISABLED);
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t nrf_sdh_request_continue(void)
+{
+    if (!m_nrf_sdh_continue)
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    if (m_nrf_sdh_enabled)
+    {
+        return nrf_sdh_disable_request();
+    }
+    else
+    {
+        return nrf_sdh_enable_request();
+    }
+}
+
+
+bool nrf_sdh_is_enabled(void)
+{
+    return m_nrf_sdh_enabled;
+}
+
+
+void nrf_sdh_suspend(void)
+{
+    if (!m_nrf_sdh_enabled)
+    {
+        return;
+    }
+
+    softdevice_evt_irq_disable();
+    m_nrf_sdh_suspended = true;
+}
+
+
+void nrf_sdh_resume(void)
+{
+    if ((!m_nrf_sdh_suspended) || (!m_nrf_sdh_enabled))
+    {
+        return;
+    }
+
+    // Force calling ISR again to make sure that events not previously pulled have been processed.
+#ifdef SOFTDEVICE_PRESENT
+    ret_code_t ret_code = sd_nvic_SetPendingIRQ((IRQn_Type)SD_EVT_IRQn);
+    APP_ERROR_CHECK(ret_code);
+#else
+    NVIC_SetPendingIRQ((IRQn_Type)SD_EVT_IRQn);
+#endif
+
+    softdevices_evt_irq_enable();
+
+    m_nrf_sdh_suspended = false;
+}
+
+
+bool nrf_sdh_is_suspended(void)
+{
+    return (!m_nrf_sdh_enabled) || (m_nrf_sdh_suspended);
+}
+
+
+void nrf_sdh_evts_poll(void)
+{
+    nrf_section_iter_t iter;
+
+    // Notify observers about pending SoftDevice event.
+    for (nrf_section_iter_init(&iter, &sdh_stack_observers);
+         nrf_section_iter_get(&iter) != NULL;
+         nrf_section_iter_next(&iter))
+    {
+        nrf_sdh_stack_observer_t    * p_observer;
+        nrf_sdh_stack_evt_handler_t   handler;
+
+        p_observer = (nrf_sdh_stack_observer_t *) nrf_section_iter_get(&iter);
+        handler    = p_observer->handler;
+
+        handler(p_observer->p_context);
+    }
+}
+
+
+#if (NRF_SDH_DISPATCH_MODEL == NRF_SDH_DISPATCH_MODEL_INTERRUPT)
+
+void SD_EVT_IRQHandler(void)
+{
+    nrf_sdh_evts_poll();
+}
+
+#elif (NRF_SDH_DISPATCH_MODEL == NRF_SDH_DISPATCH_MODEL_APPSH)
+
+/**@brief   Function for polling SoftDevice events.
+ *
+ * @note    This function is compatible with @ref app_sched_event_handler_t.
+ *
+ * @param[in]   p_event_data Pointer to the event data.
+ * @param[in]   event_size   Size of the event data.
+ */
+static void appsh_events_poll(void * p_event_data, uint16_t event_size)
+{
+    UNUSED_PARAMETER(p_event_data);
+    UNUSED_PARAMETER(event_size);
+
+    nrf_sdh_evts_poll();
+}
+
+
+void SD_EVT_IRQHandler(void)
+{
+    ret_code_t ret_code = app_sched_event_put(NULL, 0, appsh_events_poll);
+    APP_ERROR_CHECK(ret_code);
+}
+
+#elif (NRF_SDH_DISPATCH_MODEL == NRF_SDH_DISPATCH_MODEL_POLLING)
+
+#else
+
+#error "Unknown SoftDevice handler dispatch model."
+
+#endif // NRF_SDH_DISPATCH_MODEL
+
+#endif // NRF_MODULE_ENABLED(NRF_SDH)

+ 1565 - 0
BLE_Central.si4project/Backup/our_service(1008).c

@@ -0,0 +1,1565 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 <stdint.h>
+#include <string.h>
+#include "nrf_gpio.h"
+#include "our_service.h"
+#include "ble_srv_common.h"
+#include "app_error.h"
+#include "SEGGER_RTT.h"
+#include "board_gpi.h"
+#include "nrf_log.h"
+
+#include "sysmgr.h"
+#include "main.h"
+#include "nrf_power.h"
+
+
+char SvrRxBuffer[100];
+int SvrRxBufferPos;
+char SvrEvent;
+
+
+stSystemTimer SystemTimer;
+stSystemManager SystemManager;
+char SvrSendBuff[50];
+char SvrSendBuff_bak[50];
+
+void delete_all_begin(void);
+
+
+
+void USART_DataCheck()
+{
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SystemManager.RxValild )
+	{
+
+		SvrRxBuffer[SvrRxBufferPos] = 0;
+
+//		printf("[%d]%s\r\n", SvrRxBufferPos, SvrRxBuffer);
+		SystemManager.RxValild = 0;
+
+		if( SvrRxBufferPos == 20 )
+		{
+			SystemManager.RxEvent = 1;
+			NRF_LOG_RAW_INFO("==========================>\n\n");
+		}
+
+		SvrRxBufferPos = 0;
+	}
+
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SvrRxBufferPos )
+	{
+		SystemManager.RxValild = 0;
+		SvrRxBufferPos = 0;
+	}
+
+}
+
+
+void USART_Handler(void)
+{
+
+	char ch;
+	
+	uint8_t cr;
+
+// 	SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	if( app_uart_get(&cr) == NRF_SUCCESS )
+	{
+		SystemManager.RxValild = 1;
+		SvrRxBuffer[SvrRxBufferPos++] = cr;
+		SvrRxBufferPos %= 100;
+		SystemTimer.UART_LAST_RECV_TIMER = 0;
+	}
+}
+
+
+
+
+
+
+/* 이벤트 서버에서 20byte 들어왔을때 */
+
+
+void ParseEventServer()
+{
+
+	int i;
+
+	if( SystemManager.RxEvent == 0 )
+		return;
+
+	SystemManager.RxEvent = 0;
+
+
+	NRF_LOG_RAW_INFO("\n\n");
+	NRF_LOG_RAW_INFO("SERVER TO DATA : ")
+
+	for( i=0; i<20; i++)
+	{
+		NRF_LOG_RAW_INFO("0x%02x ", SvrRxBuffer[i]);
+	}
+	NRF_LOG_RAW_INFO("\n\n");
+
+
+	if(SvrRxBuffer[0] != 0x02)
+		return;
+
+	switch(SvrRxBuffer[1]){
+
+		case NUM_TYPE_SVR:
+		case COM_TYPE_BAND:		//
+
+			switch(SvrRxBuffer[3]){
+
+
+				// 수신기 비상신호에 대한 ACK 신호
+				case COM_TYPE_SVR_EMG_ACK:
+
+					SystemManager.Emg_Ack_Flag = 0;
+
+				break;
+
+
+				// 수신기 대기상태 요청
+				case COM_TYPE_SVR_NORMAL:
+
+					SystemManager.System_State = SYSTEM_NONE;
+
+					NRF_LOG_INFO("Recv : Normal");
+
+					PKLedOff();
+					PKBuzzerOff();
+					PKMicOff();
+					SystemManager.SwitchOn = 0;
+ 
+				break;
+
+				// 수신기 통화상태 요청 
+				case COM_TYPE_SVR_TALKING:
+
+					NRF_LOG_INFO("Recv : Talking");
+
+					PKLedOn();
+					PKBuzzerOff();
+					SystemManager.SwitchOn = 0;
+				break;
+
+				// 수신기 서버와 통화 종료 요청
+				case COM_TYPE_SVR_DISCON:
+					
+					NRF_LOG_INFO("Recv : Disconnect");
+
+					SystemManager.SwitchOn = 0;
+					//bsp_board_leds_off();
+				break;
+
+				// 서버 Busy 상태 알림
+				case COM_TYPE_SVR_BUSY:
+
+					NRF_LOG_INFO("Recv : Busy");
+
+				break;
+
+				// 송신기 Alive신호 서버로 전송
+				case COM_TYPE_SVR_ALIVE:
+
+					NRF_LOG_INFO("Recv : Keep Alive");
+
+				break;
+
+				// 수신기 마이크 상태 변경 요청 
+				case COM_TYPE_SVR_MIC:
+
+					SystemManager.System_State = SYSTEM_SERVER_COMM;
+
+					SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				
+					NRF_LOG_INFO("Recv : mic on/off");
+
+					
+					if( SvrRxBuffer[11] == 0 )
+					{  
+						NRF_LOG_INFO("mic on"); 
+						NRF_LOG_INFO("speaker off");  
+						PKSpeakerOff();
+						PKMicOn();
+						PKBuzzerOff();
+						PKLedOn();
+						SystemManager.SwitchOn = 0;
+					}else{
+						NRF_LOG_INFO("mic off"); 
+						NRF_LOG_INFO("speaker on");  
+						PKMicOff();
+						PKSpeakerOn();
+						PKLedOn();
+					}
+				break;
+
+				// 송신기 등록요청
+				case COM_TYPE_SVR_RECV_REG_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_REG_REQ");
+
+					if(SystemManager.System_State == SYSTEM_NONE){
+
+						SystemManager.System_State = SYSTEM_REGISTER;
+
+						SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_REQ;
+						SystemManager.RegRequst = 1;
+
+//						SendAck(COM_TYPE_SVR_RECV_REG+1);
+						SendAck(COM_TYPE_SVR_RECV_REG_ANSWER);
+
+						SystemTimer.DEV_REG_TIMER = 0;
+					}else{
+						
+						NRF_LOG_INFO("SYSTEM is BUSY : [%d]\n", SystemManager.System_State);
+					}
+
+				break;
+
+				// 송신기 등록 초기화 요청
+				case COM_TYPE_SVR_RECV_INIT_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_INIT_REQ");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_INIT;
+//					SystemManager.LedBlinkTimer = 2500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+					
+//					SendAck(COM_TYPE_SVR_RECV_INIT+1);
+					SendAck(COM_TYPE_SVR_RECV_INIT_ANSWER);
+
+
+					//for( i=0; i<RegMacPool.Count; i++)
+					//{
+					//RegMacDelteAll();
+					// }
+					memset( &RegMacPool, 0, sizeof(RegMacPool));
+
+					delete_all_begin();
+
+					for(i=0; i<2; i++){
+						PKLedOn();
+						nrf_delay_ms(300);
+						PKLedOff();
+						nrf_delay_ms(300);
+					}
+				break;
+
+				// 송신기에 등록된 수신기 리스트 요청 
+				case COM_TYPE_SVR_RECV_LIST_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_LIST_REQ");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_LIST;
+//					SystemManager.LedBlinkTimer = 1500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+
+					Server_Answer_Reg_List();
+
+					PKLedOn();
+					nrf_delay_ms(300);
+					PKLedOff();
+
+				break;
+
+				// 서버로 부터 통화 요청
+				case COM_TYPE_SVR_CALL_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_CALL_REQ");
+
+					Server_Answer_Call();
+
+				break;
+
+				// 서버로 부터 수신기 버전 요청
+				case COM_TYPE_SVR_VER_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_VER_REQ");
+
+					Server_Answer_Version();
+
+				break;
+
+
+				case COM_TYPE_SVR_UPGREAD_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_UPGREAD_REQ");
+					
+					Server_Answer_Upgread();
+
+				break;
+			}
+		break;
+
+//		case COM_TYPE_BAND:
+
+//		break;
+	}
+}
+
+
+
+void SendToEventServer(char* data, int len)
+{
+
+	int i;
+
+	NRF_LOG_RAW_INFO("SendToEventServer ==> ");
+	
+	for( i=0; i<len; i++)
+	{
+		NRF_LOG_RAW_INFO("%02X ", data[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+
+
+	for(i=0; i<len; i++)
+	{
+		while (app_uart_put(data[i]) != NRF_SUCCESS);
+	}
+
+}
+
+
+
+
+
+
+/******************************************************************************
+*
+*			OnePass App --->   송신기 --------> Event Server
+*
+*******************************************************************************/
+
+void SendParkingApp()
+{
+	int i;
+
+	NRF_LOG_RAW_INFO("===> SendParkingApp()\n");
+
+
+  	SystemManager.SwitchOn = 0;
+	SystemManager.LedBlinkRun = COM_TYPE_APP_PARKING;
+	SystemManager.LedBlinkTimer = 1200;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_ONEPASS;
+	
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  1;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	
+	SvrSendBuff[7] =  new_ble_addr.addr[3];		// 수신기 MAC 
+	SvrSendBuff[8] =  new_ble_addr.addr[4];		// 수신기 MAC
+	SvrSendBuff[9] =  new_ble_addr.addr[5];		// 수신기 MAC
+
+	SvrSendBuff[10] =  0x12;
+	SvrSendBuff[11] =  0x74;
+
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //SITE
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //DONG
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //HO
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	for(i=1; i<28; i++){
+		SvrSendBuff[28] = SvrSendBuff[28] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[29] =  COM_ETX;
+
+	NRF_LOG_INFO("SendParkingApp ===");
+	
+//	SendToEventServer(&SvrSendBuff[0], 1);
+//	nrf_delay_ms(500);
+
+	SendToEventServer(&SvrSendBuff[0], 30);
+
+
+//	nrf_delay_ms(2000);		// 중복해서 들어오는 데이타로 인한 연속 동작 방지 
+
+}
+
+
+
+/******************************************************************************
+*
+*			Band --->   송신기 --------> Event Server
+*
+*******************************************************************************/
+
+
+void SendEmergencyBand()
+{
+	int i;
+
+	char tmpStr[10];
+
+	NRF_LOG_RAW_INFO("===> SendEmergencyBand()\n");
+
+	SystemManager.LedBlinkRun = 1;
+	SystemManager.LedBlinkTimer = 5000;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+	SystemManager.DevType = 0;
+	
+	SystemManager.SwitchOn = 1;
+
+	SystemManager.System_State = SYSTEM_EMERGENCY_SIREN;
+	SystemManager.Emg_Ack_Flag = 2;
+
+	PKBuzzerOn();
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_SMART_BAND;
+
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+	
+		strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+	
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+	
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+	
+	}else{						// 없으면 000000 전송
+		
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+	}
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	SvrSendBuff[10] =  0x12;
+	SvrSendBuff[11] =  0x72;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	for(i=1; i<28; i++){
+		SvrSendBuff[28] = SvrSendBuff[28] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[29] =  COM_ETX;
+
+	memcpy(SvrSendBuff_bak, SvrSendBuff, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("SendEmergencyBand===");
+
+
+	SendToEventServer(&SvrSendBuff[0], 30);
+
+
+#if 0
+	//NRF_LOG_RAW_INFO("================= EmergencyBand \n");
+	for( i=0; i<29; i++)
+	{
+		//NRF_LOG_RAW_INFO("%02x ", SvrSendBuff[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+}
+
+
+
+
+void SendParkingBand()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> SendParkingBand()\n");
+
+	SystemManager.DevType = 0;
+	SystemManager.LedBlinkRun = COM_TYPE_BAND_PARKING;
+	SystemManager.LedBlinkTimer = 1200;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+  	SystemManager.SwitchOn = 0;
+
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_SMART_BAND;
+	
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  2;
+
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  0x12;
+	SvrSendBuff[11] =  0x73;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	for(i=1; i<28; i++){
+		SvrSendBuff[28] = SvrSendBuff[28] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[29] =  COM_ETX;
+
+	NRF_LOG_INFO("SendParkingBand ===");
+
+	SendToEventServer(&SvrSendBuff[0], 30);
+
+}
+
+
+
+void ReSendEmergency()
+{
+
+	NRF_LOG_RAW_INFO("===> ReSendEmergency()\n");
+
+	memcpy(SvrSendBuff, SvrSendBuff_bak, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("ReSendEmergency ===");
+	
+	switch(SystemManager.Emg_Ack_Flag){
+
+		case 1:	// 비상벨 EMG
+			SendToEventServer(&SvrSendBuff[0], 20);
+		break;
+
+		case 2:	// 밴드 EMG
+			SendToEventServer(&SvrSendBuff[0], 30);
+		break;
+	}
+}
+
+
+
+
+/******************************************************************************
+*
+*			비상벨 --->   송신기 --------> Event Server
+*
+*******************************************************************************/
+
+void SendAck(uint8_t cmd)
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendAck()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	SvrSendBuff[2] =  0;
+
+	SvrSendBuff[3] =  cmd;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+	
+	SvrSendBuff[11] =  'A';
+	SvrSendBuff[12] =  'C';
+	SvrSendBuff[13] =  'K';
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+void SendEmergency()
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendEmergency()\n");
+
+
+	SystemManager.System_State = SYSTEM_EMERGENCY_SIREN;
+
+	SystemManager.Emg_Ack_Flag = 1;
+
+
+	if( SystemManager.RegRequst == 1 )		// 등록모드일경우 등록모드 해제, 비상모드 전환
+	{
+		SystemManager.RegRequst = 0;
+//			return;
+	}
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.TransferVerHigh;
+	SvrSendBuff[12] =  SystemManager.TransferVerLow;
+	SvrSendBuff[13] =  SystemManager.BatLevel;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	memcpy(SvrSendBuff_bak, SvrSendBuff, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("SendEmergency ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	SystemManager.SwitchOn = 1;
+
+	PKBuzzerOn();
+
+}
+
+
+
+
+void SendAlive()
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendAlive()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_ALIVE;
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.TransferVerHigh;
+	SvrSendBuff[12] =  SystemManager.TransferVerLow;
+	SvrSendBuff[13] =  SystemManager.BatLevel;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendAlive ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+void SendTest()
+{
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendTest()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_TEST;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.TransferVerHigh;
+	SvrSendBuff[12] =  SystemManager.TransferVerLow;
+	SvrSendBuff[13] =  SystemManager.BatLevel;
+
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendTest ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+// 송신기 등록시마다 송신기 데이타 전송 
+void SendCurrentRegDev()
+{
+
+	NRF_LOG_RAW_INFO("===> SendCurrentRegDev()\n");
+
+	uint8_t i;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	nrf_delay_ms(50);
+
+}
+
+
+
+
+// 비상벨 목록 응답.
+void Server_Answer_Reg_List()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+	uint8_t j;
+	
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Reg_List(%d EA)\n", RegMacPool.Count);
+
+
+	if( RegMacPool.Count == 0 )
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(j=1; j<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[j];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x ===== ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		nrf_delay_ms(50);
+
+		return;
+	}	
+
+
+	for( i=0; i<RegMacPool.Count; i++)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+	
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(j=1; j<18; j++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[j];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x =====> ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		SendToEventServer(&SvrSendBuff[0], 20);
+		nrf_delay_ms(200);
+
+	}
+	
+}
+  
+
+
+
+void Server_Answer_Call()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+	uint8_t j;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("Server_Answer_Call()");
+
+	SystemManager.System_State = SYSTEM_SERVER_COMM_REQ;
+
+	if( SystemManager.ServerCon == 0 )
+	{
+		SystemManager.LedBlinkRun = 1;
+		SystemManager.LedBlinkTimer = 5000;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+		SystemManager.DevType = 0;
+
+		SystemManager.SwitchOn = 1;
+
+  		PKBuzzerOn();
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_CALL_ANSWER;
+
+		if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+
+			strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+
+			tmpStr[6] = 0;
+			SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+
+			tmpStr[4] = 0;
+			SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+			
+			tmpStr[2] = 0;
+			SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		}else{						// 없으면 000000 전송
+			
+			SvrSendBuff[4] =  0;
+			SvrSendBuff[5] =  0;
+			SvrSendBuff[6] =  0;
+		}
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+		
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+
+		SvrSendBuff[11] = 0;
+		SvrSendBuff[12] = 0;
+		SvrSendBuff[13] = 0;
+		SvrSendBuff[14] = 0;
+		SvrSendBuff[15] = 0;
+		SvrSendBuff[16] = 0;
+		SvrSendBuff[17] = 0;
+		
+		for(j=1; j<18; j++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[j];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+		
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+	}
+}
+
+
+
+
+void Server_Answer_Version()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Version_Answer()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_VER_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  IES600RB_VER_HIGH;
+		SvrSendBuff[12] =  IES600RB_VER_LOW;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+
+	}
+
+
+	nrf_delay_ms(1000);
+
+#if 0
+	for(i=0; i<5; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+#endif
+}
+
+
+void Server_Answer_Upgread()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Upgread()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_UPGREAD_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  IES600RB_VER_HIGH;
+		SvrSendBuff[12] =  IES600RB_VER_LOW;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+	}
+
+
+	NRF_LOG_RAW_INFO("================================================================================\n");
+	NRF_LOG_RAW_INFO("======================== Reboot To BootLoad Start ==============================\n");
+	NRF_LOG_RAW_INFO("================================================================================\n");	
+
+	nrf_delay_ms(1000);
+
+	for(i=0; i<5; i++){
+	
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+
+	nrf_delay_ms(3000);
+
+
+	nrf_power_gpregret_set(0xB1);
+	NVIC_SystemReset();
+	
+}
+
+
+
+
+// 사용않함
+void SendEmergencyLocal()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;	
+	
+	SendToEventServer(&SvrSendBuff[0], 20);
+	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+
+}
+
+
+
+// 송신기 테스트 버튼눌렀을시 동작 
+void AliveTest()
+{
+	int cnt = 0;
+
+	int buz_cnt = 0;
+	int led_cnt = 0;
+	char blink_cnt = 0;
+	char blink_flag = 0;
+	
+	uint8_t ex = 1;
+
+	NRF_LOG_RAW_INFO("Void AliveTest()\n");
+
+#if 0
+
+	PKBuzzerOn();
+	PKLedOn();
+
+	blink_flag = 1;
+
+	while(ex){
+
+		if(SystemTimer.MS_100_TICK){
+
+			SystemTimer.MS_100_TICK = 0;
+
+			cnt++;
+			
+			if(cnt >= 5){
+
+				cnt = 0;
+
+				buz_cnt++;
+
+				if(buz_cnt >= 2){	// 10sec
+					PKBuzzerOff();
+				}
+
+				blink_flag = !blink_flag;
+			
+	 			if(blink_flag){
+					PKLedOn();
+				}else{
+					PKLedOff();
+
+					blink_cnt++;
+
+					if(blink_cnt >= 3)
+						ex = 0;
+				}
+			}
+		}
+	}
+
+//	SystemManager.LedBlinkRun = COM_TYPE_SVR_TEST;
+//	SystemManager.LedBlinkTimer = 3300;
+//	SystemTimer.LED_TOGGLE_TIMER = 0;
+#else
+
+  	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+	SystemManager.LedBlinkRun = COM_TYPE_SVR_TEST;
+	SystemManager.LedBlinkTimer = 3300;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+#endif
+	
+}
+
+
+
+
+
+
+void LedToggle()
+{
+
+	static char toggle = 0;
+
+	
+	// 송신기 등록모드시 항상 ON
+
+#if 1
+
+	switch(SystemManager.LedBlinkRun){
+		case COM_TYPE_SVR_RECV_REG_REQ:
+			PKLedOn();
+			return;
+		break;
+
+		case COM_TYPE_SVR_RECV_REG_ANSWER:
+
+			if( SystemManager.RegRequst == 1 )
+			{
+				if( SystemManager.LedBlinkTimer < 0 )
+				{
+					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_REQ;
+					PKLedOn(); 	
+					return;
+				}
+			}
+
+			if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+				return;
+
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			if( toggle++ & 0x01)
+			{
+				PKLedOn();
+			}else{
+				PKLedOff();
+			}
+
+		break;
+
+		case COM_TYPE_SVR_TEST:
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				SystemManager.LedBlinkRun = 0;
+				PKLedOff(); 
+				PKBuzzerOff();
+			
+				return;
+			}
+			
+			
+			if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+				return;
+			
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+			
+			if( toggle++&0x01)
+			{
+				PKLedOn();
+			}else{
+				PKLedOff();
+			}
+		break;
+
+
+		case COM_TYPE_BAND_PARKING:
+		case COM_TYPE_APP_PARKING:
+		case COM_TYPE_IOS_APP_PARKING:
+		case COM_TYPE_NEW_IOS_APP_PARKING:
+
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			 {
+				 SystemManager.LedBlinkRun = 0;
+				 PKLedOff();	   
+				 return;
+			 }
+			
+			
+			 if( SystemTimer.LED_TOGGLE_TIMER < 300 )
+				 return;
+			
+			 SystemTimer.LED_TOGGLE_TIMER = 0;
+			
+			 if( ++toggle&0x01)
+			 {
+				 PKLedOn();
+			 }else{
+				 PKLedOff();
+			 }
+		break;
+	}			
+
+
+#else
+	
+	
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG_REQ )
+	{
+		PKLedOn();
+		return;
+	}
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG_ANSWER )
+	{
+
+		if( SystemManager.RegRequst == 1 )
+		{
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_REQ;
+				PKLedOn(); 	
+				return;
+			}
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+		if( toggle++ & 0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_TEST )
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff();	
+			PKBuzzerOff();
+
+			return;
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}	
+	
+#endif
+
+
+
+	if( SystemManager.SwitchOn == 0 )
+		return;
+
+	if( SystemManager.LedBlinkRun == 0 )
+		return;
+
+
+	if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+		return;
+
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+	if( toggle++&0x01)
+	{
+		PKLedOn();
+	}else{
+		PKLedOff();
+	}
+}
+
+

+ 342 - 0
BLE_Central.si4project/Backup/our_service(1225).h

@@ -0,0 +1,342 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 OUR_SERVICE_H__
+#define OUR_SERVICE_H__
+
+#include <stdint.h>
+#include "ble.h"
+#include "ble_srv_common.h"
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include "app_uart.h"
+#include "app_error.h"
+
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+
+#define NUM_STX			0
+#define NUM_TYPE_SVR	1
+#define NUM_CHECKSUM	18
+#define NUM_ETX			19
+
+
+#define COM_COMM_EMG_SWTICH	0x01
+#define COM_COMM_SMART_BAND	0x02
+#define COM_COMM_ONEPASS	0x03
+
+
+#define COM_TYPE_BELL_EMG	0x01
+
+
+
+
+#define COM_STX               0x02			// START BYTE
+#define COM_ETX               0x03			// END	BYTE
+
+//#define COM_TYPE_BELL_EMG     0x01
+//#define COM_TYPE_SVR_NORMAL   0x02
+//#define COM_TYPE_SVR_TALKING  0x03
+//#define COM_TYPE_SVR_DISCON   0x04
+//#define COM_TYPE_SVR_BUSY     0x05
+//#define COM_TYPE_SVR_ALIVE    0x06
+
+
+//#define COM_TYPE_SVR_TEST	  0x07
+
+#define COM_TYPE_BAND         0x02
+#define COM_TYPE_BAND_EMG     0x01
+
+
+
+
+
+#define DEV_NONE			0
+#define DEV_BAND_PARK		1			// 밴드 주차등록
+#define DEV_BAND_EMG		2			// 밴드 비상
+#define DEV_EMG_BUTTON		3			// 비상벨 버튼 
+#define DEV_BAND_ADV		4			// 비상벨 
+#define DEV_WES_ALIVE		5			// 수신기 Alive
+#define DEV_WES_REG			6			// 수신기 목록 
+#define DEV_WES_ADV			7			// 수신기 
+
+#define DEV_EMG_BAND		8
+#define DEV_IOS_PARK		9			// NEW IOS 원패스 주차등록 
+
+
+
+#define DEV_NUS_EMG			1
+#define DEV_NUS_TEST		2
+#define DEV_NUS_REG			3
+#define DEV_NUS_ALIVE		4
+
+
+
+
+
+//#define COM_TYPE_SVR_NORMAL   0x02
+//#define COM_TYPE_SVR_TALKING  0x03
+//#define COM_TYPE_SVR_DISCON   0x04
+//#define COM_TYPE_SVR_BUSY     0x05
+//#define COM_TYPE_SVR_ALIVE    0x06
+//#define COM_TYPE_SVR_MIC      0x07
+//#define COM_TYPE_SVR_RECV_REG 	0x08
+//#define COM_TYPE_SVR_RECV_INIT 	0x0a
+//#define COM_TYPE_SVR_RECV_LIST	0x0c
+
+
+#define COM_TYPE_SVR_PARKING	0x73
+
+
+
+#define SERVER_COMM_DATA_LEN			0x08
+
+
+#define COM_TYPE_SVR_EMG_ACK			0x01		// SERVER EMG 응답
+#define COM_TYPE_SVR_NORMAL   			0x02		// 수신기 Normal 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_TALKING  			0x03		// 수신기 Talking 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_DISCON   			0x04		// 수신기 DisConnect 신호	( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_BUSY     			0x05		// 수신기 Busy 신호			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_ALIVE    			0x06		// 수신기 Alive 신호			( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_MIC      			0x07		// 수신기 Mic 상태 			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_REG_REQ		0x08		// 송신기 등록 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_REG_ANSWER	0x09		// 송신기 등록 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_INIT_REQ		0x0a		// 수신기 초기화 요청 		( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_RECV_INIT_ANSWER	0x0b		// 수신기 초기화 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_LIST_REQ		0x0c		// 송신기 목록 요청		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_LIST_ANSWER	0x0d		// 송신기 목록 응답		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_UPGREAD_REQ		0x0e		// 수신기 업그레이드 요청	( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_UPGREAD_ANSWER		0x0f		// 수신기 업그레이드 응답	( IES600 --> BleEventServer ) 
+#define COM_TYPE_SVR_VER_REQ			0x10		// 수신기 버전 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_VER_ANSWER			0x11		// 수신기 버전 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_CALL_REQ			0x12		// 수신기 통화 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_CALL_ANSWER		0x13		// 수신기 통화 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_TEST				0x14		// 수신기 TEST 신호 		( )
+
+
+// 밴드 / APP Parking
+#define COM_TYPE_BAND_PARKING			0x21
+#define COM_TYPE_APP_PARKING			0x22
+#define COM_TYPE_IOS_APP_PARKING		0x23
+#define COM_TYPE_NEW_IOS_APP_PARKING	0x24
+
+
+
+
+// 수신기 모드 
+#define SYSTEM_NONE				0x00	// 대기모드 
+#define SYSTEM_EMERGENCY_SIREN	0x01	// 송신기/밴드 비상 싸이렌 모드 
+#define SYSTEM_SERVER_COMM		0x02	// 서버와 통신 상태
+#define SYSTEM_REGISTER			0x03	// 송신기 등록모드
+#define SYSTEM_SERVER_COMM_REQ	0x04	// 서버에서  통신 요청
+
+
+
+struct stSystemTimer__ {
+
+
+	volatile int MS_1;
+	volatile int MS_10_TICK;
+	volatile int MS_100_TICK;
+	volatile int MS_1000_TICK;	
+    volatile int UART_LAST_RECV_TIMER;
+    volatile int SEND_TEST_TIMER;
+    volatile int LED_TOGGLE_TIMER;
+    volatile int TMR_SYS_OFF;
+	volatile int TMR_CON_START;
+	volatile int PARK_KEEP_TIMER;
+	volatile int DEV_REG_TIMER;
+	volatile int SVR_SEND_TIMER;
+
+	volatile int SYSTEM_REGISTER_CNT;			// 등록모드 상태 CNT (SEC)
+	volatile int SYSTEM_SERVER_COMM_CNT;		// 통신 상태 CNT (SEC)
+	volatile int SYSTEM_SERVER_COMM_REQ_CNT;	// 서버 통화 요청 상태 CNT (SEC)
+	volatile int SYSTEM_EMERGENCY_SIREN_CNT;	// 비상 싸이렌 상태 CNT (SEC)
+
+
+
+
+};
+typedef struct stSystemTimer__ stSystemTimer;
+
+
+
+
+struct stBandData__ {
+
+
+	uint32_t Uid;
+	uint32_t Site;
+	uint16_t Dong;
+	uint16_t Ho;
+	uint8_t KeyNum;
+	uint8_t KeyType;
+	uint32_t ReaderId[3];
+	uint8_t ReaderRssi[3];
+};
+typedef struct stBandData__ stBandData;
+
+
+
+
+
+
+
+
+struct stSystemManager__ {
+
+
+	char System_State;
+
+	char Emg_Ack_Flag;		// 0: NONE 	1: 비상벨 EMG  2: Band EMG
+
+	char Emg_Resend_Cnt;
+
+
+	char RxValild;
+	char RxEvent;
+
+	char SwitchOn;			// 부저 사이린 동작 유무 
+	char BuzzerOn;
+	char MicOn;
+	char SpeakerOn;
+
+
+	char ServerCon;			// 이벤트서버와 연결 유무 
+
+
+	char DevType;
+	char *PtrLocalName;
+	int  PtrLocalNameLen;
+
+
+	char LedBlinkRun;			// LED Blink 동작 종류
+	int  LedBlinkTimer;			// LED Blink 동작 시간
+
+	char RegRequst;
+	char PeerAddr[6];
+	char LocalNameAddr[6];
+	char *PtrPeerAddrStr;
+
+	char BatLevel;
+
+	char TransferVerHigh;
+	char TransferVerLow;
+
+
+	char *TmpPtr;
+
+
+	volatile char AesEncData[16];
+	char TmpBuff[40];
+	char TmpBuff2[40];
+	char SecondData;
+	char BandMode;
+
+
+	char BandType;			// 0x72 : EMG 		// 0x73 : PARKING
+	char Site[4];
+
+	char Dong[2];
+	char Ho[2];
+	char Key_Num;
+	char Key_Type;
+
+	char Dong_bak[2];
+	char Ho_bak[2];
+	char Key_Num_bak;
+	char Key_Type_bak;
+
+
+	char Random_In[2];
+	char Random_Out[2];
+
+	stBandData BandData;
+    
+
+	
+};
+typedef struct stSystemManager__ stSystemManager;
+
+
+
+void USART_Handler(void);
+void ParseEventServer();
+void SendToEventServer(char* data, int len);
+void SendEmergency();
+void SendEmergencyLocal();
+void SendTest();
+void LedToggle();
+void USART_DataCheck();
+
+void SendAck(uint8_t cmd);
+void SendCurrentRegDev();
+void SendEmergencyBand();
+void SendParkingBand();
+void AliveTest();
+void SendParkingApp();
+
+void Server_Answer_Call();
+void Server_Answer_Reg_List();
+void Server_Answer_Version();
+void Server_Answer_Upgread();
+
+
+
+
+extern char SvrRxBuffer[];
+extern int SvrRxBufferPos;
+extern char SvrEvent;
+
+
+extern stSystemTimer SystemTimer;
+extern stSystemManager SystemManager;
+
+
+
+#endif  /* _ OUR_SERVICE_H__ */

+ 247 - 0
BLE_Central.si4project/Backup/our_service(142).h

@@ -0,0 +1,247 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 OUR_SERVICE_H__
+#define OUR_SERVICE_H__
+
+#include <stdint.h>
+#include "ble.h"
+#include "ble_srv_common.h"
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include "app_uart.h"
+#include "app_error.h"
+
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+
+
+
+
+
+
+#define COM_STX               0x02
+#define COM_ETX               0x03
+#define COM_TYPE_SVR          0x01
+#define COM_TYPE_BELL_EMG     0x01
+#define COM_TYPE_SVR_NORMAL   0x02
+#define COM_TYPE_SVR_TALKING  0x03
+#define COM_TYPE_SVR_DISCON   0x04
+#define COM_TYPE_SVR_BUSY     0x05
+#define COM_TYPE_SVR_ALIVE    0x06
+
+
+#define COM_TYPE_BAND         0x02
+#define COM_TYPE_BAND_EMG     0x01
+#define COM_SVR_ACK           72
+
+
+
+
+#define DEV_NONE			0
+#define DEV_BAND_PARK		1
+#define DEV_BAND_EMG		2
+#define DEV_EMG_BUTTON		3
+#define DEV_BAND_ADV		4
+#define DEV_WES_ALIVE		5
+#define DEV_WES_REG			6
+#define DEV_WES_ADV			7
+
+#define DEV_EMG_BAND		8
+
+
+
+
+#define DEV_NUS_EMG			1
+#define DEV_NUS_TEST		2
+#define DEV_NUS_REG			3
+#define DEV_NUS_ALIVE		4
+
+
+
+
+
+#define COM_TYPE_SVR_NORMAL   0x02
+#define COM_TYPE_SVR_TALKING  0x03
+#define COM_TYPE_SVR_DISCON   0x04
+#define COM_TYPE_SVR_BUSY     0x05
+#define COM_TYPE_SVR_ALIVE    0x06
+#define COM_TYPE_SVR_MIC      0x07
+#define COM_TYPE_SVR_RECV_REG 	0x08
+#define COM_TYPE_SVR_RECV_INIT 	0x0a
+#define COM_TYPE_SVR_RECV_LIST	0x0c
+
+
+#define COM_TYPE_SVR_PARKING	0x73
+
+
+
+
+
+
+struct stSystemTimer__ {
+
+
+	volatile int MS_1;
+    volatile int UART_LAST_RECV_TIMER;
+    volatile int SEND_TEST_TIMER;
+    volatile int LED_TOGGLE_TIMER;
+    volatile int TMR_SYS_OFF;
+	volatile int TMR_CON_START;
+	volatile int PARK_KEEP_TIMER;
+	volatile int DEV_REG_TIMER;
+	volatile int SVR_SEND_TIMER;
+
+
+
+};
+typedef struct stSystemTimer__ stSystemTimer;
+
+
+
+
+struct stBandData__ {
+
+
+	uint32_t Uid;
+	uint32_t Site;
+	uint16_t Dong;
+	uint16_t Ho;
+	uint8_t KeyNum;
+	uint8_t KeyType;
+	uint32_t ReaderId[3];
+	uint8_t ReaderRssi[3];
+};
+typedef struct stBandData__ stBandData;
+
+
+
+
+
+
+struct stSystemManager__ {
+
+	char RxValild;
+	char RxEvent;
+
+	char SwitchOn;			// 부저 사이린 동작 유무 
+	char BuzzerOn;
+	char MicOn;
+	char SpeakerOn;
+
+
+	char ServerCon;			// 이벤트서버와 연결 유무 
+
+
+	char DevType;
+	char *PtrLocalName;
+	int  PtrLocalNameLen;
+
+
+	char LedBlinkRun;			// LED Flick 동작 
+	int  LedBlinkTimer;			// 
+
+	char NusData;
+	char RegRequst;
+	char PeerAddr[6];
+	char *PtrPeerAddrStr;
+
+	char BatLevel;
+
+	char *TmpPtr;
+
+
+	char AesEncData[16];
+	char TmpBuff[40];
+	char TmpBuff2[40];
+	char SecondData;
+	char BandMode;
+
+
+	char BandType;
+	char Site[4];
+	char Dong[2];
+	char Ho[2];
+
+
+	stBandData BandData;
+
+};
+typedef struct stSystemManager__ stSystemManager;
+
+
+
+void USART_Handler(void);
+void ParseEventServer();
+void SendToEventServer(char* data, int len);
+void SendEmergency();
+void SendEmergencyLocal();
+void SendTest();
+void LedToggle();
+void USART_DataCheck();
+void SendDevList();
+void SendAck(uint8_t cmd);
+void SendCurrentRegDev();
+void SendEmergencyBand();
+void SendParkingBand();
+void AliveTest();
+void SendParkingApp();
+
+
+
+extern char SvrRxBuffer[];
+extern int SvrRxBufferPos;
+extern char SvrEvent;
+
+
+extern stSystemTimer SystemTimer;
+extern stSystemManager SystemManager;
+
+
+
+#endif  /* _ OUR_SERVICE_H__ */

+ 331 - 0
BLE_Central.si4project/Backup/our_service(145).h

@@ -0,0 +1,331 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 OUR_SERVICE_H__
+#define OUR_SERVICE_H__
+
+#include <stdint.h>
+#include "ble.h"
+#include "ble_srv_common.h"
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include "app_uart.h"
+#include "app_error.h"
+
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+
+#define NUM_STX			0
+#define NUM_TYPE_SVR	1
+#define NUM_CHECKSUM	18
+#define NUM_ETX			19
+
+
+#define COM_COMM_EMG_SWTICH	0x01
+#define COM_COMM_SMART_BAND	0x02
+#define COM_COMM_ONEPASS	0x03
+
+
+#define COM_TYPE_BELL_EMG	0x01
+
+
+
+
+#define COM_STX               0x02			// START BYTE
+#define COM_ETX               0x03			// END	BYTE
+
+//#define COM_TYPE_BELL_EMG     0x01
+//#define COM_TYPE_SVR_NORMAL   0x02
+//#define COM_TYPE_SVR_TALKING  0x03
+//#define COM_TYPE_SVR_DISCON   0x04
+//#define COM_TYPE_SVR_BUSY     0x05
+//#define COM_TYPE_SVR_ALIVE    0x06
+
+
+//#define COM_TYPE_SVR_TEST	  0x07
+
+#define COM_TYPE_BAND         0x02
+#define COM_TYPE_BAND_EMG     0x01
+
+
+
+
+
+#define DEV_NONE			0
+#define DEV_BAND_PARK		1			// 밴드 주차등록
+#define DEV_BAND_EMG		2			// 밴드 비상
+#define DEV_EMG_BUTTON		3			// 비상벨 버튼 
+#define DEV_BAND_ADV		4			// 비상벨 
+#define DEV_WES_ALIVE		5			// 수신기 Alive
+#define DEV_WES_REG			6			// 수신기 목록 
+#define DEV_WES_ADV			7			// 수신기 
+
+#define DEV_EMG_BAND		8
+#define DEV_IOS_PARK		9			// NEW IOS 원패스 주차등록 
+
+
+
+#define DEV_NUS_EMG			1
+#define DEV_NUS_TEST		2
+#define DEV_NUS_REG			3
+#define DEV_NUS_ALIVE		4
+
+
+
+
+
+//#define COM_TYPE_SVR_NORMAL   0x02
+//#define COM_TYPE_SVR_TALKING  0x03
+//#define COM_TYPE_SVR_DISCON   0x04
+//#define COM_TYPE_SVR_BUSY     0x05
+//#define COM_TYPE_SVR_ALIVE    0x06
+//#define COM_TYPE_SVR_MIC      0x07
+//#define COM_TYPE_SVR_RECV_REG 	0x08
+//#define COM_TYPE_SVR_RECV_INIT 	0x0a
+//#define COM_TYPE_SVR_RECV_LIST	0x0c
+
+
+#define COM_TYPE_SVR_PARKING	0x73
+
+
+
+#define SERVER_COMM_DATA_LEN			0x08
+
+
+#define COM_TYPE_SVR_EMG_ACK			0x01		// SERVER EMG 응답
+#define COM_TYPE_SVR_NORMAL   			0x02		// 수신기 Normal 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_TALKING  			0x03		// 수신기 Talking 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_DISCON   			0x04		// 수신기 DisConnect 신호	( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_BUSY     			0x05		// 수신기 Busy 신호			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_ALIVE    			0x06		// 수신기 Alive 신호			( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_MIC      			0x07		// 수신기 Mic 상태 			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_REG_REQ		0x08		// 송신기 등록 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_REG_ANSWER	0x09		// 송신기 등록 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_INIT_REQ		0x0a		// 수신기 초기화 요청 		( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_RECV_INIT_ANSWER	0x0b		// 수신기 초기화 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_LIST_REQ		0x0c		// 송신기 목록 요청		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_LIST_ANSWER	0x0d		// 송신기 목록 응답		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_UPGREAD_REQ		0x0e		// 수신기 업그레이드 요청	( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_UPGREAD_ANSWER		0x0f		// 수신기 업그레이드 응답	( IES600 --> BleEventServer ) 
+#define COM_TYPE_SVR_VER_REQ			0x10		// 수신기 버전 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_VER_ANSWER			0x11		// 수신기 버전 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_CALL_REQ			0x12		// 수신기 통화 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_CALL_ANSWER		0x13		// 수신기 통화 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_TEST				0x14		// 수신기 TEST 신호 		( )
+
+
+// 밴드 / APP Parking
+#define COM_TYPE_BAND_PARKING			0x21
+#define COM_TYPE_APP_PARKING			0x22
+#define COM_TYPE_IOS_APP_PARKING		0x23
+#define COM_TYPE_NEW_IOS_APP_PARKING	0x24
+
+
+
+
+// 수신기 모드 
+#define SYSTEM_NONE				0x00	// 대기모드 
+#define SYSTEM_EMERGENCY_SIREN	0x01	// 송신기/밴드 비상 싸이렌 모드 
+#define SYSTEM_SERVER_COMM		0x02	// 서버와 통신 상태
+#define SYSTEM_REGISTER			0x03	// 송신기 등록모드
+#define SYSTEM_SERVER_COMM_REQ	0x04	// 서버에서  통신 요청
+
+
+
+struct stSystemTimer__ {
+
+
+	volatile int MS_1;
+	volatile int MS_10_TICK;
+	volatile int MS_100_TICK;
+	volatile int MS_1000_TICK;	
+    volatile int UART_LAST_RECV_TIMER;
+    volatile int SEND_TEST_TIMER;
+    volatile int LED_TOGGLE_TIMER;
+    volatile int TMR_SYS_OFF;
+	volatile int TMR_CON_START;
+	volatile int PARK_KEEP_TIMER;
+	volatile int DEV_REG_TIMER;
+	volatile int SVR_SEND_TIMER;
+
+	volatile int SYSTEM_REGISTER_CNT;			// 등록모드 상태 CNT (SEC)
+	volatile int SYSTEM_SERVER_COMM_CNT;		// 통신 상태 CNT (SEC)
+	volatile int SYSTEM_SERVER_COMM_REQ_CNT;	// 서버 통화 요청 상태 CNT (SEC)
+	volatile int SYSTEM_EMERGENCY_SIREN_CNT;	// 비상 싸이렌 상태 CNT (SEC)
+
+
+
+
+};
+typedef struct stSystemTimer__ stSystemTimer;
+
+
+
+
+struct stBandData__ {
+
+
+	uint32_t Uid;
+	uint32_t Site;
+	uint16_t Dong;
+	uint16_t Ho;
+	uint8_t KeyNum;
+	uint8_t KeyType;
+	uint32_t ReaderId[3];
+	uint8_t ReaderRssi[3];
+};
+typedef struct stBandData__ stBandData;
+
+
+
+
+
+
+
+
+struct stSystemManager__ {
+
+
+	char System_State;
+
+	char Emg_Ack_Flag;		// 0: NONE 	1: 비상벨 EMG  2: Band EMG
+
+	char Emg_Resend_Cnt;
+
+
+	char RxValild;
+	char RxEvent;
+
+	char SwitchOn;			// 부저 사이린 동작 유무 
+	char BuzzerOn;
+	char MicOn;
+	char SpeakerOn;
+
+
+	char ServerCon;			// 이벤트서버와 연결 유무 
+
+
+	char DevType;
+	char *PtrLocalName;
+	int  PtrLocalNameLen;
+
+
+	char LedBlinkRun;			// LED Blink 동작 종류
+	int  LedBlinkTimer;			// LED Blink 동작 시간
+
+	char RegRequst;
+	char PeerAddr[6];
+	char *PtrPeerAddrStr;
+
+	char BatLevel;
+
+	char TransferVerHigh;
+	char TransferVerLow;
+
+
+	char *TmpPtr;
+
+
+	volatile char AesEncData[16];
+	char TmpBuff[40];
+	char TmpBuff2[40];
+	char SecondData;
+	char BandMode;
+
+
+	char BandType;			// 0x72 : EMG 		// 0x73 : PARKING
+	char Site[4];
+	char Dong[2];
+	char Ho[2];
+	char Key_Num;
+	char Key_Type;
+	char Random_In[2];
+	char Random_Out[2];
+
+	stBandData BandData;
+
+};
+typedef struct stSystemManager__ stSystemManager;
+
+
+
+void USART_Handler(void);
+void ParseEventServer();
+void SendToEventServer(char* data, int len);
+void SendEmergency();
+void SendEmergencyLocal();
+void SendTest();
+void LedToggle();
+void USART_DataCheck();
+
+void SendAck(uint8_t cmd);
+void SendCurrentRegDev();
+void SendEmergencyBand();
+void SendParkingBand();
+void AliveTest();
+void SendParkingApp();
+
+void Server_Answer_Call();
+void Server_Answer_Reg_List();
+void Server_Answer_Version();
+void Server_Answer_Upgread();
+
+
+
+
+extern char SvrRxBuffer[];
+extern int SvrRxBufferPos;
+extern char SvrEvent;
+
+
+extern stSystemTimer SystemTimer;
+extern stSystemManager SystemManager;
+
+
+
+#endif  /* _ OUR_SERVICE_H__ */

+ 319 - 0
BLE_Central.si4project/Backup/our_service(177).h

@@ -0,0 +1,319 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 OUR_SERVICE_H__
+#define OUR_SERVICE_H__
+
+#include <stdint.h>
+#include "ble.h"
+#include "ble_srv_common.h"
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include "app_uart.h"
+#include "app_error.h"
+
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+
+#define NUM_STX			0
+#define NUM_TYPE_SVR	1
+#define NUM_CHECKSUM	18
+#define NUM_ETX			19
+
+
+#define COM_COMM_EMG_SWTICH	0x01
+#define COM_COMM_SMART_BAND	0x02
+#define COM_COMM_ONEPASS	0x03
+
+
+#define COM_TYPE_BELL_EMG	0x01
+
+
+
+
+#define COM_STX               0x02			// START BYTE
+#define COM_ETX               0x03			// END	BYTE
+
+//#define COM_TYPE_BELL_EMG     0x01
+//#define COM_TYPE_SVR_NORMAL   0x02
+//#define COM_TYPE_SVR_TALKING  0x03
+//#define COM_TYPE_SVR_DISCON   0x04
+//#define COM_TYPE_SVR_BUSY     0x05
+//#define COM_TYPE_SVR_ALIVE    0x06
+
+
+//#define COM_TYPE_SVR_TEST	  0x07
+
+#define COM_TYPE_BAND         0x02
+#define COM_TYPE_BAND_EMG     0x01
+
+
+
+
+
+#define DEV_NONE			0
+#define DEV_BAND_PARK		1			// 밴드 주차등록
+#define DEV_BAND_EMG		2			// 밴드 비상
+#define DEV_EMG_BUTTON		3			// 비상벨 버튼 
+#define DEV_BAND_ADV		4			// 비상벨 
+#define DEV_WES_ALIVE		5			// 수신기 Alive
+#define DEV_WES_REG			6			// 수신기 목록 
+#define DEV_WES_ADV			7			// 수신기 
+
+#define DEV_EMG_BAND		8
+#define DEV_IOS_PARK		9			// NEW IOS 원패스 주차등록 
+
+
+
+#define DEV_NUS_EMG			1
+#define DEV_NUS_TEST		2
+#define DEV_NUS_REG			3
+#define DEV_NUS_ALIVE		4
+
+
+
+
+
+//#define COM_TYPE_SVR_NORMAL   0x02
+//#define COM_TYPE_SVR_TALKING  0x03
+//#define COM_TYPE_SVR_DISCON   0x04
+//#define COM_TYPE_SVR_BUSY     0x05
+//#define COM_TYPE_SVR_ALIVE    0x06
+//#define COM_TYPE_SVR_MIC      0x07
+#define COM_TYPE_SVR_RECV_REG 	0x08
+#define COM_TYPE_SVR_RECV_INIT 	0x0a
+#define COM_TYPE_SVR_RECV_LIST	0x0c
+
+
+#define COM_TYPE_SVR_PARKING	0x73
+
+
+
+#define SERVER_COMM_DATA_LEN			0x08
+
+
+#define COM_TYPE_SVR_EMG_REQ			0x01		// SERVER EMG 응답
+#define COM_TYPE_SVR_NORMAL   			0x02		// 수신기 Normal 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_TALKING  			0x03		// 수신기 Talking 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_DISCON   			0x04		// 수신기 DisConnect 신호	( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_BUSY     			0x05		// 수신기 Busy 신호			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_ALIVE    			0x06		// 수신기 Alive 신호			( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_MIC      			0x07		// 수신기 Mic 상태 			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_REG_REQ		0x08		// 송신기 등록 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SEV_RECV_REG_ANSWER	0x09		// 송신기 등록 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_INIT_REQ		0x0a		// 수신기 초기화 요청 		( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_RECV_INIT_ANSWER	0x0b		// 수신기 초기화 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_LIST_REQ		0x0c		// 송신기 목록 요청		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_LIST_ANSWER	0x0d		// 송신기 목록 응답		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_UPGREAD_REQ		0x0e		// 수신기 업그레이드 요청	( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_UPGREAD_ANSWER		0x0f		// 수신기 업그레이드 응답	( IES600 --> BleEventServer ) 
+#define COM_TYPE_SVR_VER_REQ			0x10		// 수신기 버전 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_VER_ANSWER			0x11		// 수신기 버전 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_CALL_REQ			0x12		// 수신기 통화 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_CALL_ANSWER		0x13		// 수신기 통화 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_TEST				0x14		// 수신기 TEST 신호 		( )
+
+
+
+// 수신기 모드 
+#define SYSTEM_NONE				0x00	// 대기모드 
+#define SYSTEM_EMERGENCY_SIREN	0x01	// 송신기/밴드 비상 싸이렌 모드 
+#define SYSTEM_SERVER_COMM		0x02	// 서버와 통신 상태
+#define SYSTEM_REGISTER			0x03	// 송신기 등록모드
+#define SYSTEM_SERVER_COMM_REQ	0x04	// 서버와 통신 요청
+
+
+
+struct stSystemTimer__ {
+
+
+	volatile int MS_1;
+	volatile int MS_10_TICK;
+	volatile int MS_100_TICK;
+	volatile int MS_1000_TICK;	
+    volatile int UART_LAST_RECV_TIMER;
+    volatile int SEND_TEST_TIMER;
+    volatile int LED_TOGGLE_TIMER;
+    volatile int TMR_SYS_OFF;
+	volatile int TMR_CON_START;
+	volatile int PARK_KEEP_TIMER;
+	volatile int DEV_REG_TIMER;
+	volatile int SVR_SEND_TIMER;
+
+	volatile int SYSTEM_REGISTER_CNT;			// 등록모드 상태 CNT (SEC)
+	volatile int SYSTEM_SERVER_COMM_CNT;		// 통신 상태 CNT (SEC)
+	volatile int SYSTEM_SERVER_COMM_REQ_CNT;	// 서버 통화 요청 상태 CNT (SEC)
+	volatile int SYSTEM_EMERGENCY_SIREN_CNT;	// 비상 싸이렌 상태 CNT (SEC)
+
+
+
+
+};
+typedef struct stSystemTimer__ stSystemTimer;
+
+
+
+
+struct stBandData__ {
+
+
+	uint32_t Uid;
+	uint32_t Site;
+	uint16_t Dong;
+	uint16_t Ho;
+	uint8_t KeyNum;
+	uint8_t KeyType;
+	uint32_t ReaderId[3];
+	uint8_t ReaderRssi[3];
+};
+typedef struct stBandData__ stBandData;
+
+
+
+
+
+
+
+
+struct stSystemManager__ {
+
+
+	char System_State;
+
+	char RxValild;
+	char RxEvent;
+
+	char SwitchOn;			// 부저 사이린 동작 유무 
+	char BuzzerOn;
+	char MicOn;
+	char SpeakerOn;
+
+
+	char ServerCon;			// 이벤트서버와 연결 유무 
+
+
+	char DevType;
+	char *PtrLocalName;
+	int  PtrLocalNameLen;
+
+
+	char LedBlinkRun;			// LED Blink 동작 종류
+	int  LedBlinkTimer;			// LED Blink 동작 시간
+
+	char NusData;
+	char RegRequst;
+	char PeerAddr[6];
+	char *PtrPeerAddrStr;
+
+	char BatLevel;
+
+	char TransferVerHigh;
+	char TransferVerLow;
+
+
+	char *TmpPtr;
+
+
+	char AesEncData[16];
+	char TmpBuff[40];
+	char TmpBuff2[40];
+	char SecondData;
+	char BandMode;
+
+
+	char BandType;
+	char Site[4];
+	char Dong[2];
+	char Ho[2];
+
+
+
+
+
+	stBandData BandData;
+
+};
+typedef struct stSystemManager__ stSystemManager;
+
+
+
+void USART_Handler(void);
+void ParseEventServer();
+void SendToEventServer(char* data, int len);
+void SendEmergency();
+void SendEmergencyLocal();
+void SendTest();
+void LedToggle();
+void USART_DataCheck();
+
+void SendAck(uint8_t cmd);
+void SendCurrentRegDev();
+void SendEmergencyBand();
+void SendParkingBand();
+void AliveTest();
+void SendParkingApp();
+
+void Server_Answer_Call();
+void Server_Answer_Reg_List();
+void Server_Answer_Version();
+void Server_Answer_Upgread();
+
+
+
+
+extern char SvrRxBuffer[];
+extern int SvrRxBufferPos;
+extern char SvrEvent;
+
+
+extern stSystemTimer SystemTimer;
+extern stSystemManager SystemManager;
+
+
+
+#endif  /* _ OUR_SERVICE_H__ */

+ 244 - 0
BLE_Central.si4project/Backup/our_service(2634).h

@@ -0,0 +1,244 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 OUR_SERVICE_H__
+#define OUR_SERVICE_H__
+
+#include <stdint.h>
+#include "ble.h"
+#include "ble_srv_common.h"
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include "app_uart.h"
+#include "app_error.h"
+
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+
+
+
+
+
+
+#define COM_STX               0x02
+#define COM_ETX               0x03
+#define COM_TYPE_SVR          0x01
+#define COM_TYPE_BELL_EMG     0x01
+#define COM_TYPE_SVR_NORMAL   0x02
+#define COM_TYPE_SVR_TALKING  0x03
+#define COM_TYPE_SVR_DISCON   0x04
+#define COM_TYPE_SVR_BUSY     0x05
+#define COM_TYPE_SVR_ALIVE    0x06
+
+
+#define COM_TYPE_BAND         0x02
+#define COM_TYPE_BAND_EMG     0x01
+#define COM_SVR_ACK           72
+
+
+
+
+#define DEV_NONE			0
+#define DEV_BAND_PARK		1
+#define DEV_BAND_EMG		2
+#define DEV_EMG_BUTTON		3
+#define DEV_BAND_ADV		4
+#define DEV_WES_ALIVE		5
+#define DEV_WES_REG			6
+#define DEV_WES_ADV			7
+
+#define DEV_EMG_BAND		8
+
+
+
+
+#define DEV_NUS_EMG			1
+#define DEV_NUS_ALIVE		2
+#define DEV_NUS_REG			3
+
+
+
+
+
+#define COM_TYPE_SVR_NORMAL   0x02
+#define COM_TYPE_SVR_TALKING  0x03
+#define COM_TYPE_SVR_DISCON   0x04
+#define COM_TYPE_SVR_BUSY     0x05
+#define COM_TYPE_SVR_ALIVE    0x06
+#define COM_TYPE_SVR_MIC      0x07
+#define COM_TYPE_SVR_RECV_REG 	0x08
+#define COM_TYPE_SVR_RECV_INIT 	0x0a
+#define COM_TYPE_SVR_RECV_LIST	0x0c
+
+
+#define COM_TYPE_SVR_PARKING	0x73
+
+
+
+
+
+
+struct stSystemTimer__ {
+
+
+	volatile int MS_1;
+    volatile int UART_LAST_RECV_TIMER;
+    volatile int SEND_TEST_TIMER;
+    volatile int LED_TOGGLE_TIMER;
+    volatile int TMR_SYS_OFF;
+	volatile int TMR_CON_START;
+	volatile int PARK_KEEP_TIMER;
+	volatile int DEV_REG_TIMER;
+	volatile int SVR_SEND_TIMER;
+
+
+
+};
+typedef struct stSystemTimer__ stSystemTimer;
+
+
+
+
+struct stBandData__ {
+
+
+	uint32_t Uid;
+	uint32_t Site;
+	uint16_t Dong;
+	uint16_t Ho;
+	uint8_t KeyNum;
+	uint8_t KeyType;
+	uint32_t ReaderId[3];
+	uint8_t ReaderRssi[3];
+};
+typedef struct stBandData__ stBandData;
+
+
+
+
+
+
+struct stSystemManager__ {
+
+	char RxValild;
+	char RxEvent;
+
+	char SwitchOn;			// 부저 사이린 동작 유무 
+	char BuzzerOn;
+	char MicOn;
+	char SpeakerOn;
+
+
+	char ServerCon;			// 이벤트서버와 연결 유무 
+
+
+	char DevType;
+	char *PtrLocalName;
+	int  PtrLocalNameLen;
+
+
+	char LedBlinkRun;			// LED Flick 동작 
+	int  LedBlinkTimer;			// 
+
+	char NusData;
+	char RegRequst;
+	char PeerAddr[6];
+	char *PtrPeerAddrStr;
+
+	char *TmpPtr;
+
+
+	char AesEncData[16];
+	char TmpBuff[40];
+	char TmpBuff2[40];
+	char SecondData;
+	char BandMode;
+
+
+	char BandType;
+	char Site[4];
+	char Dong[2];
+	char Ho[2];
+
+
+	stBandData BandData;
+
+};
+typedef struct stSystemManager__ stSystemManager;
+
+
+
+void USART_Handler(void);
+void ParseEventServer();
+void SendToEventServer(char* data, int len);
+void SendEmergency();
+void SendEmergencyLocal();
+void SendTest();
+void LedToggle();
+void USART_DataCheck();
+void SendDevList();
+void SendAck(uint8_t cmd);
+void SendCurrentRegDev();
+void SendEmergencyBand();
+void SendParkingBand();
+void AliveTest();
+void SendParkingApp();
+
+
+
+extern char SvrRxBuffer[];
+extern int SvrRxBufferPos;
+extern char SvrEvent;
+
+
+extern stSystemTimer SystemTimer;
+extern stSystemManager SystemManager;
+
+
+
+#endif  /* _ OUR_SERVICE_H__ */

+ 1461 - 0
BLE_Central.si4project/Backup/our_service(2862).c

@@ -0,0 +1,1461 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 <stdint.h>
+#include <string.h>
+#include "nrf_gpio.h"
+#include "our_service.h"
+#include "ble_srv_common.h"
+#include "app_error.h"
+#include "SEGGER_RTT.h"
+#include "board_gpi.h"
+#include "nrf_log.h"
+
+#include "sysmgr.h"
+#include "main.h"
+#include "nrf_power.h"
+
+
+char SvrRxBuffer[100];
+int SvrRxBufferPos;
+char SvrEvent;
+
+
+stSystemTimer SystemTimer;
+stSystemManager SystemManager;
+char SvrSendBuff[50];
+
+void delete_all_begin(void);
+
+
+
+void USART_DataCheck()
+{
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SystemManager.RxValild )
+	{
+
+		SvrRxBuffer[SvrRxBufferPos] = 0;
+
+//		printf("[%d]%s\r\n", SvrRxBufferPos, SvrRxBuffer);
+		SystemManager.RxValild = 0;
+
+		if( SvrRxBufferPos == 20 )
+		{
+			SystemManager.RxEvent = 1;
+			NRF_LOG_RAW_INFO("==========================>\n\n");
+		}
+
+		SvrRxBufferPos = 0;
+	}
+
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SvrRxBufferPos )
+	{
+		SystemManager.RxValild = 0;
+		SvrRxBufferPos = 0;
+	}
+
+}
+
+
+void USART_Handler(void)
+{
+
+	char ch;
+	
+	uint8_t cr;
+
+// 	SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	if( app_uart_get(&cr) == NRF_SUCCESS )
+	{
+		SystemManager.RxValild = 1;
+		SvrRxBuffer[SvrRxBufferPos++] = cr;
+		SvrRxBufferPos %= 100;
+		SystemTimer.UART_LAST_RECV_TIMER = 0;
+	}
+}
+
+
+
+
+
+
+/* 이벤트 서버에서 20byte 들어왔을때 */
+
+
+void ParseEventServer()
+{
+
+	int i;
+
+	if( SystemManager.RxEvent == 0 )
+		return;
+
+	SystemManager.RxEvent = 0;
+
+
+	NRF_LOG_RAW_INFO("\n\n");
+	NRF_LOG_RAW_INFO("SERVER TO DATA : ")
+
+	for( i=0; i<20; i++)
+	{
+		NRF_LOG_RAW_INFO("0x%02x ", SvrRxBuffer[i]);
+	}
+	NRF_LOG_RAW_INFO("\n\n");
+
+
+	if(SvrRxBuffer[0] != 0x02)
+		return;
+
+
+	switch(SvrRxBuffer[1]){
+
+		case NUM_TYPE_SVR:
+		case COM_TYPE_BAND:		//
+
+
+			switch(SvrRxBuffer[3]){
+
+				// 수신기 대기상태 요청
+				case COM_TYPE_SVR_NORMAL:
+
+					SystemManager.System_State = SYSTEM_NONE;
+
+					NRF_LOG_INFO("Recv : Normal");
+
+					PKLedOff();
+					PKBuzzerOff();
+					PKMicOff();
+					SystemManager.SwitchOn = 0;
+ 
+				break;
+
+				// 수신기 통화상태 요청 
+				case COM_TYPE_SVR_TALKING:
+
+					NRF_LOG_INFO("Recv : Talking");
+
+					PKLedOn();
+					PKBuzzerOff();
+					SystemManager.SwitchOn = 0;
+				break;
+
+				// 수신기 서버와 통화 종료 요청
+				case COM_TYPE_SVR_DISCON:
+					
+					NRF_LOG_INFO("Recv : Disconnect");
+
+					SystemManager.SwitchOn = 0;
+					//bsp_board_leds_off();
+				break;
+
+				// 서버 Busy 상태 알림
+				case COM_TYPE_SVR_BUSY:
+
+					NRF_LOG_INFO("Recv : Busy");
+
+				break;
+
+				// 송신기 Alive신호 서버로 전송
+				case COM_TYPE_SVR_ALIVE:
+
+					NRF_LOG_INFO("Recv : Keep Alive");
+
+				break;
+
+				// 수신기 마이크 상태 변경 요청 
+				case COM_TYPE_SVR_MIC:
+
+					SystemManager.System_State = SYSTEM_SERVER_COMM;
+
+					SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				
+					NRF_LOG_INFO("Recv : mic on/off");
+
+					
+					if( SvrRxBuffer[11] == 0 )
+					{  
+						NRF_LOG_INFO("mic on"); 
+						NRF_LOG_INFO("speaker off");  
+						PKSpeakerOff();
+						PKMicOn();
+						PKBuzzerOff();
+						PKLedOn();
+						SystemManager.SwitchOn = 0;
+					}else{
+						NRF_LOG_INFO("mic off"); 
+						NRF_LOG_INFO("speaker on");  
+						PKMicOff();
+						PKSpeakerOn();
+						PKLedOn();
+					}
+				break;
+
+				// 송신기 등록요청
+				case COM_TYPE_SVR_RECV_REG_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_REG");
+
+					if(SystemManager.System_State == SYSTEM_NONE){
+
+						SystemManager.System_State = SYSTEM_REGISTER;
+
+						SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG;
+						SystemManager.RegRequst = 1;
+
+						SendAck(COM_TYPE_SVR_RECV_REG+1);
+
+						SystemTimer.DEV_REG_TIMER = 0;
+					}else{
+						
+						NRF_LOG_INFO("SYSTEM is BUSY : [%d]\n", SystemManager.System_State);
+					}
+
+				break;
+
+				// 송신기 등록 초기화 요청
+				case COM_TYPE_SVR_RECV_INIT_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_INIT");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_INIT;
+//					SystemManager.LedBlinkTimer = 2500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+					
+					SendAck(COM_TYPE_SVR_RECV_INIT+1);
+
+					//for( i=0; i<RegMacPool.Count; i++)
+					//{
+					//RegMacDelteAll();
+					// }
+					memset( &RegMacPool, 0, sizeof(RegMacPool));
+
+					delete_all_begin();
+
+					for(i=0; i<2; i++){
+						PKLedOn();
+						nrf_delay_ms(300);
+						PKLedOff();
+						nrf_delay_ms(300);
+					}
+				break;
+
+				// 송신기에 등록된 수신기 리스트 요청 
+				case COM_TYPE_SVR_RECV_LIST_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_LIST");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_LIST;
+//					SystemManager.LedBlinkTimer = 1500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+
+					Server_Answer_Reg_List();
+
+					PKLedOn();
+					nrf_delay_ms(300);
+					PKLedOff();
+
+				break;
+
+				// 서버로 부터 통화 요청
+				case COM_TYPE_SVR_CALL_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_CALL_REQ");
+
+					Server_Answer_Call();
+
+				break;
+
+				// 서버로 부터 수신기 버전 요청
+				case COM_TYPE_SVR_VER_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_VER_REQ");
+
+					Server_Answer_Version();
+
+				break;
+
+
+				case COM_TYPE_SVR_UPGREAD_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_UPGREAD_REQ");
+					
+					Server_Answer_Upgread();
+
+				break;
+			}
+		break;
+
+//		case COM_TYPE_BAND:
+
+//		break;
+	}
+}
+
+
+
+void SendToEventServer(char* data, int len)
+{
+
+	int i;
+
+	NRF_LOG_RAW_INFO("SendToEventServer ==> ");
+	
+	for( i=0; i<len; i++)
+	{
+		NRF_LOG_RAW_INFO("%02X ", data[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+
+
+	for(i=0; i<len; i++)
+	{
+		while (app_uart_put(data[i]) != NRF_SUCCESS);
+	}
+
+}
+
+
+/******************************************************************************
+*
+*			OnePass App --->   송신기 --------> Event Server
+*
+*******************************************************************************/
+
+void SendParkingApp()
+{
+	int i;
+
+	NRF_LOG_RAW_INFO("===> SendParkingApp()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_ONEPASS;
+	
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  1;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	
+	SvrSendBuff[7] =  new_ble_addr.addr[3];		// 수신기 MAC 
+	SvrSendBuff[8] =  new_ble_addr.addr[4];		// 수신기 MAC
+	SvrSendBuff[9] =  new_ble_addr.addr[5];		// 수신기 MAC
+
+	SvrSendBuff[10] =  0x12;
+	SvrSendBuff[11] =  0x74;
+
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //SITE
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //DONG
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //HO
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	for(i=1; i<28; i++){
+		SvrSendBuff[28] = SvrSendBuff[28] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[29] =  COM_ETX;
+
+	NRF_LOG_INFO("SendParkingApp ===");
+	
+	SendToEventServer(&SvrSendBuff[0], 1);
+	nrf_delay_ms(500);
+
+	SendToEventServer(&SvrSendBuff[0], 30);
+
+
+	if(SystemManager.System_State == SYSTEM_NONE){
+
+		for(i=0; i<2; i++){
+			PKLedOn();
+			nrf_delay_ms(300);
+			PKLedOff();
+			nrf_delay_ms(300);
+		}
+	}
+	nrf_delay_ms(2000);		// 중복해서 들어오는 데이타로 인한 연속 동작 방지 
+
+}
+
+
+
+/******************************************************************************
+*
+*			Band --->   송신기 --------> Event Server
+*
+*******************************************************************************/
+
+
+void SendEmergencyBand()
+{
+	int i;
+
+	char tmpStr[10];
+
+	NRF_LOG_RAW_INFO("===> SendEmergencyBand()\n");
+
+	SystemManager.LedBlinkRun = 1;
+	SystemManager.LedBlinkTimer = 5000;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+	SystemManager.DevType = 0;
+	
+	SystemManager.SwitchOn = 1;
+
+	SystemManager.System_State = SYSTEM_EMERGENCY_SIREN;
+
+	PKBuzzerOn();
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_SMART_BAND;
+
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+	
+		strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+	
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+	
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+	
+	}else{						// 없으면 000000 전송
+		
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+	}
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	SvrSendBuff[10] =  0x12;
+	SvrSendBuff[11] =  0x72;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	for(i=1; i<28; i++){
+		SvrSendBuff[28] = SvrSendBuff[28] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[29] =  COM_ETX;
+
+	NRF_LOG_INFO("SendEmergencyBand===");
+
+//	SendToEventServer(&SvrSendBuff[0], 1);
+//	nrf_delay_ms(500);
+	
+	SendToEventServer(&SvrSendBuff[0], 30);
+
+
+	//NRF_LOG_RAW_INFO("================= EmergencyBand \n");
+	for( i=0; i<29; i++)
+	{
+		//NRF_LOG_RAW_INFO("%02x ", SvrSendBuff[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+	
+
+}
+
+
+
+
+
+
+void SendParkingBand()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> SendParkingBand()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_SMART_BAND;
+	
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  2;
+
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  0x12;
+	SvrSendBuff[11] =  0x73;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	for(i=1; i<28; i++){
+		SvrSendBuff[28] = SvrSendBuff[28] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[29] =  COM_ETX;
+
+	NRF_LOG_INFO("SendParkingBand ===");
+
+	SendToEventServer(&SvrSendBuff[0], 1);
+	nrf_delay_ms(500);
+
+	SendToEventServer(&SvrSendBuff[0], 30);
+
+
+//	SystemManager.SwitchOn = 1;
+	SystemManager.SwitchOn = 0;
+
+
+	if(SystemManager.System_State == SYSTEM_NONE){
+
+		for(i=0; i<2; i++){
+			PKLedOn();
+			nrf_delay_ms(300);
+			PKLedOff();
+			nrf_delay_ms(300);
+		}
+	}
+}
+
+
+
+/******************************************************************************
+*
+*			비상벨 --->   송신기 --------> Event Server
+*
+*******************************************************************************/
+
+void SendAck(uint8_t cmd)
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendAck()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	SvrSendBuff[2] =  0;
+
+	SvrSendBuff[3] =  cmd;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+	
+	SvrSendBuff[11] =  'A';
+	SvrSendBuff[12] =  'C';
+	SvrSendBuff[13] =  'K';
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+void SendEmergency()
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendEmergency()\n");
+
+
+	SystemManager.System_State = SYSTEM_EMERGENCY_SIREN;
+
+	if( SystemManager.RegRequst == 1 )		// 등록모드일경우 등록모드 해제, 비상모드 전환
+	{
+		SystemManager.RegRequst = 0;
+//			return;
+	}
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.TransferVerHigh;
+	SvrSendBuff[12] =  SystemManager.TransferVerLow;
+	SvrSendBuff[13] =  SystemManager.BatLevel;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendEmergency ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	SystemManager.SwitchOn = 1;
+
+	PKBuzzerOn();
+
+}
+
+
+
+
+void SendAlive()
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendAlive()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_ALIVE;
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.TransferVerHigh;
+	SvrSendBuff[12] =  SystemManager.TransferVerLow;
+	SvrSendBuff[13] =  SystemManager.BatLevel;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendAlive ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+void SendTest()
+{
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendTest()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_TEST;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.TransferVerHigh;
+	SvrSendBuff[12] =  SystemManager.TransferVerLow;
+	SvrSendBuff[13] =  SystemManager.BatLevel;
+
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendTest ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+// 송신기 등록시마다 송신기 데이타 전송 
+void SendCurrentRegDev()
+{
+
+	NRF_LOG_RAW_INFO("===> SendCurrentRegDev()\n");
+
+	uint8_t i;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	nrf_delay_ms(50);
+
+}
+
+
+
+
+// 비상벨 목록 응답.
+void Server_Answer_Reg_List()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+	uint8_t j;
+	
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Reg_List(%d EA)\n", RegMacPool.Count);
+
+
+	if( RegMacPool.Count == 0 )
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(j=1; j<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[j];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x ===== ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		nrf_delay_ms(50);
+
+		return;
+	}	
+
+
+	for( i=0; i<RegMacPool.Count; i++)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+	
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(j=1; j<18; j++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[j];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x =====> ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		SendToEventServer(&SvrSendBuff[0], 20);
+		nrf_delay_ms(200);
+
+	}
+	
+}
+  
+
+
+
+void Server_Answer_Call()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+	uint8_t j;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("Server_Answer_Call()");
+
+	SystemManager.System_State = SYSTEM_SERVER_COMM_REQ;
+
+	if( SystemManager.ServerCon == 0 )
+	{
+		SystemManager.LedBlinkRun = 1;
+		SystemManager.LedBlinkTimer = 5000;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+		SystemManager.DevType = 0;
+
+		SystemManager.SwitchOn = 1;
+
+  		PKBuzzerOn();
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_CALL_ANSWER;
+
+		if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+
+			strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+
+			tmpStr[6] = 0;
+			SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+
+			tmpStr[4] = 0;
+			SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+			
+			tmpStr[2] = 0;
+			SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		}else{						// 없으면 000000 전송
+			
+			SvrSendBuff[4] =  0;
+			SvrSendBuff[5] =  0;
+			SvrSendBuff[6] =  0;
+		}
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+		
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+
+		SvrSendBuff[11] = 0;
+		SvrSendBuff[12] = 0;
+		SvrSendBuff[13] = 0;
+		SvrSendBuff[14] = 0;
+		SvrSendBuff[15] = 0;
+		SvrSendBuff[16] = 0;
+		SvrSendBuff[17] = 0;
+		
+		for(j=1; j<18; j++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[j];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+		
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+	}
+}
+
+
+
+
+void Server_Answer_Version()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Version_Answer()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_VER_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  IES600RB_VER_HIGH;
+		SvrSendBuff[12] =  IES600RB_VER_LOW;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+
+	}
+
+
+	nrf_delay_ms(1000);
+
+#if 0
+	for(i=0; i<5; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+#endif
+}
+
+
+void Server_Answer_Upgread()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Upgread()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_UPGREAD_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  IES600RB_VER_HIGH;
+		SvrSendBuff[12] =  IES600RB_VER_LOW;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+	}
+
+
+	NRF_LOG_RAW_INFO("================================================================================\n");
+	NRF_LOG_RAW_INFO("======================== Reboot To BootLoad Start ==============================\n");
+	NRF_LOG_RAW_INFO("================================================================================\n");	
+
+	nrf_delay_ms(1000);
+
+	for(i=0; i<5; i++){
+	
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+
+	nrf_delay_ms(3000);
+
+
+	nrf_power_gpregret_set(0xB1);
+	NVIC_SystemReset();
+	
+}
+
+
+
+
+// 사용않함
+void SendEmergencyLocal()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;	
+	
+	SendToEventServer(&SvrSendBuff[0], 20);
+	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+
+}
+
+
+
+// 송신기 테스트 버튼눌렀을시 동작 
+void AliveTest()
+{
+	int cnt = 0;
+
+	int buz_cnt = 0;
+	int led_cnt = 0;
+	char blink_cnt = 0;
+	char blink_flag = 0;
+	
+
+	uint8_t ex = 1;
+
+	NRF_LOG_RAW_INFO("Void AliveTest\n");
+
+#if 0
+
+	PKBuzzerOn();
+	PKLedOn();
+
+	blink_flag = 1;
+
+	while(ex){
+
+		if(SystemTimer.MS_100_TICK){
+
+			SystemTimer.MS_100_TICK = 0;
+
+			cnt++;
+			
+			if(cnt >= 5){
+
+				cnt = 0;
+
+				buz_cnt++;
+
+				if(buz_cnt >= 2){	// 10sec
+					PKBuzzerOff();
+				}
+
+				blink_flag = !blink_flag;
+			
+	 			if(blink_flag){
+					PKLedOn();
+				}else{
+					PKLedOff();
+
+					blink_cnt++;
+
+					if(blink_cnt >= 3)
+						ex = 0;
+				}
+			}
+		}
+	}
+
+//	SystemManager.LedBlinkRun = COM_TYPE_SVR_TEST;
+//	SystemManager.LedBlinkTimer = 3300;
+//	SystemTimer.LED_TOGGLE_TIMER = 0;
+#else
+
+  	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+	SystemManager.LedBlinkRun = COM_TYPE_SVR_TEST;
+	SystemManager.LedBlinkTimer = 3300;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+#endif
+	
+}
+
+
+
+
+
+
+void LedToggle()
+{
+
+	static char toggle = 0;
+
+#if 0
+	if( SystemManager.RegRequst )
+	{
+
+		if( SystemTimer.DEV_REG_TIMER >= 60000 )
+		{
+			SystemManager.RegRequst = 0;
+			PKLedOff();
+			SystemManager.LedBlinkRun = 0;
+		}
+	}
+#endif
+	
+	// 송신기 등록모드시 항상 ON
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG )
+	{
+		PKLedOn();
+		return;
+	}
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG+1 )
+	{
+
+		if( SystemManager.RegRequst == 1 )
+		{
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG;
+				PKLedOn(); 	
+				return;
+			}
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+		if( toggle++ & 0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_TEST )
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff();	
+			PKBuzzerOff();
+
+			return;
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}	
+
+
+
+
+	if( SystemManager.SwitchOn == 0 )
+		return;
+
+	if( SystemManager.LedBlinkRun == 0 )
+		return;
+
+
+#if 0
+	if( SystemManager.LedBlinkTimer < 0 )
+	{
+
+		SystemManager.LedBlinkRun = 0;
+		PKLedOff();  	
+
+		return;
+	}
+#endif
+
+	if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+		return;
+
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+	if( toggle++&0x01)
+	{
+		PKLedOn();
+	}else{
+		PKLedOff();
+	}
+}
+
+

+ 1427 - 0
BLE_Central.si4project/Backup/our_service(3473).c

@@ -0,0 +1,1427 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 <stdint.h>
+#include <string.h>
+#include "nrf_gpio.h"
+#include "our_service.h"
+#include "ble_srv_common.h"
+#include "app_error.h"
+#include "SEGGER_RTT.h"
+#include "board_gpi.h"
+#include "nrf_log.h"
+
+#include "sysmgr.h"
+#include "main.h"
+#include "nrf_power.h"
+
+
+char SvrRxBuffer[100];
+int SvrRxBufferPos;
+char SvrEvent;
+
+
+stSystemTimer SystemTimer;
+stSystemManager SystemManager;
+char SvrSendBuff[50];
+
+void delete_all_begin(void);
+
+
+
+void USART_DataCheck()
+{
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SystemManager.RxValild )
+	{
+
+		SvrRxBuffer[SvrRxBufferPos] = 0;
+
+		//printf("[%d]%s\r\n", SvrRxBufferPos, SvrRxBuffer);
+		SystemManager.RxValild = 0;
+
+		if( SvrRxBufferPos == 20 )
+		{
+			SystemManager.RxEvent = 1;
+		}
+
+		SvrRxBufferPos = 0;
+	}
+
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SvrRxBufferPos )
+	{
+		SystemManager.RxValild = 0;
+		SvrRxBufferPos = 0;
+	}
+
+}
+
+
+void USART_Handler(void)
+{
+
+	char ch;
+	
+	uint8_t cr;
+
+// 	SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	if( app_uart_get(&cr) == NRF_SUCCESS )
+	{
+		SystemManager.RxValild = 1;
+		SvrRxBuffer[SvrRxBufferPos++] = cr;
+		SvrRxBufferPos %= 100;
+		SystemTimer.UART_LAST_RECV_TIMER = 0;
+	}
+}
+
+
+
+#define SERVER_COMM_DATA_LEN		0x08
+
+
+#define COM_TYPE_SVR_EMG_REQ			0x01		// SERVER EMG 응답
+#define COM_TYPE_SVR_NORMAL   			0x02		// 수신기 Normal 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_TALKING  			0x03		// 수신기 Talking 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_DISCON   			0x04		// 수신기 DisConnect 신호	( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_BUSY     			0x05		// 수신기 Busy 신호			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_ALIVE    			0x06		// 수신기 Alive 신호			( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_MIC      			0x07		// 수신기 Mic 상태 			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_REG_REQ		0x08		// 송신기 등록 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SEV_RECV_REG_ANSWER	0x09		// 송신기 등록 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_INIT_REQ		0x0a		// 수신기 초기화 요청 		( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_RECV_INIT_ANSWER	0x0b		// 수신기 초기화 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_LIST_REQ		0x0c		// 송신기 목록 요청		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_LIST_ANSWER	0x0d		// 송신기 목록 응답		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_VER_REQ			0x10		// 수신기 버전 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_VER_ANSWER			0x11		// 수신기 버전 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_CALL_REQ			0x12		// 수신기 통화 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_CALL_ANSWER		0x13		// 수신기 통화 응답 		( IES600 --> BleEventServer )
+
+#define COM_TYPE_SVR_UPGREAD_REQ		0x14		// 수신기 업그레이드 요청	( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_UPGREAD_ANSWER		0x15		// 수신기 업그레이드 응답	( IES600 --> BleEventServer ) 
+
+
+
+
+
+/* 이벤트 서버에서 20byte 들어왔을때 */
+
+
+void ParseEventServer()
+{
+
+	int i;
+
+	if( SystemManager.RxEvent == 0 )
+		return;
+
+	SystemManager.RxEvent = 0;
+
+
+	NRF_LOG_RAW_INFO("\n\n");
+	NRF_LOG_RAW_INFO("SERVER TO DATA : ")
+	for( i=0; i<20; i++)
+	{
+		NRF_LOG_RAW_INFO("0x%02x ", SvrRxBuffer[i]);
+	}
+	NRF_LOG_RAW_INFO("\n\n");
+
+
+	if(SvrRxBuffer[0] != 0x02)
+		return;
+
+
+	switch(SvrRxBuffer[1]){
+
+		case COM_TYPE_SVR:
+
+			switch(SvrRxBuffer[3]){
+
+				// 수신기 대기상태 요청
+				case COM_TYPE_SVR_NORMAL:
+
+					NRF_LOG_INFO("Recv : Normal");
+
+					PKLedOff();
+					PKBuzzerOff();
+					PKMicOff();
+					SystemManager.SwitchOn = 0;
+ 
+				break;
+
+				// 수신기 통화상태 요청 
+				case COM_TYPE_SVR_TALKING:
+
+					NRF_LOG_INFO("Recv : Talking");
+
+					PKLedOn();
+					PKBuzzerOff();
+					SystemManager.SwitchOn = 0;
+				break;
+
+				// 수신기 서버와 통화 종료 요청
+				case COM_TYPE_SVR_DISCON:
+					
+					NRF_LOG_INFO("Recv : Disconnect");
+
+					SystemManager.SwitchOn = 0;
+					//bsp_board_leds_off();
+				break;
+
+				// 서버 Busy 상태 알림
+				case COM_TYPE_SVR_BUSY:
+
+					NRF_LOG_INFO("Recv : Busy");
+
+				break;
+
+				// 송신기 Alive신호 서버로 전송
+				case COM_TYPE_SVR_ALIVE:
+
+					NRF_LOG_INFO("Recv : Keep Alive");
+				break;
+
+				// 수신기 마이크 상태 변경 요청 
+				case COM_TYPE_SVR_MIC:
+					
+					NRF_LOG_INFO("Recv : mic on/off");
+
+					if( SvrRxBuffer[11] == 0 )
+					{  
+						NRF_LOG_INFO("mic on"); 
+						NRF_LOG_INFO("speaker off");  
+						PKSpeakerOff();
+						PKMicOn();
+						PKBuzzerOff();
+						PKLedOn();
+						SystemManager.SwitchOn = 0;
+					}else{
+						NRF_LOG_INFO("mic off"); 
+						NRF_LOG_INFO("speaker on");  
+						PKMicOff();
+						PKSpeakerOn();
+						PKLedOn();
+					}
+				break;
+
+				// 송신기 등록요청
+				case COM_TYPE_SVR_RECV_REG_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_REG");
+
+					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG;
+					SystemManager.RegRequst = 1;
+
+					SendAck(COM_TYPE_SVR_RECV_REG+1);
+
+					SystemTimer.DEV_REG_TIMER = 0;
+
+				break;
+
+				// 송신기 등록 초기화 요청
+				case COM_TYPE_SVR_RECV_INIT_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_INIT");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_INIT;
+//					SystemManager.LedBlinkTimer = 2500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+					
+					SendAck(COM_TYPE_SVR_RECV_INIT+1);
+
+					//for( i=0; i<RegMacPool.Count; i++)
+					//{
+					//RegMacDelteAll();
+					// }
+					memset( &RegMacPool, 0, sizeof(RegMacPool));
+
+					delete_all_begin();
+
+					for(i=0; i<2; i++){
+						PKLedOn();
+						nrf_delay_ms(300);
+						PKLedOff();
+						nrf_delay_ms(300);
+					}
+				break;
+
+				// 송신기에 등록된 수신기 리스트 요청 
+				case COM_TYPE_SVR_RECV_LIST_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_LIST");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_LIST;
+//					SystemManager.LedBlinkTimer = 1500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+
+					Server_Answer_Reg_List();
+
+					PKLedOn();
+					nrf_delay_ms(300);
+					PKLedOff();
+
+				break;
+
+				// 서버로 부터 통화 요청
+				case COM_TYPE_SVR_CALL_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_CALL_REQ");
+
+					Server_Answer_Call();
+
+				break;
+
+				// 서버로 부터 수신기 버전 요청
+				case COM_TYPE_SVR_VER_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_VER_REQ");
+
+					Server_Answer_Version();
+
+				break;
+
+
+				case COM_TYPE_SVR_UPGREAD_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_UPGREAD_REQ");
+					
+					Server_Answer_Upgread();
+
+				break;
+			}
+		break;
+
+		case COM_TYPE_BAND:
+
+		break;
+	}
+}
+
+
+
+void SendToEventServer(char* data, int len)
+{
+
+	int i;
+
+	NRF_LOG_RAW_INFO("SendToEventServer ==> ");
+	for( i=0; i<len; i++)
+	{
+		NRF_LOG_RAW_INFO("%02x ", data[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+
+
+	for( i=0; i<len; i++)
+	{
+		while (app_uart_put(data[i]) != NRF_SUCCESS);
+	}
+
+}
+
+
+
+
+
+void SendParkingApp()
+{
+	int i;
+
+	NRF_LOG_RAW_INFO("===> SendParkingApp()\n");
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  3;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  1;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	
+	SvrSendBuff[7] =  new_ble_addr.addr[3];		// 수신기 MAC 
+	SvrSendBuff[8] =  new_ble_addr.addr[4];		// 수신기 MAC
+	SvrSendBuff[9] =  new_ble_addr.addr[5];		// 수신기 MAC
+
+	SvrSendBuff[10] =  0x11;
+	SvrSendBuff[11] =  0x74;
+
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //SITE
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //DONG
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //HO
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	SvrSendBuff[28] =  COM_ETX;
+
+
+	NRF_LOG_INFO("SendParkingApp ===");
+	
+	SendToEventServer(&SvrSendBuff[0], 1);
+
+	SendToEventServer(&SvrSendBuff[0], 29);
+
+
+	for(i=0; i<2; i++){
+		PKLedOn();
+		nrf_delay_ms(300);
+		PKLedOff();
+		nrf_delay_ms(300);
+	}
+
+	nrf_delay_ms(2000);		// 중복해서 들어오는 데이타로 인한 연속 동작 방지 
+
+}
+
+
+
+
+
+void SendEmergencyBand()
+{
+	int i;
+
+	char tmpStr[10];
+
+	NRF_LOG_RAW_INFO("===> SendEmergencyBand()\n");
+
+	SystemManager.LedBlinkRun = 1;
+	SystemManager.LedBlinkTimer = 5000;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+	SystemManager.DevType = 0;
+	
+	SystemManager.SwitchOn = 1;
+
+	PKBuzzerOn();
+  
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  2;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+	
+		strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+	
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+	
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+	
+	}else{						// 없으면 000000 전송
+		
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+	}
+
+
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	SvrSendBuff[10] =  0x11;
+	SvrSendBuff[11] =  0x72;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	SvrSendBuff[28] =  COM_ETX;
+
+	NRF_LOG_INFO("SendEmergencyBand===");
+
+	SendToEventServer(&SvrSendBuff[0], 1);
+
+	nrf_delay_ms(500);
+	
+	SendToEventServer(&SvrSendBuff[0], 29);
+
+
+	//NRF_LOG_RAW_INFO("================= EmergencyBand \n");
+	for( i=0; i<29; i++)
+	{
+		//NRF_LOG_RAW_INFO("%02x ", SvrSendBuff[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+	
+
+}
+
+
+
+
+
+
+void SendParkingBand()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> SendParkingBand()\n");
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  2;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  2;
+
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  0x11;
+	SvrSendBuff[11] =  0x73;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	SvrSendBuff[28] =  COM_ETX;
+
+//	NRF_LOG_INFO("SendParkingBand ===");
+	SendToEventServer(&SvrSendBuff[0], 1);
+
+	SendToEventServer(&SvrSendBuff[0], 29);
+
+//	SystemManager.SwitchOn = 1;
+	SystemManager.SwitchOn = 0;
+
+
+	for(i=0; i<2; i++){
+		PKLedOn();
+		nrf_delay_ms(300);
+		PKLedOff();
+		nrf_delay_ms(300);
+	}
+
+}
+
+
+
+/******************************************************************************
+*
+*						 송신기 --------> Event Server
+*
+*******************************************************************************/
+
+void SendAck(uint8_t cmd)
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendAck()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+
+	SvrSendBuff[3] =  cmd;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+	
+	SvrSendBuff[11] =  'A';
+	SvrSendBuff[12] =  'C';
+	SvrSendBuff[13] =  'K';
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+void SendEmergency()
+{
+
+	NRF_LOG_RAW_INFO("===> SendEmergency()\n");
+
+	if( SystemManager.RegRequst == 1 )
+	{
+		SystemManager.RegRequst = 0;
+			return;
+	}
+  
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.BatLevel;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendEmergency ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	SystemManager.SwitchOn = 1;
+
+	PKBuzzerOn();
+
+}
+
+
+
+
+void SendAlive()
+{
+
+	NRF_LOG_RAW_INFO("===> SendAlive()\n");
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_ALIVE;
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;		// Data Length
+
+	SvrSendBuff[11] =  SystemManager.BatLevel;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendAlive ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+// 김효섭 차장 요청을 추가
+void SendTest()
+{
+
+	NRF_LOG_RAW_INFO("===> SendAlive()\n");
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_TEST;
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;		// Data Length
+
+	SvrSendBuff[11] =  SystemManager.BatLevel;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendAlive ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+// 송신기 등록시마다 송신기 데이타 전송 
+void SendCurrentRegDev()
+{
+
+	NRF_LOG_RAW_INFO("===> SendCurrentRegDev()\n");
+
+	uint8_t i;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+
+	SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	nrf_delay_ms(50);
+
+}
+
+
+
+
+// 비상벨 목록 응답.
+void Server_Answer_Reg_List()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Reg_List(%d)\n", RegMacPool.Count);
+
+#if 1
+	if( RegMacPool.Count == 0 )
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x ===== ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		nrf_delay_ms(50);
+	}	
+#endif	
+
+	for( i=0; i<RegMacPool.Count; i++)
+	{
+
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+		
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x ===== ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		SendToEventServer(&SvrSendBuff[0], 20);
+		nrf_delay_ms(200);
+
+	}
+}
+  
+
+
+
+void Server_Answer_Call()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("Server_Answer_Call()");
+	
+	if( SystemManager.ServerCon == 0 )
+	{
+		SystemManager.LedBlinkRun = 1;
+		SystemManager.LedBlinkTimer = 5000;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+		SystemManager.DevType = 0;
+
+		SystemManager.SwitchOn = 1;
+
+  		PKBuzzerOn();
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+
+		SvrSendBuff[3] =  COM_TYPE_SVR_CALL_ANSWER;
+
+		if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+
+			strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+
+			tmpStr[6] = 0;
+			SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+
+			tmpStr[4] = 0;
+			SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+			
+			tmpStr[2] = 0;
+			SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		}else{						// 없으면 000000 전송
+			
+			SvrSendBuff[4] =  0;
+			SvrSendBuff[5] =  0;
+			SvrSendBuff[6] =  0;
+		}
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+		
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+
+		SvrSendBuff[11] = 0;
+		SvrSendBuff[12] = 0;
+		SvrSendBuff[13] = 0;
+		SvrSendBuff[14] = 0;
+		SvrSendBuff[15] = 0;
+		SvrSendBuff[16] = 0;
+		SvrSendBuff[17] = 0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+		
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+	}
+}
+
+
+
+
+void Server_Answer_Version()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Version_Answer()\n");
+
+
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+
+		SvrSendBuff[3] =  COM_TYPE_SVR_VER_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  IES600RB_VER_HIGH;
+		SvrSendBuff[12] =  IES600RB_VER_LOW;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+
+	}
+
+
+	NRF_LOG_RAW_INFO("================================================================================\n");
+	NRF_LOG_RAW_INFO("======================== Reboot To BootLoad Start ==============================\n");
+	NRF_LOG_RAW_INFO("================================================================================\n");	
+
+	nrf_delay_ms(1000);
+
+	for(i=0; i<5; i++){
+	
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+
+	nrf_power_gpregret_set(0xB1);
+	NVIC_SystemReset();
+
+
+}
+
+
+void Server_Answer_Upgread()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Upgread()\n");
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+
+		SvrSendBuff[3] =  COM_TYPE_SVR_UPGREAD_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+	}
+
+
+	NRF_LOG_RAW_INFO("================================================================================\n");
+	NRF_LOG_RAW_INFO("======================== Reboot To BootLoad Start ==============================\n");
+	NRF_LOG_RAW_INFO("================================================================================\n");	
+
+	nrf_delay_ms(1000);
+
+	for(i=0; i<5; i++){
+	
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+
+	nrf_power_gpregret_set(0xB1);
+	NVIC_SystemReset();
+
+	
+}
+
+
+
+
+// 사용않함
+void SendEmergencyLocal()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+	
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0xaa;
+	SvrSendBuff[5] =  0xaa;
+	SvrSendBuff[6] =  0xaa;
+	SvrSendBuff[7] =  0xbb;
+	SvrSendBuff[8] =  0xbb;
+	SvrSendBuff[9] =  0xbb;
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+
+	SvrSendBuff[19] =  COM_ETX;	
+	
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+
+}
+
+
+
+// 송신기 테스트 버튼눌렀을시 동작 
+void AliveTest()
+{
+
+  	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+	SystemManager.LedBlinkRun = COM_TYPE_SVR_ALIVE;
+	SystemManager.LedBlinkTimer = 3300;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+}
+
+
+
+
+#if 0
+// 사용않함
+void SendTest()
+{
+	if( SystemTimer.SEND_TEST_TIMER < 3000 )
+		return;
+
+	SystemTimer.SEND_TEST_TIMER = 0;
+
+	SendEmergency();
+  
+}
+#endif
+
+
+void LedToggle()
+{
+
+	static char toggle = 0;
+
+	if( SystemManager.RegRequst )
+	{
+
+		if( SystemTimer.DEV_REG_TIMER >= 60000 )
+		{
+			SystemManager.RegRequst = 0;
+			PKLedOff();
+			SystemManager.LedBlinkRun = 0;
+		}
+	}
+  
+	// 송신기 등록모드시 항상 ON
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG )
+	{
+		PKLedOn();
+		return;
+	}
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG+1 )
+	{
+
+		if( SystemManager.RegRequst == 1 )
+		{
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG;
+				PKLedOn(); 	
+				return;
+			}
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+
+
+#if 0
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_PARKING )
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff(); 	
+			return;
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+#endif
+
+#if 0	
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_INIT )
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff();	  
+
+			return;
+		}
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+#endif
+
+
+#if 0
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_LIST || SystemManager.LedBlinkRun == COM_TYPE_SVR_VER_REQ)
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff();	  
+
+			return;
+		}
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+#endif
+
+
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_ALIVE )
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff();	
+			PKBuzzerOff();
+
+			return;
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}	
+
+	if( SystemManager.SwitchOn == 0 )
+		return;
+
+	if( SystemManager.LedBlinkRun == 0 )
+		return;
+
+
+#if 0
+	if( SystemManager.LedBlinkTimer < 0 )
+	{
+
+		SystemManager.LedBlinkRun = 0;
+		PKLedOff();  	
+
+		return;
+	}
+#endif
+
+	if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+		return;
+
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+	if( toggle++&0x01)
+	{
+		PKLedOn();
+	}else{
+		PKLedOff();
+	}
+}
+
+

+ 1578 - 0
BLE_Central.si4project/Backup/our_service(3512).c

@@ -0,0 +1,1578 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 <stdint.h>
+#include <string.h>
+#include "nrf_gpio.h"
+#include "our_service.h"
+#include "ble_srv_common.h"
+#include "app_error.h"
+#include "SEGGER_RTT.h"
+#include "board_gpi.h"
+#include "nrf_log.h"
+
+#include "sysmgr.h"
+#include "main.h"
+#include "nrf_power.h"
+
+
+char SvrRxBuffer[100];
+int SvrRxBufferPos;
+char SvrEvent;
+
+
+stSystemTimer SystemTimer;
+stSystemManager SystemManager;
+char SvrSendBuff[50];
+char SvrSendBuff_bak[50];
+
+void delete_all_begin(void);
+
+
+
+void USART_DataCheck()
+{
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SystemManager.RxValild )
+	{
+
+		SvrRxBuffer[SvrRxBufferPos] = 0;
+
+//		printf("[%d]%s\r\n", SvrRxBufferPos, SvrRxBuffer);
+		SystemManager.RxValild = 0;
+
+		if( SvrRxBufferPos == 20 )
+		{
+			SystemManager.RxEvent = 1;
+			NRF_LOG_RAW_INFO("==========================>\n\n");
+		}
+
+		SvrRxBufferPos = 0;
+	}
+
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SvrRxBufferPos )
+	{
+		SystemManager.RxValild = 0;
+		SvrRxBufferPos = 0;
+	}
+
+}
+
+
+void USART_Handler(void)
+{
+
+	char ch;
+	
+	uint8_t cr;
+
+// 	SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	if( app_uart_get(&cr) == NRF_SUCCESS )
+	{
+		SystemManager.RxValild = 1;
+		SvrRxBuffer[SvrRxBufferPos++] = cr;
+		SvrRxBufferPos %= 100;
+		SystemTimer.UART_LAST_RECV_TIMER = 0;
+	}
+}
+
+
+
+
+
+
+/* 이벤트 서버에서 20byte 들어왔을때 */
+
+
+void ParseEventServer()
+{
+
+	int i;
+
+	if( SystemManager.RxEvent == 0 )
+		return;
+
+	SystemManager.RxEvent = 0;
+
+
+	NRF_LOG_RAW_INFO("\n\n");
+	NRF_LOG_RAW_INFO("SERVER ==> RECEVER DATA : ")
+
+	for( i=0; i<20; i++)
+	{
+		NRF_LOG_RAW_INFO("0x%02x ", SvrRxBuffer[i]);
+	}
+	NRF_LOG_RAW_INFO("\n\n");
+
+
+	if(SvrRxBuffer[0] != 0x02)
+		return;
+
+	switch(SvrRxBuffer[1]){
+
+		case NUM_TYPE_SVR:
+		case COM_TYPE_BAND:		//
+
+			switch(SvrRxBuffer[3]){
+
+
+				// 수신기 비상신호에 대한 ACK 신호
+				case COM_TYPE_SVR_EMG_ACK:
+
+					SystemManager.Emg_Ack_Flag = 0;
+
+				break;
+
+
+				// 수신기 대기상태 요청
+				case COM_TYPE_SVR_NORMAL:
+
+					SystemManager.System_State = SYSTEM_NONE;
+
+					NRF_LOG_INFO("Recv : Normal");
+
+					PKLedOff();
+					PKBuzzerOff();
+					PKMicOff();
+					SystemManager.SwitchOn = 0;
+ 
+				break;
+
+				// 수신기 통화상태 요청 
+				case COM_TYPE_SVR_TALKING:
+
+					NRF_LOG_INFO("Recv : Talking");
+
+					PKLedOn();
+					PKBuzzerOff();
+					SystemManager.SwitchOn = 0;
+				break;
+
+				// 수신기 서버와 통화 종료 요청
+				case COM_TYPE_SVR_DISCON:
+					
+					NRF_LOG_INFO("Recv : Disconnect");
+
+					SystemManager.SwitchOn = 0;
+					//bsp_board_leds_off();
+				break;
+
+				// 서버 Busy 상태 알림
+				case COM_TYPE_SVR_BUSY:
+
+					NRF_LOG_INFO("Recv : Busy");
+
+				break;
+
+				// 송신기 Alive신호 서버로 전송
+				case COM_TYPE_SVR_ALIVE:
+
+					NRF_LOG_INFO("Recv : Keep Alive");
+
+				break;
+
+				// 수신기 마이크 상태 변경 요청 
+				case COM_TYPE_SVR_MIC:
+
+					SystemManager.System_State = SYSTEM_SERVER_COMM;
+
+					SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
+				
+					NRF_LOG_INFO("Recv : mic on/off");
+
+					
+					if( SvrRxBuffer[11] == 0 )
+					{  
+						NRF_LOG_INFO("mic on"); 
+						NRF_LOG_INFO("speaker off");  
+						PKSpeakerOff();
+						PKMicOn();
+						PKBuzzerOff();
+						PKLedOn();
+						SystemManager.SwitchOn = 0;
+					}else{
+						NRF_LOG_INFO("mic off"); 
+						NRF_LOG_INFO("speaker on");  
+						PKMicOff();
+						PKSpeakerOn();
+						PKLedOn();
+					}
+				break;
+
+				// 송신기 등록요청
+				case COM_TYPE_SVR_RECV_REG_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_REG_REQ");
+
+					if(SystemManager.System_State == SYSTEM_NONE){
+
+						SystemManager.System_State = SYSTEM_REGISTER;
+
+						SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_REQ;
+						SystemManager.RegRequst = 1;
+
+//						SendAck(COM_TYPE_SVR_RECV_REG+1);
+						SendAck(COM_TYPE_SVR_RECV_REG_ANSWER);
+
+						SystemTimer.DEV_REG_TIMER = 0;
+					}else{
+						
+						NRF_LOG_INFO("SYSTEM is BUSY : [%d]\n", SystemManager.System_State);
+					}
+
+				break;
+
+				// 송신기 등록 초기화 요청
+				case COM_TYPE_SVR_RECV_INIT_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_INIT_REQ");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_INIT;
+//					SystemManager.LedBlinkTimer = 2500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+					
+//					SendAck(COM_TYPE_SVR_RECV_INIT+1);
+					SendAck(COM_TYPE_SVR_RECV_INIT_ANSWER);
+
+
+					//for( i=0; i<RegMacPool.Count; i++)
+					//{
+					//RegMacDelteAll();
+					// }
+					memset( &RegMacPool, 0, sizeof(RegMacPool));
+
+					delete_all_begin();
+
+					for(i=0; i<2; i++){
+						PKLedOn();
+						nrf_delay_ms(300);
+						PKLedOff();
+						nrf_delay_ms(300);
+					}
+				break;
+
+				// 송신기에 등록된 수신기 리스트 요청 
+				case COM_TYPE_SVR_RECV_LIST_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_LIST_REQ");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_LIST;
+//					SystemManager.LedBlinkTimer = 1500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+
+					Server_Answer_Reg_List();
+
+					PKLedOn();
+					nrf_delay_ms(300);
+					PKLedOff();
+
+				break;
+
+				// 서버로 부터 통화 요청
+				case COM_TYPE_SVR_CALL_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_CALL_REQ");
+
+					Server_Answer_Call();
+
+				break;
+
+				// 서버로 부터 수신기 버전 요청
+				case COM_TYPE_SVR_VER_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_VER_REQ");
+
+					Server_Answer_Version();
+
+				break;
+
+
+				case COM_TYPE_SVR_UPGREAD_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_UPGREAD_REQ");
+					
+					Server_Answer_Upgread();
+
+				break;
+			}
+		break;
+
+//		case COM_TYPE_BAND:
+
+//		break;
+	}
+}
+
+
+
+void SendToEventServer(char* data, int len)
+{
+
+	int i;
+
+	NRF_LOG_RAW_INFO("SendToEventServer ==> ");
+	
+	for( i=0; i<len; i++)
+	{
+		NRF_LOG_RAW_INFO("%02X ", data[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+
+
+	for(i=0; i<len; i++)
+	{
+		while (app_uart_put(data[i]) != NRF_SUCCESS);
+	}
+
+}
+
+
+
+
+
+
+/******************************************************************************
+*
+*			OnePass App --->   송신기 --------> Event Server
+*
+*******************************************************************************/
+
+void SendParkingApp()
+{
+	int i;
+
+	NRF_LOG_RAW_INFO("===> SendParkingApp()\n");
+
+
+  	SystemManager.SwitchOn = 0;
+	SystemManager.LedBlinkRun = COM_TYPE_APP_PARKING;
+	SystemManager.LedBlinkTimer = 1200;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_ONEPASS;
+	
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  1;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	
+	SvrSendBuff[7] =  new_ble_addr.addr[3];		// 수신기 MAC 
+	SvrSendBuff[8] =  new_ble_addr.addr[4];		// 수신기 MAC
+	SvrSendBuff[9] =  new_ble_addr.addr[5];		// 수신기 MAC
+
+	SvrSendBuff[10] =  0x12;
+	SvrSendBuff[11] =  0x74;
+
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //SITE
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //DONG
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //HO
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	for(i=1; i<28; i++){
+		SvrSendBuff[28] = SvrSendBuff[28] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[29] =  COM_ETX;
+
+	NRF_LOG_INFO("SendParkingApp ===");
+	
+//	SendToEventServer(&SvrSendBuff[0], 1);
+//	nrf_delay_ms(500);
+
+	SendToEventServer(&SvrSendBuff[0], 30);
+
+
+//	nrf_delay_ms(2000);		// 중복해서 들어오는 데이타로 인한 연속 동작 방지 
+
+}
+
+
+
+/******************************************************************************
+*
+*			Band --->   송신기 --------> Event Server
+*
+*******************************************************************************/
+
+
+void SendEmergencyBand()
+{
+	int i;
+
+	char tmpStr[10];
+
+	NRF_LOG_RAW_INFO("===> SendEmergencyBand()\n");
+
+	SystemManager.LedBlinkRun = 1;
+	SystemManager.LedBlinkTimer = 5000;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+	SystemManager.DevType = 0;
+	
+	SystemManager.SwitchOn = 1;
+
+	SystemManager.System_State = SYSTEM_EMERGENCY_SIREN;
+	SystemManager.Emg_Ack_Flag = 2;
+
+	PKBuzzerOn();
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_SMART_BAND;
+
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+	
+		strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+	
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+	
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+	
+	}else{						// 없으면 000000 전송
+		
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+	}
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	SvrSendBuff[10] =  0x12;
+	SvrSendBuff[11] =  0x72;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	for(i=1; i<28; i++){
+		SvrSendBuff[28] = SvrSendBuff[28] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[29] =  COM_ETX;
+
+	memcpy(SvrSendBuff_bak, SvrSendBuff, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("SendEmergencyBand===");
+
+
+	SendToEventServer(&SvrSendBuff[0], 30);
+
+
+#if 0
+	//NRF_LOG_RAW_INFO("================= EmergencyBand \n");
+	for( i=0; i<29; i++)
+	{
+		//NRF_LOG_RAW_INFO("%02x ", SvrSendBuff[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+#endif
+
+}
+
+
+
+
+void SendParkingBand()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> SendParkingBand()\n");
+
+	SystemManager.DevType = 0;
+	SystemManager.LedBlinkRun = COM_TYPE_BAND_PARKING;
+	SystemManager.LedBlinkTimer = 1200;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+  	SystemManager.SwitchOn = 0;
+
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_SMART_BAND;
+	
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  2;
+
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  0x12;
+	SvrSendBuff[11] =  0x73;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	for(i=1; i<28; i++){
+		SvrSendBuff[28] = SvrSendBuff[28] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[29] =  COM_ETX;
+
+	NRF_LOG_INFO("SendParkingBand ===");
+
+	SendToEventServer(&SvrSendBuff[0], 30);
+
+}
+
+
+
+void ReSendEmergency()
+{
+
+	NRF_LOG_RAW_INFO("===> ReSendEmergency()\n");
+
+	memcpy(SvrSendBuff, SvrSendBuff_bak, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("ReSendEmergency ===");
+	
+	switch(SystemManager.Emg_Ack_Flag){
+
+		case 1:	// 비상벨 EMG
+			SendToEventServer(&SvrSendBuff[0], 20);
+		break;
+
+		case 2:	// 밴드 EMG
+			SendToEventServer(&SvrSendBuff[0], 30);
+		break;
+	}
+}
+
+
+
+
+/******************************************************************************
+*
+*			비상벨 --->   송신기 --------> Event Server
+*
+*******************************************************************************/
+
+void SendAck(uint8_t cmd)
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendAck()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	SvrSendBuff[2] =  0;
+
+	SvrSendBuff[3] =  cmd;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+	
+	SvrSendBuff[11] =  'A';
+	SvrSendBuff[12] =  'C';
+	SvrSendBuff[13] =  'K';
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+void SendEmergency()
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendEmergency()\n");
+
+
+	SystemManager.System_State = SYSTEM_EMERGENCY_SIREN;
+
+	SystemManager.Emg_Ack_Flag = 1;
+
+
+	if( SystemManager.RegRequst == 1 )		// 등록모드일경우 등록모드 해제, 비상모드 전환
+	{
+		SystemManager.RegRequst = 0;
+//			return;
+	}
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.TransferVerHigh;
+	SvrSendBuff[12] =  SystemManager.TransferVerLow;
+	SvrSendBuff[13] =  SystemManager.BatLevel;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	memcpy(SvrSendBuff_bak, SvrSendBuff, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("SendEmergency ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	SystemManager.SwitchOn = 1;
+
+	PKBuzzerOn();
+
+}
+
+
+
+
+void SendAlive()
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendAlive()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_ALIVE;
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.TransferVerHigh;
+	SvrSendBuff[12] =  SystemManager.TransferVerLow;
+	SvrSendBuff[13] =  SystemManager.BatLevel;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendAlive ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+void SendTest()
+{
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendTest()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+	
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_TEST;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.TransferVerHigh;
+	SvrSendBuff[12] =  SystemManager.TransferVerLow;
+	SvrSendBuff[13] =  SystemManager.BatLevel;
+
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendTest ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+// 송신기 등록시마다 송신기 데이타 전송 
+void SendCurrentRegDev()
+{
+
+	NRF_LOG_RAW_INFO("===> SendCurrentRegDev()\n");
+
+	uint8_t i;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	nrf_delay_ms(50);
+
+}
+
+
+
+
+// 비상벨 목록 응답.
+void Server_Answer_Reg_List()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+	uint8_t j;
+	
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Reg_List (%d EA)\n", RegMacPool.Count);
+
+	i = 0;
+	
+	if( RegMacPool.Count == 0 )
+	{
+
+#if 1
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+#endif
+
+		
+		for(j=1; j<18; j++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[j];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x ===== ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		nrf_delay_ms(50);
+
+		return;
+	}	
+
+
+	for( i=0; i<RegMacPool.Count; i++)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+	
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(j=1; j<18; j++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[j];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x =====> ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		SendToEventServer(&SvrSendBuff[0], 20);
+		nrf_delay_ms(200);
+
+	}
+	
+}
+  
+
+
+
+void Server_Answer_Call()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+	uint8_t j;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("Server_Answer_Call()");
+
+	SystemManager.System_State = SYSTEM_SERVER_COMM_REQ;
+
+	if( SystemManager.ServerCon == 0 )
+	{
+		SystemManager.LedBlinkRun = 1;
+		SystemManager.LedBlinkTimer = 5000;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+		SystemManager.DevType = 0;
+
+		SystemManager.SwitchOn = 1;
+
+  		PKBuzzerOn();
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_CALL_ANSWER;
+
+		if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+
+			strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+
+			tmpStr[6] = 0;
+			SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+
+			tmpStr[4] = 0;
+			SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+			
+			tmpStr[2] = 0;
+			SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		}else{						// 없으면 000000 전송
+			
+			SvrSendBuff[4] =  0;
+			SvrSendBuff[5] =  0;
+			SvrSendBuff[6] =  0;
+		}
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+		
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+
+		SvrSendBuff[11] = 0;
+		SvrSendBuff[12] = 0;
+		SvrSendBuff[13] = 0;
+		SvrSendBuff[14] = 0;
+		SvrSendBuff[15] = 0;
+		SvrSendBuff[16] = 0;
+		SvrSendBuff[17] = 0;
+		
+		for(j=1; j<18; j++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[j];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+		
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+	}
+}
+
+
+
+
+void Server_Answer_Version()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Version_Answer(22)\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_VER_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  IES600RB_VER_HIGH;
+		SvrSendBuff[12] =  IES600RB_VER_LOW;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+
+	}
+
+
+	nrf_delay_ms(1000);
+
+#if 0
+	for(i=0; i<5; i++){
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+#endif
+}
+
+
+void Server_Answer_Upgread()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Upgread()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_UPGREAD_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  IES600RB_VER_HIGH;
+		SvrSendBuff[12] =  IES600RB_VER_LOW;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+	}
+
+
+	NRF_LOG_RAW_INFO("================================================================================\n");
+	NRF_LOG_RAW_INFO("======================== Reboot To BootLoad Start ==============================\n");
+	NRF_LOG_RAW_INFO("================================================================================\n");	
+
+	nrf_delay_ms(1000);
+
+	for(i=0; i<5; i++){
+	
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+
+	nrf_delay_ms(3000);
+
+
+	nrf_power_gpregret_set(0xB1);
+	NVIC_SystemReset();
+	
+}
+
+
+
+
+// 사용않함
+void SendEmergencyLocal()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_COMM_EMG_SWTICH;
+
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;	
+	
+	SendToEventServer(&SvrSendBuff[0], 20);
+	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+
+}
+
+
+
+// 송신기 테스트 버튼눌렀을시 동작 
+void AliveTest()
+{
+	int cnt = 0;
+
+	int buz_cnt = 0;
+	int led_cnt = 0;
+	char blink_cnt = 0;
+	char blink_flag = 0;
+	
+	uint8_t ex = 1;
+
+	NRF_LOG_RAW_INFO("Void AliveTest()\n");
+
+#if 0
+
+	PKBuzzerOn();
+	PKLedOn();
+
+	blink_flag = 1;
+
+	while(ex){
+
+		if(SystemTimer.MS_100_TICK){
+
+			SystemTimer.MS_100_TICK = 0;
+
+			cnt++;
+			
+			if(cnt >= 5){
+
+				cnt = 0;
+
+				buz_cnt++;
+
+				if(buz_cnt >= 2){	// 10sec
+					PKBuzzerOff();
+				}
+
+				blink_flag = !blink_flag;
+			
+	 			if(blink_flag){
+					PKLedOn();
+				}else{
+					PKLedOff();
+
+					blink_cnt++;
+
+					if(blink_cnt >= 3)
+						ex = 0;
+				}
+			}
+		}
+	}
+
+//	SystemManager.LedBlinkRun = COM_TYPE_SVR_TEST;
+//	SystemManager.LedBlinkTimer = 3300;
+//	SystemTimer.LED_TOGGLE_TIMER = 0;
+#else
+
+  	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+	SystemManager.LedBlinkRun = COM_TYPE_SVR_TEST;
+	SystemManager.LedBlinkTimer = 3300;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+#endif
+	
+}
+
+
+
+
+
+
+void LedToggle()
+{
+
+	static char toggle = 0;
+
+	
+	// 송신기 등록모드시 항상 ON
+
+#if 1
+
+	switch(SystemManager.LedBlinkRun){
+		case COM_TYPE_SVR_RECV_REG_REQ:
+			PKLedOn();
+			return;
+		break;
+
+		case COM_TYPE_SVR_RECV_REG_ANSWER:
+
+			if( SystemManager.RegRequst == 1 )
+			{
+				if( SystemManager.LedBlinkTimer < 0 )
+				{
+					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_REQ;
+					PKLedOn(); 	
+					return;
+				}
+			}
+
+			if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+				return;
+
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+
+			if( toggle++ & 0x01)
+			{
+				PKLedOn();
+			}else{
+				PKLedOff();
+			}
+
+		break;
+
+		case COM_TYPE_SVR_TEST:
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				SystemManager.LedBlinkRun = 0;
+				PKLedOff(); 
+				PKBuzzerOff();
+			
+				return;
+			}
+			
+			
+			if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+				return;
+			
+			SystemTimer.LED_TOGGLE_TIMER = 0;
+			
+			if( toggle++&0x01)
+			{
+				PKLedOn();
+			}else{
+				PKLedOff();
+			}
+		break;
+
+
+		case COM_TYPE_BAND_PARKING:
+		case COM_TYPE_APP_PARKING:
+		case COM_TYPE_IOS_APP_PARKING:
+		case COM_TYPE_NEW_IOS_APP_PARKING:
+
+
+			if( SystemManager.LedBlinkTimer < 0 )
+			 {
+				 SystemManager.LedBlinkRun = 0;
+				 PKLedOff();	   
+				 return;
+			 }
+			
+			
+			 if( SystemTimer.LED_TOGGLE_TIMER < 300 )
+				 return;
+			
+			 SystemTimer.LED_TOGGLE_TIMER = 0;
+			
+			 if( ++toggle&0x01)
+			 {
+				 PKLedOn();
+			 }else{
+				 PKLedOff();
+			 }
+		break;
+	}			
+
+
+#else
+	
+	
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG_REQ )
+	{
+		PKLedOn();
+		return;
+	}
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG_ANSWER )
+	{
+
+		if( SystemManager.RegRequst == 1 )
+		{
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_REQ;
+				PKLedOn(); 	
+				return;
+			}
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+		if( toggle++ & 0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_TEST )
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff();	
+			PKBuzzerOff();
+
+			return;
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}	
+	
+#endif
+
+
+
+	if( SystemManager.SwitchOn == 0 )
+		return;
+
+	if( SystemManager.LedBlinkRun == 0 )
+		return;
+
+
+	if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+		return;
+
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+	if( toggle++&0x01)
+	{
+		PKLedOn();
+	}else{
+		PKLedOff();
+	}
+}
+
+

+ 1427 - 0
BLE_Central.si4project/Backup/our_service(4012).c

@@ -0,0 +1,1427 @@
+/**
+ * Copyright (c) 2014 - 2018, 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 <stdint.h>
+#include <string.h>
+#include "nrf_gpio.h"
+#include "our_service.h"
+#include "ble_srv_common.h"
+#include "app_error.h"
+#include "SEGGER_RTT.h"
+#include "board_gpi.h"
+#include "nrf_log.h"
+
+#include "sysmgr.h"
+#include "main.h"
+#include "nrf_power.h"
+
+
+char SvrRxBuffer[100];
+int SvrRxBufferPos;
+char SvrEvent;
+
+
+stSystemTimer SystemTimer;
+stSystemManager SystemManager;
+char SvrSendBuff[50];
+
+void delete_all_begin(void);
+
+
+
+void USART_DataCheck()
+{
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SystemManager.RxValild )
+	{
+
+		SvrRxBuffer[SvrRxBufferPos] = 0;
+
+		//printf("[%d]%s\r\n", SvrRxBufferPos, SvrRxBuffer);
+		SystemManager.RxValild = 0;
+
+		if( SvrRxBufferPos == 20 )
+		{
+			SystemManager.RxEvent = 1;
+		}
+
+		SvrRxBufferPos = 0;
+	}
+
+	if( SystemTimer.UART_LAST_RECV_TIMER > 10 && SvrRxBufferPos )
+	{
+		SystemManager.RxValild = 0;
+		SvrRxBufferPos = 0;
+	}
+
+}
+
+
+void USART_Handler(void)
+{
+
+	char ch;
+	
+	uint8_t cr;
+
+// 	SystemTimer.UART1_LAST_RECV_TIMER = 0;
+
+	if( app_uart_get(&cr) == NRF_SUCCESS )
+	{
+		SystemManager.RxValild = 1;
+		SvrRxBuffer[SvrRxBufferPos++] = cr;
+		SvrRxBufferPos %= 100;
+		SystemTimer.UART_LAST_RECV_TIMER = 0;
+	}
+}
+
+
+
+#define SERVER_COMM_DATA_LEN		0x08
+
+
+#define COM_TYPE_SVR_EMG_REQ			0x01		// SERVER EMG 응답
+#define COM_TYPE_SVR_NORMAL   			0x02		// 수신기 Normal 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_TALKING  			0x03		// 수신기 Talking 신호		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_DISCON   			0x04		// 수신기 DisConnect 신호	( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_BUSY     			0x05		// 수신기 Busy 신호			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_ALIVE    			0x06		// 수신기 Alive 신호			( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_MIC      			0x07		// 수신기 Mic 상태 			( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_REG_REQ		0x08		// 송신기 등록 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SEV_RECV_REG_ANSWER	0x09		// 송신기 등록 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_INIT_REQ		0x0a		// 수신기 초기화 요청 		( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_RECV_INIT_ANSWER	0x0b		// 수신기 초기화 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_RECV_LIST_REQ		0x0c		// 송신기 목록 요청		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_RECV_LIST_ANSWER	0x0d		// 송신기 목록 응답		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_VER_REQ			0x10		// 수신기 버전 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_VER_ANSWER			0x11		// 수신기 버전 응답 		( IES600 --> BleEventServer )
+#define COM_TYPE_SVR_CALL_REQ			0x12		// 수신기 통화 요청 		( BleEventServer --> IES600 )
+#define COM_TYPE_SVR_CALL_ANSWER		0x13		// 수신기 통화 응답 		( IES600 --> BleEventServer )
+
+#define COM_TYPE_SVR_UPGREAD_REQ		0x14		// 수신기 업그레이드 요청	( BleEventServer --> IES600 ) 
+#define COM_TYPE_SVR_UPGREAD_ANSWER		0x15		// 수신기 업그레이드 응답	( IES600 --> BleEventServer ) 
+
+
+
+
+
+/* 이벤트 서버에서 20byte 들어왔을때 */
+
+
+void ParseEventServer()
+{
+
+	int i;
+
+	if( SystemManager.RxEvent == 0 )
+		return;
+
+	SystemManager.RxEvent = 0;
+
+
+	NRF_LOG_RAW_INFO("\n\n");
+	NRF_LOG_RAW_INFO("SERVER TO DATA : ")
+	for( i=0; i<20; i++)
+	{
+		NRF_LOG_RAW_INFO("0x%02x ", SvrRxBuffer[i]);
+	}
+	NRF_LOG_RAW_INFO("\n\n");
+
+
+	if(SvrRxBuffer[0] != 0x02)
+		return;
+
+
+	switch(SvrRxBuffer[1]){
+
+		case COM_TYPE_SVR:
+
+			switch(SvrRxBuffer[3]){
+
+				// 수신기 대기상태 요청
+				case COM_TYPE_SVR_NORMAL:
+
+					NRF_LOG_INFO("Recv : Normal");
+
+					PKLedOff();
+					PKBuzzerOff();
+					PKMicOff();
+					SystemManager.SwitchOn = 0;
+ 
+				break;
+
+				// 수신기 통화상태 요청 
+				case COM_TYPE_SVR_TALKING:
+
+					NRF_LOG_INFO("Recv : Talking");
+
+					PKLedOn();
+					PKBuzzerOff();
+					SystemManager.SwitchOn = 0;
+				break;
+
+				// 수신기 서버와 통화 종료 요청
+				case COM_TYPE_SVR_DISCON:
+					
+					NRF_LOG_INFO("Recv : Disconnect");
+
+					SystemManager.SwitchOn = 0;
+					//bsp_board_leds_off();
+				break;
+
+				// 서버 Busy 상태 알림
+				case COM_TYPE_SVR_BUSY:
+
+					NRF_LOG_INFO("Recv : Busy");
+
+				break;
+
+				// 송신기 Alive신호 서버로 전송
+				case COM_TYPE_SVR_ALIVE:
+
+					NRF_LOG_INFO("Recv : Keep Alive");
+				break;
+
+				// 수신기 마이크 상태 변경 요청 
+				case COM_TYPE_SVR_MIC:
+					
+					NRF_LOG_INFO("Recv : mic on/off");
+
+					if( SvrRxBuffer[11] == 0 )
+					{  
+						NRF_LOG_INFO("mic on"); 
+						NRF_LOG_INFO("speaker off");  
+						PKSpeakerOff();
+						PKMicOn();
+						PKBuzzerOff();
+						PKLedOn();
+						SystemManager.SwitchOn = 0;
+					}else{
+						NRF_LOG_INFO("mic off"); 
+						NRF_LOG_INFO("speaker on");  
+						PKMicOff();
+						PKSpeakerOn();
+						PKLedOn();
+					}
+				break;
+
+				// 송신기 등록요청
+				case COM_TYPE_SVR_RECV_REG_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_REG");
+
+					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG;
+					SystemManager.RegRequst = 1;
+
+					SendAck(COM_TYPE_SVR_RECV_REG+1);
+
+					SystemTimer.DEV_REG_TIMER = 0;
+
+				break;
+
+				// 송신기 등록 초기화 요청
+				case COM_TYPE_SVR_RECV_INIT_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_INIT");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_INIT;
+//					SystemManager.LedBlinkTimer = 2500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+					
+					SendAck(COM_TYPE_SVR_RECV_INIT+1);
+
+					//for( i=0; i<RegMacPool.Count; i++)
+					//{
+					//RegMacDelteAll();
+					// }
+					memset( &RegMacPool, 0, sizeof(RegMacPool));
+
+					delete_all_begin();
+
+					for(i=0; i<2; i++){
+						PKLedOn();
+						nrf_delay_ms(300);
+						PKLedOff();
+						nrf_delay_ms(300);
+					}
+				break;
+
+				// 송신기에 등록된 수신기 리스트 요청 
+				case COM_TYPE_SVR_RECV_LIST_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_RECV_LIST");
+
+//					SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_LIST;
+//					SystemManager.LedBlinkTimer = 1500;
+//					SystemTimer.LED_TOGGLE_TIMER = 0;
+
+//					SystemManager.SwitchOn = 1;
+
+					Server_Answer_Reg_List();
+
+					PKLedOn();
+					nrf_delay_ms(300);
+					PKLedOff();
+
+				break;
+
+				// 서버로 부터 통화 요청
+				case COM_TYPE_SVR_CALL_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_CALL_REQ");
+
+					Server_Answer_Call();
+
+				break;
+
+				// 서버로 부터 수신기 버전 요청
+				case COM_TYPE_SVR_VER_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_VER_REQ");
+
+					Server_Answer_Version();
+
+				break;
+
+
+				case COM_TYPE_SVR_UPGREAD_REQ:
+
+					NRF_LOG_INFO("Recv : COM_TYPE_SVR_UPGREAD_REQ");
+					
+					Server_Answer_Upgread();
+
+				break;
+			}
+		break;
+
+		case COM_TYPE_BAND:
+
+		break;
+	}
+}
+
+
+
+void SendToEventServer(char* data, int len)
+{
+
+	int i;
+
+	NRF_LOG_RAW_INFO("SendToEventServer ==> ");
+	for( i=0; i<len; i++)
+	{
+		NRF_LOG_RAW_INFO("%02x ", data[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+
+
+	for( i=0; i<len; i++)
+	{
+		while (app_uart_put(data[i]) != NRF_SUCCESS);
+	}
+
+}
+
+
+
+
+
+void SendParkingApp()
+{
+	int i;
+
+	NRF_LOG_RAW_INFO("===> SendParkingApp()\n");
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  3;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  1;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	
+	SvrSendBuff[7] =  new_ble_addr.addr[3];		// 수신기 MAC 
+	SvrSendBuff[8] =  new_ble_addr.addr[4];		// 수신기 MAC
+	SvrSendBuff[9] =  new_ble_addr.addr[5];		// 수신기 MAC
+
+	SvrSendBuff[10] =  0x11;
+	SvrSendBuff[11] =  0x74;
+
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //SITE
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //DONG
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //HO
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	SvrSendBuff[28] =  COM_ETX;
+
+
+	NRF_LOG_INFO("SendParkingApp ===");
+	
+	SendToEventServer(&SvrSendBuff[0], 1);
+
+	SendToEventServer(&SvrSendBuff[0], 29);
+
+
+	for(i=0; i<2; i++){
+		PKLedOn();
+		nrf_delay_ms(300);
+		PKLedOff();
+		nrf_delay_ms(300);
+	}
+
+	nrf_delay_ms(2000);		// 중복해서 들어오는 데이타로 인한 연속 동작 방지 
+
+}
+
+
+
+
+
+void SendEmergencyBand()
+{
+	int i;
+
+	char tmpStr[10];
+
+	NRF_LOG_RAW_INFO("===> SendEmergencyBand()\n");
+
+	SystemManager.LedBlinkRun = 1;
+	SystemManager.LedBlinkTimer = 5000;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+	SystemManager.DevType = 0;
+	
+	SystemManager.SwitchOn = 1;
+
+	PKBuzzerOn();
+  
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  2;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+	
+		strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+	
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+	
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+	
+	}else{						// 없으면 000000 전송
+		
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+	}
+
+
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	SvrSendBuff[10] =  0x11;
+	SvrSendBuff[11] =  0x72;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	SvrSendBuff[28] =  COM_ETX;
+
+	NRF_LOG_INFO("SendEmergencyBand===");
+
+	SendToEventServer(&SvrSendBuff[0], 1);
+
+	nrf_delay_ms(500);
+	
+	SendToEventServer(&SvrSendBuff[0], 29);
+
+
+	//NRF_LOG_RAW_INFO("================= EmergencyBand \n");
+	for( i=0; i<29; i++)
+	{
+		//NRF_LOG_RAW_INFO("%02x ", SvrSendBuff[i]);
+	}
+	NRF_LOG_RAW_INFO("\n");
+	
+
+}
+
+
+
+
+
+
+void SendParkingBand()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> SendParkingBand()\n");
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  2;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  2;
+
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  0x11;
+	SvrSendBuff[11] =  0x73;
+
+	SvrSendBuff[12] =  0; //uuid
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+
+	SvrSendBuff[16] =  SystemManager.Site[0]; //Site
+	SvrSendBuff[17] =  SystemManager.Site[1];
+	SvrSendBuff[18] =  SystemManager.Site[2];
+	SvrSendBuff[19] =  SystemManager.Site[3];
+
+	SvrSendBuff[20] =  SystemManager.Dong[0]; //Dong
+	SvrSendBuff[21] =  SystemManager.Dong[1];
+
+	SvrSendBuff[22] =  SystemManager.Ho[0]; //Ho
+	SvrSendBuff[23] =  SystemManager.Ho[1];
+
+	SvrSendBuff[24] =  0; //KEY NUM
+	SvrSendBuff[25] =  0; //KEY TYPE
+
+	SvrSendBuff[26] =  0; //Random
+	SvrSendBuff[27] =  0;  
+
+	SvrSendBuff[28] =  COM_ETX;
+
+//	NRF_LOG_INFO("SendParkingBand ===");
+	SendToEventServer(&SvrSendBuff[0], 1);
+
+	SendToEventServer(&SvrSendBuff[0], 29);
+
+//	SystemManager.SwitchOn = 1;
+	SystemManager.SwitchOn = 0;
+
+
+	for(i=0; i<2; i++){
+		PKLedOn();
+		nrf_delay_ms(300);
+		PKLedOff();
+		nrf_delay_ms(300);
+	}
+
+}
+
+
+
+/******************************************************************************
+*
+*						 송신기 --------> Event Server
+*
+*******************************************************************************/
+
+void SendAck(uint8_t cmd)
+{
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> SendAck()\n");
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+
+	SvrSendBuff[3] =  cmd;
+
+	SvrSendBuff[4] =  0;
+	SvrSendBuff[5] =  0;
+	SvrSendBuff[6] =  0;
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+	
+	SvrSendBuff[11] =  'A';
+	SvrSendBuff[12] =  'C';
+	SvrSendBuff[13] =  'K';
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+void SendEmergency()
+{
+
+	NRF_LOG_RAW_INFO("===> SendEmergency()\n");
+
+	if( SystemManager.RegRequst == 1 )
+	{
+		SystemManager.RegRequst = 0;
+			return;
+	}
+  
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  SystemManager.BatLevel;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendEmergency ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	SystemManager.SwitchOn = 1;
+
+	PKBuzzerOn();
+
+}
+
+
+
+
+void SendAlive()
+{
+
+	NRF_LOG_RAW_INFO("===> SendAlive()\n");
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_SVR_ALIVE;
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;		// Data Length
+
+	SvrSendBuff[11] =  SystemManager.BatLevel;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendAlive ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+// 김효섭 차장 요청을 추가
+void SendTest()
+{
+
+	NRF_LOG_RAW_INFO("===> SendAlive()\n");
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+	SvrSendBuff[3] =  COM_TYPE_TEST;
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;		// Data Length
+
+	SvrSendBuff[11] =  SystemManager.BatLevel;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+	SvrSendBuff[19] =  COM_ETX;
+
+	NRF_LOG_INFO("SendAlive ===");
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+}
+
+
+
+// 송신기 등록시마다 송신기 데이타 전송 
+void SendCurrentRegDev()
+{
+
+	NRF_LOG_RAW_INFO("===> SendCurrentRegDev()\n");
+
+	uint8_t i;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+
+	SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+	SvrSendBuff[4] =  SystemManager.PeerAddr[3];
+	SvrSendBuff[5] =  SystemManager.PeerAddr[4];
+	SvrSendBuff[6] =  SystemManager.PeerAddr[5];
+	SvrSendBuff[7] =  new_ble_addr.addr[3];
+	SvrSendBuff[8] =  new_ble_addr.addr[4];
+	SvrSendBuff[9] =  new_ble_addr.addr[5];
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+
+	for(i=1; i<18; i++){
+		SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+	}
+
+	SvrSendBuff[19] =  COM_ETX;
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+
+	nrf_delay_ms(50);
+
+}
+
+
+
+
+// 비상벨 목록 응답.
+void Server_Answer_Reg_List()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Reg_List(%d)\n", RegMacPool.Count);
+
+#if 1
+	if( RegMacPool.Count == 0 )
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x ===== ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		nrf_delay_ms(50);
+	}	
+#endif	
+
+	for( i=0; i<RegMacPool.Count; i++)
+	{
+
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+	
+		strcpy( tmpStr, &RegMacPool.Mac[i][6]);
+		tmpStr[6] = 0;
+		SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+
+		tmpStr[4] = 0;
+		SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+
+		tmpStr[2] = 0;
+		SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+		
+		SvrSendBuff[3] =  COM_TYPE_SVR_RECV_LIST_ANSWER;
+
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		NRF_LOG_INFO("DevList %02x%02x%02x ===== ", SvrSendBuff[4], SvrSendBuff[5], SvrSendBuff[6]);
+		SendToEventServer(&SvrSendBuff[0], 20);
+		nrf_delay_ms(200);
+
+	}
+}
+  
+
+
+
+void Server_Answer_Call()
+{
+
+	char tmpStr[10];
+
+	uint8_t i;
+
+	memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+
+	NRF_LOG_INFO("Server_Answer_Call()");
+	
+	if( SystemManager.ServerCon == 0 )
+	{
+		SystemManager.LedBlinkRun = 1;
+		SystemManager.LedBlinkTimer = 5000;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+		SystemManager.DevType = 0;
+
+		SystemManager.SwitchOn = 1;
+
+  		PKBuzzerOn();
+	
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+
+		SvrSendBuff[3] =  COM_TYPE_SVR_CALL_ANSWER;
+
+		if( RegMacPool.Count != 0 ){  // 등록된 송신기가 있으면 첫번째 MAC 전송
+
+			strcpy( tmpStr, &RegMacPool.Mac[0][6]);
+
+			tmpStr[6] = 0;
+			SvrSendBuff[6] = strtoul( &tmpStr[4], NULL, 16 );
+
+			tmpStr[4] = 0;
+			SvrSendBuff[5] = strtoul( &tmpStr[2], NULL, 16 );
+			
+			tmpStr[2] = 0;
+			SvrSendBuff[4] = strtoul( &tmpStr[0], NULL, 16 );
+
+		}else{						// 없으면 000000 전송
+			
+			SvrSendBuff[4] =  0;
+			SvrSendBuff[5] =  0;
+			SvrSendBuff[6] =  0;
+		}
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+		
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+
+		SvrSendBuff[11] = 0;
+		SvrSendBuff[12] = 0;
+		SvrSendBuff[13] = 0;
+		SvrSendBuff[14] = 0;
+		SvrSendBuff[15] = 0;
+		SvrSendBuff[16] = 0;
+		SvrSendBuff[17] = 0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+		
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+	}
+}
+
+
+
+
+void Server_Answer_Version()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Version_Answer()\n");
+
+
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+
+		SvrSendBuff[3] =  COM_TYPE_SVR_VER_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  IES600RB_VER_HIGH;
+		SvrSendBuff[12] =  IES600RB_VER_LOW;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+
+	}
+
+
+	NRF_LOG_RAW_INFO("================================================================================\n");
+	NRF_LOG_RAW_INFO("======================== Reboot To BootLoad Start ==============================\n");
+	NRF_LOG_RAW_INFO("================================================================================\n");	
+
+	nrf_delay_ms(1000);
+
+	for(i=0; i<5; i++){
+	
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+
+	nrf_power_gpregret_set(0xB1);
+	NVIC_SystemReset();
+
+
+}
+
+
+void Server_Answer_Upgread()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+	NRF_LOG_RAW_INFO("===> Server_Answer_Upgread()\n");
+
+	if( SystemManager.ServerCon == 0)
+	{
+		memset(SvrSendBuff, 0x00, sizeof(SvrSendBuff));
+		
+		SystemManager.LedBlinkRun = COM_TYPE_SVR_VER_REQ;
+		SystemManager.LedBlinkTimer = 1500;
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		SystemManager.DevType = 0;
+
+		SvrSendBuff[0] =  COM_STX;
+		SvrSendBuff[1] =  COM_TYPE_SVR;
+		SvrSendBuff[2] =  0;
+
+		SvrSendBuff[3] =  COM_TYPE_SVR_UPGREAD_ANSWER;
+
+		SvrSendBuff[4] =  0;
+		SvrSendBuff[5] =  0;
+		SvrSendBuff[6] =  0;
+		SvrSendBuff[7] =  new_ble_addr.addr[3];
+		SvrSendBuff[8] =  new_ble_addr.addr[4];
+		SvrSendBuff[9] =  new_ble_addr.addr[5];
+
+		SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+		
+		SvrSendBuff[11] =  0;
+		SvrSendBuff[12] =  0;
+		SvrSendBuff[13] =  0;
+		SvrSendBuff[14] =  0;
+		SvrSendBuff[15] =  0;
+		SvrSendBuff[16] =  0;
+		SvrSendBuff[17] =  0;
+		
+		for(i=1; i<18; i++){
+			SvrSendBuff[18] = SvrSendBuff[18] + SvrSendBuff[i];
+		}
+
+		SvrSendBuff[19] =  COM_ETX;
+
+		SendToEventServer(&SvrSendBuff[0], 20);
+
+		SystemManager.SwitchOn = 0;
+	}
+
+
+	NRF_LOG_RAW_INFO("================================================================================\n");
+	NRF_LOG_RAW_INFO("======================== Reboot To BootLoad Start ==============================\n");
+	NRF_LOG_RAW_INFO("================================================================================\n");	
+
+	nrf_delay_ms(1000);
+
+	for(i=0; i<5; i++){
+	
+		PKLedOn();
+		nrf_delay_ms(100);
+		PKLedOff();
+		nrf_delay_ms(100);
+	}
+
+
+	nrf_power_gpregret_set(0xB1);
+	NVIC_SystemReset();
+
+	
+}
+
+
+
+
+// 사용않함
+void SendEmergencyLocal()
+{
+
+	uint8_t i;
+
+	uint8_t check_sum = 0;
+
+
+	SvrSendBuff[0] =  COM_STX;
+	SvrSendBuff[1] =  COM_TYPE_SVR;
+	SvrSendBuff[2] =  0;
+	
+	SvrSendBuff[3] =  COM_TYPE_BELL_EMG;
+
+	SvrSendBuff[4] =  0xaa;
+	SvrSendBuff[5] =  0xaa;
+	SvrSendBuff[6] =  0xaa;
+	SvrSendBuff[7] =  0xbb;
+	SvrSendBuff[8] =  0xbb;
+	SvrSendBuff[9] =  0xbb;
+	
+	SvrSendBuff[10] =  SERVER_COMM_DATA_LEN;
+
+	SvrSendBuff[11] =  0;
+	SvrSendBuff[12] =  0;
+	SvrSendBuff[13] =  0;
+	SvrSendBuff[14] =  0;
+	SvrSendBuff[15] =  0;
+	SvrSendBuff[16] =  0;
+	SvrSendBuff[17] =  0;
+	SvrSendBuff[18] =  0;
+
+	SvrSendBuff[19] =  COM_ETX;	
+	
+
+	SendToEventServer(&SvrSendBuff[0], 20);
+	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+
+}
+
+
+
+// 송신기 테스트 버튼눌렀을시 동작 
+void AliveTest()
+{
+
+  	SystemManager.SwitchOn = 1;
+	PKBuzzerOn();
+	SystemManager.LedBlinkRun = COM_TYPE_SVR_ALIVE;
+	SystemManager.LedBlinkTimer = 3300;
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+}
+
+
+
+
+
+// 사용않함
+void SendTest()
+{
+	if( SystemTimer.SEND_TEST_TIMER < 3000 )
+		return;
+
+	SystemTimer.SEND_TEST_TIMER = 0;
+
+	SendEmergency();
+  
+}
+
+
+
+void LedToggle()
+{
+
+	static char toggle = 0;
+
+	if( SystemManager.RegRequst )
+	{
+
+		if( SystemTimer.DEV_REG_TIMER >= 60000 )
+		{
+			SystemManager.RegRequst = 0;
+			PKLedOff();
+			SystemManager.LedBlinkRun = 0;
+		}
+	}
+  
+	// 송신기 등록모드시 항상 ON
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG )
+	{
+		PKLedOn();
+		return;
+	}
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_REG+1 )
+	{
+
+		if( SystemManager.RegRequst == 1 )
+		{
+			if( SystemManager.LedBlinkTimer < 0 )
+			{
+				SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG;
+				PKLedOn(); 	
+				return;
+			}
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+
+
+#if 0
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_PARKING )
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff(); 	
+			return;
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+#endif
+
+#if 0	
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_INIT )
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff();	  
+
+			return;
+		}
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+#endif
+
+
+#if 0
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_RECV_LIST || SystemManager.LedBlinkRun == COM_TYPE_SVR_VER_REQ)
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff();	  
+
+			return;
+		}
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}
+#endif
+
+
+
+
+	if( SystemManager.LedBlinkRun == COM_TYPE_SVR_ALIVE )
+	{
+		if( SystemManager.LedBlinkTimer < 0 )
+		{
+			SystemManager.LedBlinkRun = 0;
+			PKLedOff();	
+			PKBuzzerOff();
+
+			return;
+		}
+
+
+		if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+			return;
+
+		SystemTimer.LED_TOGGLE_TIMER = 0;
+
+		if( toggle++&0x01)
+		{
+			PKLedOn();
+		}else{
+			PKLedOff();
+		}
+	}	
+
+	if( SystemManager.SwitchOn == 0 )
+		return;
+
+	if( SystemManager.LedBlinkRun == 0 )
+		return;
+
+
+#if 0
+	if( SystemManager.LedBlinkTimer < 0 )
+	{
+
+		SystemManager.LedBlinkRun = 0;
+		PKLedOff();  	
+
+		return;
+	}
+#endif
+
+	if( SystemTimer.LED_TOGGLE_TIMER < 500 )
+		return;
+
+	SystemTimer.LED_TOGGLE_TIMER = 0;
+
+
+	if( toggle++&0x01)
+	{
+		PKLedOn();
+	}else{
+		PKLedOff();
+	}
+}
+
+

Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä