main(5194).c 44 KB

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