main(7818).c 39 KB

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