main(3414).c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724
  1. /**
  2. * Copyright (c) 2016 - 2020, Nordic Semiconductor ASA
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without modification,
  7. * are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form, except as embedded into a Nordic
  13. * Semiconductor ASA integrated circuit in a product or a software update for
  14. * such product, must reproduce the above copyright notice, this list of
  15. * conditions and the following disclaimer in the documentation and/or other
  16. * materials provided with the distribution.
  17. *
  18. * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
  19. * contributors may be used to endorse or promote products derived from this
  20. * software without specific prior written permission.
  21. *
  22. * 4. This software, with or without modification, must only be used with a
  23. * Nordic Semiconductor ASA integrated circuit.
  24. *
  25. * 5. Any software provided in binary form under this license must not be reverse
  26. * engineered, decompiled, modified and/or disassembled.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
  29. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31. * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
  32. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  34. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *
  39. */
  40. /*************************************************************************************
  41. 2022/01/26
  42. 업데이트 후 바뀐 버전정보 확인을 위해 부팅시 서버에 버전정보 전달
  43. 2022/03/09 (Release V1.0)
  44. 비상벨 프로토콜 확인
  45. 안드로이드 원패스 필터 수정
  46. 2022/03/24 (Release V1.1)
  47. 안드로이드 원패스 필터 수정
  48. New iOS 원패스 추가
  49. *************************************************************************************/
  50. #include <stdio.h>
  51. #include <stdint.h>
  52. #include <stdbool.h>
  53. #include "nordic_common.h"
  54. #include "app_error.h"
  55. #include "app_uart.h"
  56. #include "ble_db_discovery.h"
  57. #include "app_timer.h"
  58. #include "app_util.h"
  59. #include "bsp_btn_ble.h"
  60. #include "ble.h"
  61. #include "ble_gap.h"
  62. #include "ble_hci.h"
  63. #include "nrf_sdh.h"
  64. #include "nrf_sdh_ble.h"
  65. #include "nrf_sdh_soc.h"
  66. #include "ble_nus_c.h"
  67. #include "nrf_ble_gatt.h"
  68. #include "nrf_pwr_mgmt.h"
  69. #include "nrf_ble_scan.h"
  70. #include "peer_manager.h"
  71. #include "nrf_log.h"
  72. #include "nrf_log_ctrl.h"
  73. #include "nrf_log_default_backends.h"
  74. #include "our_service.h"
  75. #include "board_gpi.h"
  76. #include "nrf_spi.h"
  77. #include "nrf_drv_spi.h"
  78. #include "app_util_platform.h"
  79. #include "nrf_gpio.h"
  80. #include "nrf_delay.h"
  81. #include "boards.h"
  82. #include "app_error.h"
  83. #include <string.h>
  84. #include "main.h"
  85. #include "sysmgr.h"
  86. #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. */
  87. #define APP_BLE_OBSERVER_PRIO 3 /**< BLE observer priority of the application. There is no need to modify this value. */
  88. #define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */
  89. #define UART_RX_BUF_SIZE 256 /**< UART RX buffer size. */
  90. #define NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic UART Service (vendor specific). */
  91. #define ECHOBACK_BLE_UART_DATA 1 /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
  92. BLE_NUS_C_DEF(m_ble_nus_c); /**< BLE Nordic UART Service (NUS) client instance. */
  93. NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
  94. BLE_DB_DISCOVERY_DEF(m_db_disc); /**< Database discovery module instance. */
  95. NRF_BLE_SCAN_DEF(m_scan); /**< Scanning Module instance. */
  96. NRF_BLE_GQ_DEF(m_ble_gatt_queue, /**< BLE GATT Queue instance. */
  97. NRF_SDH_BLE_CENTRAL_LINK_COUNT,
  98. NRF_BLE_GQ_QUEUE_SIZE);
  99. #define SPI_INSTANCE 0 /**< SPI instance index. */
  100. //const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE); /**< SPI instance. */
  101. //const nrf_drv_spi_t spi = { 0, { .spi = spi0 }, false }; /**< SPI instance. */
  102. volatile bool spi_xfer_done; /**< Flag used to indicate that SPI instance completed the transfer. */
  103. APP_TIMER_DEF(m_our_char_timer_id);
  104. #define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms intervals
  105. 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. */
  106. static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID;
  107. unsigned int gTimeCounter = 0;
  108. /**@brief NUS UUID. */
  109. static ble_uuid_t const m_nus_uuid =
  110. {
  111. .uuid = BLE_UUID_NUS_SERVICE,
  112. .type = NUS_SERVICE_UUID_TYPE
  113. };
  114. //static char my_addr[6] = {0xE9, 0xB1, 0x8D, 0xA2, 0xED, 0x07}; C
  115. static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDB}; //P
  116. //static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCC}; //SAMPLE
  117. //static char my_addr[6] = {0x65, 0x7C, 0x2C, 0x69, 0xC1, 0xDD}; //P TEST Bad-Mac
  118. static char my_addr_1[6] = {0x26, 0xAA, 0xEE, 0x75, 0x90, 0xCd}; //SAMPLE bad-mac
  119. extern char ScanHSBuff[];
  120. extern uint8_t m_tx_buf[]; /**< TX buffer. */
  121. extern uint8_t m_rx_buf[]; /**< RX buffer. */
  122. extern uint8_t m_length; /**< Transfer length. */
  123. /* Flag to check fds initialization. */
  124. static bool volatile m_fds_initialized;
  125. /* Array to map FDS events to strings. */
  126. static char const * fds_evt_str[] =
  127. {
  128. "FDS_EVT_INIT",
  129. "FDS_EVT_WRITE",
  130. "FDS_EVT_UPDATE",
  131. "FDS_EVT_DEL_RECORD",
  132. "FDS_EVT_DEL_FILE",
  133. "FDS_EVT_GC",
  134. };
  135. /* Keep track of the progress of a delete_all operation. */
  136. static struct
  137. {
  138. bool delete_next; //!< Delete next record.
  139. bool pending; //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
  140. } m_delete_all;
  141. ble_gap_addr_t old_ble_addr;
  142. ble_gap_addr_t new_ble_addr;
  143. static void fds_evt_handler(fds_evt_t const * p_evt)
  144. {
  145. if (p_evt->result == NRF_SUCCESS)
  146. {
  147. NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
  148. fds_evt_str[p_evt->id]);
  149. }
  150. else
  151. {
  152. NRF_LOG_INFO("Event: %s received (%s)",
  153. fds_evt_str[p_evt->id],
  154. fds_err_str(p_evt->result));
  155. }
  156. switch (p_evt->id)
  157. {
  158. case FDS_EVT_INIT:
  159. if (p_evt->result == NRF_SUCCESS)
  160. {
  161. m_fds_initialized = true;
  162. }
  163. break;
  164. case FDS_EVT_WRITE:
  165. {
  166. if (p_evt->result == NRF_SUCCESS)
  167. {
  168. NRF_LOG_INFO("Record ID:\t0x%04x", p_evt->write.record_id);
  169. NRF_LOG_INFO("File ID:\t0x%04x", p_evt->write.file_id);
  170. NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
  171. }
  172. } break;
  173. case FDS_EVT_DEL_RECORD:
  174. {
  175. if (p_evt->result == NRF_SUCCESS)
  176. {
  177. NRF_LOG_INFO("Record ID:\t0x%04x", p_evt->del.record_id);
  178. NRF_LOG_INFO("File ID:\t0x%04x", p_evt->del.file_id);
  179. NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
  180. }
  181. m_delete_all.pending = false;
  182. } break;
  183. default:
  184. break;
  185. }
  186. }
  187. /**@brief Begin deleting all records, one by one. */
  188. void delete_all_begin(void)
  189. {
  190. m_delete_all.delete_next = true;
  191. }
  192. /**@brief Process a delete all command.
  193. *
  194. * Delete records, one by one, until no records are left.
  195. */
  196. void delete_all_process(void)
  197. {
  198. if (m_delete_all.delete_next & !m_delete_all.pending)
  199. {
  200. NRF_LOG_INFO("Deleting next record.");
  201. m_delete_all.delete_next = record_delete_next();
  202. if (!m_delete_all.delete_next)
  203. {
  204. NRF_LOG_INFO("No records left to delete.");
  205. }
  206. }
  207. }
  208. /**
  209. * @brief SPI user event handler.
  210. * @param event
  211. */
  212. void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
  213. void * p_context)
  214. {
  215. spi_xfer_done = true;
  216. NRF_LOG_INFO("Transfer completed.");
  217. if (m_rx_buf[0] != 0)
  218. {
  219. NRF_LOG_INFO(" Received:");
  220. NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char *)m_rx_buf));
  221. }
  222. }
  223. // 1ms tick (1ms interrupt)
  224. // ALREADY_DONE_FOR_YOU: This is a timer event handler
  225. static void timer_timeout_handler(void * p_context)
  226. {
  227. // Step 3.F, Update temperature and characteristic value.
  228. static int32_t sensor_value = 0;
  229. // sd_temp_get(&sensor_value); // *modify where sensor measurement function goes
  230. // our_sensor_characteristic_update(&m_our_service, &sensor_value); // make a call to characteristic update function
  231. // nrf_gpio_pin_toggle(LED_4);
  232. //printf("%d\r\n", sensor_value++);
  233. //SendData();
  234. gTimeCounter++;
  235. SystemTimer.MS_1++;
  236. SystemTimer.UART_LAST_RECV_TIMER++;
  237. SystemTimer.SEND_TEST_TIMER++;
  238. SystemTimer.LED_TOGGLE_TIMER++;
  239. SystemTimer.TMR_CON_START++;
  240. SystemTimer.PARK_KEEP_TIMER++;
  241. SystemTimer.DEV_REG_TIMER++;
  242. SystemTimer.SVR_SEND_TIMER++;
  243. SystemManager.LedBlinkTimer--;
  244. if(!(SystemTimer.MS_1 % 10)){
  245. SystemTimer.MS_10_TICK = 1;
  246. }
  247. if(!(SystemTimer.MS_1 % 100)){
  248. SystemTimer.MS_100_TICK = 1;
  249. }
  250. if(!(SystemTimer.MS_1 % 1000)){
  251. SystemTimer.MS_1000_TICK = 1;
  252. }
  253. if( SystemTimer.TMR_CON_START == 10000 )
  254. {
  255. sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION);
  256. }
  257. }
  258. /**@brief Function for starting timers.
  259. */
  260. static void application_timers_start(void)
  261. {
  262. /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
  263. ret_code_t err_code;
  264. err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
  265. APP_ERROR_CHECK(err_code); */
  266. app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
  267. }
  268. /**@brief Function for handling asserts in the SoftDevice.
  269. *
  270. * @details This function is called in case of an assert in the SoftDevice.
  271. *
  272. * @warning This handler is only an example and is not meant for the final product. You need to analyze
  273. * how your product is supposed to react in case of assert.
  274. * @warning On assert from the SoftDevice, the system can only recover on reset.
  275. *
  276. * @param[in] line_num Line number of the failing assert call.
  277. * @param[in] p_file_name File name of the failing assert call.
  278. */
  279. void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
  280. {
  281. app_error_handler(0xDEADBEEF, line_num, p_file_name);
  282. }
  283. /**@brief Function for handling the Nordic UART Service Client errors.
  284. *
  285. * @param[in] nrf_error Error code containing information about what went wrong.
  286. */
  287. static void nus_error_handler(uint32_t nrf_error)
  288. {
  289. APP_ERROR_HANDLER(nrf_error);
  290. }
  291. /**@brief Function to start scanning. */
  292. static void scan_start(void)
  293. {
  294. ret_code_t ret;
  295. ret = nrf_ble_scan_start(&m_scan);
  296. APP_ERROR_CHECK(ret);
  297. ret = bsp_indication_set(BSP_INDICATE_SCANNING);
  298. APP_ERROR_CHECK(ret);
  299. }
  300. /**@brief Function for handling Scanning Module events.
  301. */
  302. static void scan_evt_handler(scan_evt_t const * p_scan_evt)
  303. {
  304. ret_code_t err_code;
  305. switch(p_scan_evt->scan_evt_id)
  306. {
  307. case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
  308. {
  309. err_code = p_scan_evt->params.connecting_err.err_code;
  310. APP_ERROR_CHECK(err_code);
  311. } break;
  312. case NRF_BLE_SCAN_EVT_CONNECTED:
  313. {
  314. ble_gap_evt_connected_t const * p_connected =
  315. p_scan_evt->params.connected.p_connected;
  316. // Scan is automatically stopped by the connection.
  317. NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
  318. p_connected->peer_addr.addr[0],
  319. p_connected->peer_addr.addr[1],
  320. p_connected->peer_addr.addr[2],
  321. p_connected->peer_addr.addr[3],
  322. p_connected->peer_addr.addr[4],
  323. p_connected->peer_addr.addr[5]
  324. );
  325. } break;
  326. case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
  327. {
  328. NRF_LOG_INFO("Scan timed out.");
  329. scan_start();
  330. } break;
  331. default:
  332. break;
  333. }
  334. }
  335. /**@brief Function for initializing the scanning and setting the filters.
  336. */
  337. static void scan_init(void)
  338. {
  339. ret_code_t err_code;
  340. nrf_ble_scan_init_t init_scan;
  341. memset(&init_scan, 0, sizeof(init_scan));
  342. init_scan.connect_if_match = true;
  343. init_scan.conn_cfg_tag = APP_BLE_CONN_CFG_TAG;
  344. err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
  345. APP_ERROR_CHECK(err_code);
  346. #if 0
  347. err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr);
  348. APP_ERROR_CHECK(err_code);
  349. err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, my_addr_1);
  350. APP_ERROR_CHECK(err_code);
  351. err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
  352. APP_ERROR_CHECK(err_code);
  353. #endif
  354. #if 1
  355. err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
  356. APP_ERROR_CHECK(err_code);
  357. err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
  358. APP_ERROR_CHECK(err_code);
  359. #endif
  360. }
  361. /**@brief Function for handling database discovery events.
  362. *
  363. * @details This function is a callback function to handle events from the database discovery module.
  364. * Depending on the UUIDs that are discovered, this function forwards the events
  365. * to their respective services.
  366. *
  367. * @param[in] p_event Pointer to the database discovery event.
  368. */
  369. static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
  370. {
  371. ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
  372. }
  373. /**@brief Function for handling characters received by the Nordic UART Service (NUS).
  374. *
  375. * @details This function takes a list of characters of length data_len and prints the characters out on UART.
  376. * If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
  377. */
  378. static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
  379. {
  380. ret_code_t ret_val;
  381. NRF_LOG_DEBUG("Receiving data.");
  382. NRF_LOG_INFO("Receiving data.");
  383. NRF_LOG_RAW_INFO("Receiving data.");
  384. NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
  385. for (uint32_t i = 0; i < data_len; i++)
  386. {
  387. do
  388. {
  389. ret_val = app_uart_put(p_data[i]);
  390. if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
  391. {
  392. NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
  393. APP_ERROR_CHECK(ret_val);
  394. }
  395. } while (ret_val == NRF_ERROR_BUSY);
  396. }
  397. if (p_data[data_len-1] == '\r')
  398. {
  399. while (app_uart_put('\n') == NRF_ERROR_BUSY);
  400. }
  401. if (ECHOBACK_BLE_UART_DATA)
  402. {
  403. // Send data back to the peripheral.
  404. do
  405. {
  406. ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
  407. if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
  408. {
  409. NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
  410. APP_ERROR_CHECK(ret_val);
  411. }
  412. } while (ret_val == NRF_ERROR_BUSY);
  413. }
  414. }
  415. void uart_event_handle(app_uart_evt_t * p_event)
  416. {
  417. static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
  418. static uint16_t index = 0;
  419. uint32_t ret_val;
  420. switch (p_event->evt_type)
  421. {
  422. /**@snippet [Handling data from UART] */
  423. case APP_UART_DATA_READY:
  424. // SystemTimer.UART1_LAST_RECV_TIMER = 0;
  425. USART_Handler();
  426. break;
  427. case APP_UART_DATA:
  428. NRF_LOG_INFO("APP_UART_DATA");
  429. break;
  430. /**@snippet [Handling data from UART] */
  431. case APP_UART_COMMUNICATION_ERROR:
  432. NRF_LOG_ERROR("Communication error occurred while handling UART.");
  433. APP_ERROR_HANDLER(p_event->data.error_communication);
  434. break;
  435. case APP_UART_FIFO_ERROR:
  436. NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
  437. APP_ERROR_HANDLER(p_event->data.error_code);
  438. break;
  439. default:
  440. break;
  441. }
  442. }
  443. /**@brief Callback handling Nordic UART Service (NUS) client events.
  444. *
  445. * @details This function is called to notify the application of NUS client events.
  446. *
  447. * @param[in] p_ble_nus_c NUS client handle. This identifies the NUS client.
  448. * @param[in] p_ble_nus_evt Pointer to the NUS client event.
  449. */
  450. /**@snippet [Handling events from the ble_nus_c module] */
  451. //char tmpData11[] = {0x60, 0x2C, 0x4E, 0x2D, 0x74, 0xB3, 0xAB, 0xF8, 0xE5, 0x28, 0xB4, 0x41, 0x3D, 0x52, 0x66, 0xC4};
  452. 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)
  453. {
  454. ret_code_t err_code;
  455. int i;
  456. switch (p_ble_nus_evt->evt_type)
  457. {
  458. case BLE_NUS_C_EVT_DISCOVERY_COMPLETE: // Connecting
  459. SystemManager.SecondData = 0;
  460. NRF_LOG_INFO("Discovery complete.");
  461. err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
  462. APP_ERROR_CHECK(err_code);
  463. err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
  464. APP_ERROR_CHECK(err_code);
  465. NRF_LOG_INFO("Connected to device with Nordic UART Service.");
  466. switch(SystemManager.Encryption_Mode){
  467. case AES_ENC_WES:
  468. CarEncryptEcb( AES_ENC_WES );
  469. ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
  470. break;
  471. case AES_ENC_CAR:
  472. CarEncryptEcb( AES_ENC_CAR );
  473. ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
  474. break;
  475. case AES_ENC_EMG:
  476. CarEncryptEcb( AES_ENC_EMG );
  477. ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
  478. break;
  479. case AES_ENC_PCA:
  480. CarEncryptEcb( AES_ENC_PCA );
  481. ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16); // PCAXX 전송
  482. break;
  483. }
  484. break;
  485. case BLE_NUS_C_EVT_NUS_TX_EVT: // BLE NUS Data Rx
  486. //ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
  487. //printf("Connected to device with Nordic UART Service. Len:%d\r\n", p_ble_nus_evt->data_len);
  488. #if 0
  489. for( i=0; i<p_ble_nus_evt->data_len; i++)
  490. {
  491. //NRF_LOG_RAW_INFO("%02x-", p_ble_nus_evt->p_data[i]);
  492. }
  493. #endif
  494. NRF_LOG_RAW_INFO("Type %x\n", p_ble_nus_evt->p_data[0]);
  495. if(SystemManager.SecondData == 0){
  496. switch(p_ble_nus_evt->p_data[0]){
  497. case 0x74: // 무선 비상벨 신호
  498. memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
  499. CarDecryptEcb( &SystemManager.TmpBuff[1], &SystemManager.AesEncData[0] );
  500. NRF_LOG_RAW_INFO("WES");
  501. for( i=0; i<16; i++)
  502. {
  503. NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
  504. }
  505. memcpy( &(p_ble_nus_evt->p_data[1]), &SystemManager.AesEncData[0], 16 );
  506. switch(p_ble_nus_evt->p_data[12]){
  507. // 비상벨 버튼 동작시
  508. case DEV_NUS_EMG:
  509. NRF_LOG_INFO("TRANSFER SWITCH --- Emergency");
  510. SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
  511. SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
  512. SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
  513. switch(SystemManager.System_State){
  514. case SYSTEM_EMERGENCY_SIREN:
  515. case SYSTEM_SERVER_COMM:
  516. case SYSTEM_SERVER_COMM_REQ:
  517. break;
  518. case SYSTEM_REGISTER: // 등록 모드일 경우
  519. if( FindRegMac(ScanHSBuff) == 1 )
  520. {
  521. SystemManager.RegRequst = 0;
  522. SystemManager.LedBlinkRun = 0;
  523. SystemManager.System_State = SYSTEM_NONE;
  524. ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
  525. NRF_LOG_INFO("Device Registration Disable");
  526. SystemManager.SwitchOn = 0;
  527. PKBuzzerOff();
  528. PKLedOff();
  529. err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  530. APP_ERROR_CHECK(err_code);
  531. }
  532. break;
  533. case SYSTEM_NONE:
  534. SystemManager.LedBlinkRun = 1;
  535. SystemManager.LedBlinkTimer = 5000;
  536. SystemTimer.LED_TOGGLE_TIMER = 0;
  537. SystemManager.DevType = 0;
  538. SendEmergency();
  539. err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  540. APP_ERROR_CHECK(err_code);
  541. break;
  542. }
  543. SystemManager.DevType = 0;
  544. break;
  545. // 테스트 버튼 동작시
  546. case DEV_NUS_TEST:
  547. NRF_LOG_INFO("TRANSFER SWITCH --- TEST");
  548. SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
  549. SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
  550. SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
  551. switch(SystemManager.System_State){
  552. case SYSTEM_EMERGENCY_SIREN:
  553. case SYSTEM_SERVER_COMM:
  554. case SYSTEM_SERVER_COMM_REQ:
  555. break;
  556. case SYSTEM_REGISTER:
  557. if( FindRegMac(ScanHSBuff) == 1 )
  558. {
  559. SystemManager.RegRequst = 0;
  560. SystemManager.LedBlinkRun = 0;
  561. SystemManager.System_State = SYSTEM_NONE;
  562. ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
  563. NRF_LOG_INFO("Device Registration Disable");
  564. SystemManager.SwitchOn = 0;
  565. PKBuzzerOff();
  566. PKLedOff();
  567. }
  568. err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  569. APP_ERROR_CHECK(err_code);
  570. break;
  571. case SYSTEM_NONE:
  572. AliveTest();
  573. err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  574. APP_ERROR_CHECK(err_code);
  575. break;
  576. }
  577. SystemManager.DevType = 0;
  578. break;
  579. // 등록버튼 동작시
  580. case DEV_NUS_REG:
  581. NRF_LOG_INFO("TRANSFER SWITCH --- Device Registration");
  582. SystemTimer.DEV_REG_TIMER = 0;
  583. SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
  584. SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
  585. SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
  586. if(SystemManager.RegRequst) // 현재 등록모드일 경우
  587. {
  588. SystemManager.LedBlinkRun = COM_TYPE_SVR_RECV_REG_ANSWER;
  589. SystemManager.LedBlinkTimer = 2000;
  590. SystemTimer.LED_TOGGLE_TIMER = 0;
  591. for( i=0; i<6; i++)
  592. {
  593. NRF_LOG_INFO("0x%02x", SystemManager.PeerAddr[i]);
  594. }
  595. NRF_LOG_RAW_INFO("Reg Mac=>%s\n", SystemManager.PtrPeerAddrStr);
  596. NRF_LOG_RAW_INFO("\n");
  597. SaveRegMac(SystemManager.PtrPeerAddrStr);
  598. ble_nus_c_string_send(&m_ble_nus_c, "WESACK", 6);
  599. NRF_LOG_INFO("Send WESACK");
  600. SendCurrentRegDev();
  601. }else{
  602. ;
  603. }
  604. SystemManager.DevType = 0;
  605. break;
  606. // Alive 동작시
  607. case DEV_NUS_ALIVE:
  608. NRF_LOG_INFO("TRANSFER SWITCH --- Alive");
  609. SystemManager.BatLevel = p_ble_nus_evt->p_data[13];
  610. SystemManager.TransferVerHigh = p_ble_nus_evt->p_data[14];
  611. SystemManager.TransferVerLow = p_ble_nus_evt->p_data[15];
  612. SendAlive();
  613. err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  614. APP_ERROR_CHECK(err_code);
  615. SystemManager.DevType = 0;
  616. break;
  617. }
  618. break;
  619. case 0x73: // 밴드 주차
  620. NRF_LOG_RAW_INFO("Band Parking %d\n", p_ble_nus_evt->data_len);
  621. SystemManager.SecondData = 1;
  622. SystemManager.BandType = 0x73;
  623. memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
  624. CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
  625. NRF_LOG_RAW_INFO("Nus First Data ==>");
  626. for( i=0; i<16; i++)
  627. {
  628. NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
  629. }
  630. NRF_LOG_RAW_INFO("\n");
  631. SystemManager.Site[0] = SystemManager.AesEncData[4];
  632. SystemManager.Site[1] = SystemManager.AesEncData[5];
  633. SystemManager.Site[2] = SystemManager.AesEncData[6];
  634. SystemManager.Site[3] = SystemManager.AesEncData[7];
  635. SystemManager.Dong[0] = SystemManager.AesEncData[8];
  636. SystemManager.Dong[1] = SystemManager.AesEncData[9];
  637. SystemManager.Ho[0] = SystemManager.AesEncData[10];
  638. SystemManager.Ho[1] = SystemManager.AesEncData[11];
  639. SystemManager.Key_Num = SystemManager.AesEncData[12];
  640. SystemManager.Key_Type = SystemManager.AesEncData[13];
  641. SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
  642. SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
  643. break;
  644. case 0x72: // 밴드 비상
  645. NRF_LOG_RAW_INFO("Band Alarm %d\n", p_ble_nus_evt->data_len);
  646. SystemManager.SecondData = 1;
  647. SystemManager.BandType = 0x72;
  648. memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
  649. CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
  650. NRF_LOG_RAW_INFO("Nus First Data ==>");
  651. for( i=0; i<16; i++)
  652. {
  653. NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
  654. }
  655. NRF_LOG_RAW_INFO("\n");
  656. SystemManager.Site[0] = SystemManager.AesEncData[4];
  657. SystemManager.Site[1] = SystemManager.AesEncData[5];
  658. SystemManager.Site[2] = SystemManager.AesEncData[6];
  659. SystemManager.Site[3] = SystemManager.AesEncData[7];
  660. SystemManager.Dong[0] = SystemManager.AesEncData[8];
  661. SystemManager.Dong[1] = SystemManager.AesEncData[9];
  662. SystemManager.Ho[0] = SystemManager.AesEncData[10];
  663. SystemManager.Ho[1] = SystemManager.AesEncData[11];
  664. SystemManager.Key_Num = SystemManager.AesEncData[12];
  665. SystemManager.Key_Type = SystemManager.AesEncData[13];
  666. SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
  667. SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
  668. break;
  669. case 0x75: // 신규 원패스앱
  670. NRF_LOG_RAW_INFO("One Pass App %d\n", p_ble_nus_evt->data_len);
  671. SystemManager.SecondData = 1;
  672. SystemManager.BandType = 0x75;
  673. memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
  674. CarDecryptEcb( &SystemManager.TmpBuff[1], SystemManager.AesEncData );
  675. NRF_LOG_RAW_INFO("Nus First Data ==>");
  676. for( i=0; i<16; i++)
  677. {
  678. NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
  679. }
  680. NRF_LOG_RAW_INFO("\n");
  681. SystemManager.Site[0] = SystemManager.AesEncData[4];
  682. SystemManager.Site[1] = SystemManager.AesEncData[5];
  683. SystemManager.Site[2] = SystemManager.AesEncData[6];
  684. SystemManager.Site[3] = SystemManager.AesEncData[7];
  685. SystemManager.Dong[0] = SystemManager.AesEncData[8];
  686. SystemManager.Dong[1] = SystemManager.AesEncData[9];
  687. SystemManager.Ho[0] = SystemManager.AesEncData[10];
  688. SystemManager.Ho[1] = SystemManager.AesEncData[11];
  689. SystemManager.Key_Num = SystemManager.AesEncData[12];
  690. SystemManager.Key_Type = SystemManager.AesEncData[13];
  691. SystemManager.Random_Out[0] = SystemManager.AesEncData[14];
  692. SystemManager.Random_Out[1] = SystemManager.AesEncData[15];
  693. break;
  694. }
  695. }else if( SystemManager.SecondData == 1 ){ // 두번째 Nus Packet
  696. SystemManager.SecondData = 0;
  697. // for( i=0; i<p_ble_nus_evt->data_len; i++)
  698. // {
  699. // NRF_LOG_RAW_INFO("%02x ", p_ble_nus_evt->p_data[i]);
  700. // }
  701. memcpy( SystemManager.TmpBuff, p_ble_nus_evt->p_data, p_ble_nus_evt->data_len );
  702. #if 0
  703. NRF_LOG_RAW_INFO("======== SystemManager.TmpBuff\n");
  704. for( i=0; i<p_ble_nus_evt->data_len; i++)
  705. {
  706. NRF_LOG_RAW_INFO("%02x ",SystemManager.TmpBuff[i]);
  707. }
  708. NRF_LOG_RAW_INFO("\n");
  709. #endif
  710. CarDecryptEcb( &SystemManager.TmpBuff[0], SystemManager.AesEncData );
  711. NRF_LOG_RAW_INFO("Nus Secound Data ===>");
  712. for( i=0; i<16; i++)
  713. {
  714. NRF_LOG_RAW_INFO("%02x ", SystemManager.AesEncData[i]);
  715. }
  716. NRF_LOG_RAW_INFO("\n");
  717. switch(SystemManager.BandType){
  718. case 0x73: // BAND PARKING
  719. if( SystemManager.ServerCon == 0)
  720. {
  721. CarEncryptEcbACK(SystemManager.BandType);
  722. ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
  723. SystemManager.Encryption_Mode = AES_ENC_NONE;
  724. SendParkingBand();
  725. // jakuja disconnect
  726. err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  727. APP_ERROR_CHECK(err_code);
  728. }
  729. break;
  730. case 0x72: // BAND EMG
  731. if( SystemManager.ServerCon == 0)
  732. {
  733. CarEncryptEcbACK(SystemManager.BandType);
  734. ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
  735. switch(SystemManager.System_State){
  736. case SYSTEM_NONE:
  737. SendEmergencyBand();
  738. break;
  739. case SYSTEM_REGISTER:
  740. case SYSTEM_EMERGENCY_SIREN:
  741. case SYSTEM_SERVER_COMM:
  742. case SYSTEM_SERVER_COMM_REQ:
  743. break;
  744. }
  745. err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  746. APP_ERROR_CHECK(err_code);
  747. SystemManager.Encryption_Mode = AES_ENC_NONE;
  748. }
  749. break;
  750. case 0x75: // New iOS App
  751. if( SystemManager.ServerCon == 0)
  752. {
  753. PcaEncryptEcbACK(SystemManager.BandType);
  754. ble_nus_c_string_send(&m_ble_nus_c, SystemManager.AesEncData, 16);
  755. SystemManager.DevType = 0;
  756. SendParkingApp();
  757. err_code = sd_ble_gap_disconnect(p_ble_nus_c->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  758. APP_ERROR_CHECK(err_code);
  759. NRF_LOG_RAW_INFO("======== Send CARACK\n");
  760. }
  761. break;
  762. }
  763. }
  764. break;
  765. case BLE_NUS_C_EVT_DISCONNECTED:
  766. NRF_LOG_INFO("Disconnected --------------------\n");
  767. scan_start();
  768. break;
  769. }
  770. }
  771. /**@snippet [Handling events from the ble_nus_c module] */
  772. /**
  773. * @brief Function for handling shutdown events.
  774. *
  775. * @param[in] event Shutdown type.
  776. */
  777. static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
  778. {
  779. ret_code_t err_code;
  780. err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  781. APP_ERROR_CHECK(err_code);
  782. switch (event)
  783. {
  784. case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
  785. // Prepare wakeup buttons.
  786. err_code = bsp_btn_ble_sleep_mode_prepare();
  787. APP_ERROR_CHECK(err_code);
  788. break;
  789. default:
  790. break;
  791. }
  792. return true;
  793. }
  794. NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
  795. /**@brief Function for handling BLE events.
  796. *
  797. * @param[in] p_ble_evt Bluetooth stack event.
  798. * @param[in] p_context Unused.
  799. */
  800. static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
  801. {
  802. int i;
  803. ret_code_t err_code;
  804. ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
  805. switch (p_ble_evt->header.evt_id)
  806. {
  807. case BLE_GAP_EVT_ADV_REPORT :
  808. //NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT : %d", &p_gap_evt->params.adv_report.data.len);
  809. //NRF_LOG_INFO(&p_gap_evt->params.adv_report);
  810. break;
  811. case BLE_GAP_EVT_SCAN_REQ_REPORT:
  812. NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
  813. break;
  814. case BLE_GAP_EVT_CONNECTED:
  815. NRF_LOG_INFO("BLE_GAP_EVT_CONNECTED");
  816. err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
  817. APP_ERROR_CHECK(err_code);
  818. err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
  819. APP_ERROR_CHECK(err_code);
  820. // start discovery of services. The NUS Client waits for a discovery result
  821. err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
  822. APP_ERROR_CHECK(err_code);
  823. break;
  824. case BLE_GAP_EVT_DISCONNECTED:
  825. NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
  826. p_gap_evt->conn_handle,
  827. p_gap_evt->params.disconnected.reason);
  828. #if 0
  829. if( SystemManager.DevType == DEV_IOS_PARK && p_gap_evt->params.disconnected.reason != 0x16 )
  830. {
  831. NVIC_SystemReset();
  832. //nrf_delay_ms(100);
  833. //UNUSED_RETURN_VALUE(sd_ble_gap_scan_start(NULL, &p_scan_ctx->scan_buffer));
  834. }
  835. #endif
  836. break;
  837. case BLE_GAP_EVT_TIMEOUT:
  838. if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
  839. {
  840. NRF_LOG_INFO("Connection Request timed out.");
  841. }
  842. break;
  843. case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
  844. // Pairing not supported.
  845. 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);
  846. APP_ERROR_CHECK(err_code);
  847. break;
  848. case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
  849. // Accepting parameters requested by peer.
  850. err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
  851. &p_gap_evt->params.conn_param_update_request.conn_params);
  852. APP_ERROR_CHECK(err_code);
  853. break;
  854. case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
  855. {
  856. NRF_LOG_DEBUG("PHY update request.");
  857. ble_gap_phys_t const phys =
  858. {
  859. .rx_phys = BLE_GAP_PHY_AUTO,
  860. .tx_phys = BLE_GAP_PHY_AUTO,
  861. };
  862. err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
  863. APP_ERROR_CHECK(err_code);
  864. } break;
  865. case BLE_GATTC_EVT_TIMEOUT:
  866. // Disconnect on GATT Client timeout event.
  867. NRF_LOG_DEBUG("GATT Client Timeout.");
  868. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
  869. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  870. APP_ERROR_CHECK(err_code);
  871. break;
  872. case BLE_GATTS_EVT_TIMEOUT:
  873. // Disconnect on GATT Server timeout event.
  874. NRF_LOG_DEBUG("GATT Server Timeout.");
  875. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
  876. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  877. APP_ERROR_CHECK(err_code);
  878. break;
  879. default:
  880. break;
  881. }
  882. }
  883. /**@brief Function for initializing the BLE stack.
  884. *
  885. * @details Initializes the SoftDevice and the BLE event interrupt.
  886. */
  887. static void ble_stack_init(void)
  888. {
  889. ret_code_t err_code;
  890. err_code = nrf_sdh_enable_request();
  891. APP_ERROR_CHECK(err_code);
  892. // Configure the BLE stack using the default settings.
  893. // Fetch the start address of the application RAM.
  894. uint32_t ram_start = 0;
  895. err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
  896. APP_ERROR_CHECK(err_code);
  897. // Enable BLE stack.
  898. err_code = nrf_sdh_ble_enable(&ram_start);
  899. APP_ERROR_CHECK(err_code);
  900. // Register a handler for BLE events.
  901. NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
  902. }
  903. /**@brief Function for handling events from the GATT library. */
  904. void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
  905. {
  906. if (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
  907. {
  908. NRF_LOG_INFO("ATT MTU exchange completed.");
  909. m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
  910. //m_ble_nus_max_data_len = 244;
  911. 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);
  912. }
  913. }
  914. /**@brief Function for initializing the GATT library. */
  915. void gatt_init(void)
  916. {
  917. ret_code_t err_code;
  918. err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
  919. APP_ERROR_CHECK(err_code);
  920. err_code = nrf_ble_gatt_att_mtu_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
  921. APP_ERROR_CHECK(err_code);
  922. }
  923. /**@brief Function for handling events from the BSP module.
  924. *
  925. * @param[in] event Event generated by button press.
  926. */
  927. void bsp_event_handler(bsp_event_t event)
  928. {
  929. ret_code_t err_code;
  930. switch (event)
  931. {
  932. case BSP_EVENT_SLEEP:
  933. nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
  934. break;
  935. case BSP_EVENT_DISCONNECT:
  936. err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
  937. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  938. if (err_code != NRF_ERROR_INVALID_STATE)
  939. {
  940. APP_ERROR_CHECK(err_code);
  941. }
  942. break;
  943. default:
  944. break;
  945. }
  946. }
  947. /**@brief Function for initializing the UART. */
  948. static void uart_init(void)
  949. {
  950. ret_code_t err_code;
  951. app_uart_comm_params_t const comm_params =
  952. {
  953. .rx_pin_no = RX_PIN_NUMBER,
  954. .tx_pin_no = TX_PIN_NUMBER,
  955. .rts_pin_no = RTS_PIN_NUMBER,
  956. .cts_pin_no = CTS_PIN_NUMBER,
  957. .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
  958. .use_parity = false,
  959. .baud_rate = UART_BAUDRATE_BAUDRATE_Baud9600
  960. };
  961. APP_UART_FIFO_INIT(&comm_params,
  962. UART_RX_BUF_SIZE,
  963. UART_TX_BUF_SIZE,
  964. uart_event_handle,
  965. APP_IRQ_PRIORITY_LOWEST,
  966. err_code);
  967. APP_ERROR_CHECK(err_code);
  968. }
  969. /**@brief Function for initializing the Nordic UART Service (NUS) client. */
  970. static void nus_c_init(void)
  971. {
  972. ret_code_t err_code;
  973. ble_nus_c_init_t init;
  974. init.evt_handler = ble_nus_c_evt_handler;
  975. init.error_handler = nus_error_handler;
  976. init.p_gatt_queue = &m_ble_gatt_queue;
  977. err_code = ble_nus_c_init(&m_ble_nus_c, &init);
  978. APP_ERROR_CHECK(err_code);
  979. }
  980. /**@brief Function for initializing buttons and leds. */
  981. static void buttons_leds_init(void)
  982. {
  983. ret_code_t err_code;
  984. bsp_event_t startup_event;
  985. err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
  986. APP_ERROR_CHECK(err_code);
  987. err_code = bsp_btn_ble_init(NULL, &startup_event);
  988. APP_ERROR_CHECK(err_code);
  989. }
  990. /**@brief Function for initializing the timer. */
  991. static void timer_init(void)
  992. {
  993. ret_code_t err_code = app_timer_init();
  994. APP_ERROR_CHECK(err_code);
  995. app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
  996. }
  997. /**@brief Function for initializing the nrf log module. */
  998. static void log_init(void)
  999. {
  1000. ret_code_t err_code = NRF_LOG_INIT(NULL);
  1001. APP_ERROR_CHECK(err_code);
  1002. NRF_LOG_DEFAULT_BACKENDS_INIT();
  1003. }
  1004. /**@brief Function for initializing power management.
  1005. */
  1006. static void power_management_init(void)
  1007. {
  1008. ret_code_t err_code;
  1009. err_code = nrf_pwr_mgmt_init();
  1010. APP_ERROR_CHECK(err_code);
  1011. }
  1012. /** @brief Function for initializing the database discovery module. */
  1013. static void db_discovery_init(void)
  1014. {
  1015. ble_db_discovery_init_t db_init;
  1016. memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
  1017. db_init.evt_handler = db_disc_handler;
  1018. db_init.p_gatt_queue = &m_ble_gatt_queue;
  1019. ret_code_t err_code = ble_db_discovery_init(&db_init);
  1020. APP_ERROR_CHECK(err_code);
  1021. }
  1022. /**@brief Function for handling the idle state (main loop).
  1023. *
  1024. * @details Handles any pending log operations, then sleeps until the next event occurs.
  1025. */
  1026. static void idle_state_handle(void)
  1027. {
  1028. if (NRF_LOG_PROCESS() == false)
  1029. {
  1030. nrf_pwr_mgmt_run();
  1031. }
  1032. }
  1033. /**@brief Function for handling events from the button handler module.
  1034. *
  1035. * @param[in] pin_no The pin that the event applies to.
  1036. * @param[in] button_action The button action (press/release).
  1037. */
  1038. static void button_event_handler(uint8_t pin_no, uint8_t button_action)
  1039. {
  1040. ret_code_t err_code;
  1041. uint32_t gpSts;
  1042. switch (pin_no)
  1043. {
  1044. case LEDBUTTON_BUTTON:
  1045. NRF_LOG_INFO("Send button data");
  1046. gpSts = nrf_gpio_pin_read(BSP_BUTTON_0);
  1047. NRF_LOG_INFO("gpSts=%d\r\n", gpSts);
  1048. if(gpSts == 0) // BTN_PRESSED=0
  1049. {
  1050. nrf_gpio_pin_clear(LED_1);
  1051. NRF_LOG_INFO("PRESSED\r\n");
  1052. SystemManager.SwitchOn = 1;
  1053. SendEmergencyLocal();
  1054. }else{
  1055. nrf_gpio_pin_set(LED_1);
  1056. NRF_LOG_INFO("Released\r\n");
  1057. }
  1058. break;
  1059. default:
  1060. APP_ERROR_HANDLER(pin_no);
  1061. break;
  1062. }
  1063. }
  1064. /**@brief Function for initializing the button handler module.
  1065. */
  1066. static void buttons_init(void)
  1067. {
  1068. ret_code_t err_code;
  1069. //The array must be static because a pointer to it will be saved in the button handler module.
  1070. static app_button_cfg_t buttons[] =
  1071. {
  1072. {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
  1073. };
  1074. err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
  1075. BUTTON_DETECTION_DELAY);
  1076. APP_ERROR_CHECK(err_code);
  1077. }
  1078. static void GPOut_Init()
  1079. {
  1080. uint32_t i;
  1081. for (i = 0; i < 4; ++i)
  1082. {
  1083. nrf_gpio_cfg_output(m_board_led_list[i]);
  1084. }
  1085. }
  1086. void ble_get_mac(uint8_t addr[8])
  1087. {
  1088. uint32_t err_code;
  1089. ble_gap_addr_t ble_addr;
  1090. err_code = sd_ble_gap_address_get(&ble_addr);
  1091. APP_ERROR_CHECK(err_code);
  1092. IPV6_EUI64_CREATE_FROM_EUI48(addr, ble_addr.addr, ble_addr.addr_type);
  1093. }
  1094. void _1000ms_timer_handle()
  1095. {
  1096. // NRF_LOG_RAW_INFO("_1000ms_timer_handle()\n");
  1097. switch(SystemManager.System_State){
  1098. case SYSTEM_NONE:
  1099. SystemTimer.SYSTEM_REGISTER_CNT = 0;
  1100. SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
  1101. SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
  1102. SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
  1103. break;
  1104. case SYSTEM_EMERGENCY_SIREN:
  1105. SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT++;
  1106. NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_EMERGENCY_SIREN) -- [%d / %d]\n", SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT, 60*10);
  1107. if(SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT >= 60*10){
  1108. SystemTimer.SYSTEM_EMERGENCY_SIREN_CNT = 0;
  1109. SystemManager.System_State = SYSTEM_NONE;
  1110. PKLedOff();
  1111. PKBuzzerOff();
  1112. SystemManager.LedBlinkRun = 0;
  1113. SystemManager.Emg_Ack_Flag = 0;
  1114. }
  1115. if(SystemManager.Emg_Ack_Flag){
  1116. SystemManager.Emg_Resend_Cnt++;
  1117. if(SystemManager.Emg_Resend_Cnt >= 10){
  1118. SystemManager.Emg_Resend_Cnt = 0;
  1119. ReSendEmergency();
  1120. }
  1121. }
  1122. break;
  1123. case SYSTEM_SERVER_COMM:
  1124. SystemTimer.SYSTEM_SERVER_COMM_CNT++;
  1125. NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_CNT, 60*3+30);
  1126. if(SystemTimer.SYSTEM_SERVER_COMM_CNT >= 60*3+30){
  1127. SystemTimer.SYSTEM_SERVER_COMM_CNT = 0;
  1128. SystemManager.System_State = SYSTEM_NONE;
  1129. PKLedOff();
  1130. PKMicOff();
  1131. PKSpeakerOff();
  1132. SystemManager.LedBlinkRun = 0;
  1133. }
  1134. break;
  1135. case SYSTEM_REGISTER:
  1136. SystemTimer.SYSTEM_REGISTER_CNT++;
  1137. NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_REGISTER) -- [%d / %d]\n", SystemTimer.SYSTEM_REGISTER_CNT, 60*1);
  1138. if(SystemTimer.SYSTEM_REGISTER_CNT >= 60*1){
  1139. SystemTimer.SYSTEM_REGISTER_CNT = 0;
  1140. SystemManager.RegRequst = 0;
  1141. SystemManager.System_State = SYSTEM_NONE;
  1142. PKLedOff();
  1143. SystemManager.LedBlinkRun = 0;
  1144. }
  1145. break;
  1146. case SYSTEM_SERVER_COMM_REQ:
  1147. SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT++;
  1148. NRF_LOG_RAW_INFO("_1000ms_timer_handle(SYSTEM_SERVER_COMM_REQ) -- [%d / %d]\n", SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT, 60*1);
  1149. if(SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT >= 60*1){
  1150. SystemTimer.SYSTEM_SERVER_COMM_REQ_CNT = 0;
  1151. SystemManager.RegRequst = 0;
  1152. SystemManager.System_State = SYSTEM_NONE;
  1153. PKLedOff();
  1154. PKBuzzerOff();
  1155. SystemManager.LedBlinkRun = 0;
  1156. }
  1157. break;
  1158. }
  1159. }
  1160. int main(void)
  1161. {
  1162. uint8_t i;
  1163. ret_code_t err_code;
  1164. ble_gap_addr_t dd;
  1165. dd.addr_id_peer = 0;
  1166. dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
  1167. // Initialize.
  1168. log_init();
  1169. /* Register first to receive an event when initialization is complete. */
  1170. (void) fds_register(fds_evt_handler);
  1171. NRF_LOG_RAW_INFO("\n===========================================================\n\n");
  1172. NRF_LOG_RAW_INFO("IES-600RB CENTRAL Program Start -- Ver 1.10 2022/03/20\n");
  1173. NRF_LOG_RAW_INFO("\n===========================================================\n\n");
  1174. // NRF_LOG_RAW_INFO("Initializing fds...\n");
  1175. err_code = fds_init();
  1176. APP_ERROR_CHECK(err_code);
  1177. timer_init();
  1178. uart_init();
  1179. buttons_init();
  1180. GPOut_Init();
  1181. db_discovery_init();
  1182. power_management_init();
  1183. //sd_ble_gap_addr_get(&old_ble_addr);
  1184. ble_stack_init();
  1185. sd_ble_gap_addr_get(&old_ble_addr);
  1186. dd.addr[0] = IES200_1ST_MAC;
  1187. dd.addr[1] = IES200_2ST_MAC;
  1188. dd.addr[2] = IES200_3ST_MAC;
  1189. dd.addr[3] = old_ble_addr.addr[3];
  1190. dd.addr[4] = old_ble_addr.addr[4];
  1191. dd.addr[5] = old_ble_addr.addr[5];
  1192. sd_ble_gap_addr_set(&dd);
  1193. sd_ble_gap_addr_get(&new_ble_addr);
  1194. gatt_init();
  1195. nus_c_init();
  1196. scan_init();
  1197. for(i=0; i<3; i++){
  1198. PKLedOn();
  1199. nrf_delay_ms(100);
  1200. PKLedOff();
  1201. nrf_delay_ms(100);
  1202. }
  1203. // Start execution.
  1204. //printf("BLE UART central example started.=====\r\n");
  1205. NRF_LOG_INFO("BLE UART central example started.");
  1206. scan_start();
  1207. application_timers_start();
  1208. // Enabling the buttons.
  1209. err_code = app_button_enable();
  1210. APP_ERROR_CHECK(err_code);
  1211. PKLedOff();
  1212. //FlashTest();
  1213. LoadRegMac();
  1214. //delete_all_begin();
  1215. Server_Answer_Version();
  1216. nrf_delay_ms(1000);
  1217. Server_Answer_Version();
  1218. while(1)
  1219. {
  1220. idle_state_handle();
  1221. USART_DataCheck();
  1222. ParseEventServer();
  1223. LedToggle();
  1224. delete_all_process();
  1225. if(SystemTimer.MS_1000_TICK){
  1226. SystemTimer.MS_1000_TICK = 0;
  1227. _1000ms_timer_handle();
  1228. }
  1229. }
  1230. }