main(1470).c 44 KB

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