main(7114).c 45 KB

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