main(437).c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160
  1. /**
  2. * Copyright (c) 2014 - 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. /** @file
  41. *
  42. * @defgroup ble_sdk_uart_over_ble_main main.c
  43. * @{
  44. * @ingroup ble_sdk_app_nus_eval
  45. * @brief UART over BLE application main file.
  46. *
  47. * This file contains the source code for a sample application that uses the Nordic UART service.
  48. * This application uses the @ref srvlib_conn_params module.
  49. */
  50. /******************************************************************************************************************
  51. *
  52. * V2022/01/25
  53. * @ Battery
  54. * @
  55. *
  56. *
  57. * V2022/02/10
  58. * @ AES
  59. *
  60. *
  61. *
  62. *
  63. *
  64. *
  65. *
  66. *
  67. *
  68. *
  69. *
  70. *
  71. *
  72. *
  73. *
  74. *
  75. *
  76. *
  77. *
  78. *
  79. *******************************************************************************************************************/
  80. #include <stdint.h>
  81. #include <string.h>
  82. #include "nordic_common.h"
  83. #include "nrf.h"
  84. #include "ble_hci.h"
  85. #include "ble_advdata.h"
  86. #include "ble_advertising.h"
  87. #include "ble_conn_params.h"
  88. #include "nrf_sdh.h"
  89. #include "nrf_sdh_soc.h"
  90. #include "nrf_sdh_ble.h"
  91. #include "nrf_ble_gatt.h"
  92. #include "nrf_ble_qwr.h"
  93. #include "app_pwm.h"
  94. #include "app_timer.h"
  95. #include "ble_nus.h"
  96. #include "app_uart.h"
  97. #include "app_util_platform.h"
  98. #include "bsp_btn_ble.h"
  99. #include "nrf_pwr_mgmt.h"
  100. #include "nrf_delay.h"
  101. #if defined (UART_PRESENT)
  102. #include "nrf_uart.h"
  103. #endif
  104. #if defined (UARTE_PRESENT)
  105. #include "nrf_uarte.h"
  106. #endif
  107. #include "nrf_log.h"
  108. #include "nrf_log_ctrl.h"
  109. #include "nrf_log_default_backends.h"
  110. #include "nrf_drv_saadc.h"
  111. #include "nrf_drv_rtc.h"
  112. #include "nrf_drv_wdt.h"
  113. #include "main.h"
  114. #include "sysmgr.h"
  115. #include "dio.h"
  116. #include "nrf_power.h"
  117. #include "fds.h"
  118. #include "nrf_fstorage.h"
  119. #define APP_BLE_CONN_CFG_TAG 1 /**< A tag identifying the SoftDevice BLE configuration. */
  120. //#define DEVICE_NAME "Nordic_UART" /**< Name of device. Will be included in the advertising data. */
  121. #define NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic UART Service (vendor specific). */
  122. #define APP_BLE_OBSERVER_PRIO 3 /**< Application's BLE observer priority. You shouldn't need to modify this value. */
  123. #define APP_ADV_INTERVAL 64 /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
  124. //#define APP_ADV_DURATION 18000 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
  125. #define APP_ADV_DURATION 300 /**< The advertising duration (3 seconds) in units of 10 milliseconds. */
  126. #define APP_TIMER_PRESCALER 0
  127. #define MIN_CONN_INTERVAL MSEC_TO_UNITS(20, UNIT_1_25_MS) /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
  128. #define MAX_CONN_INTERVAL MSEC_TO_UNITS(75, UNIT_1_25_MS) /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
  129. #define SLAVE_LATENCY 0 /**< Slave latency. */
  130. #define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) /**< Connection supervisory timeout (4 seconds), Supervision Timeout uses 10 ms units. */
  131. #define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
  132. #define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(30000) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
  133. #define MAX_CONN_PARAMS_UPDATE_COUNT 3 /**< Number of attempts before giving up the connection parameter negotiation. */
  134. #define DEAD_BEEF 0xDEADBEEF /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
  135. #define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */
  136. #define UART_RX_BUF_SIZE 256 /**< UART RX buffer size. */
  137. #define COMPARE_COUNTERTIME (3UL) /**< Get Compare event COMPARE_TIME seconds after the counter starts from 0. */
  138. #define TICK_EVENT_OUTPUT BSP_LED_0 /**< Pin number for indicating tick event. */
  139. #define COMPARE_EVENT_OUTPUT BSP_LED_1
  140. #define TIMER_MS_INTERVAL APP_TIMER_TICKS(25) // 25ms interrupt
  141. #define OUR_CHAR_TIMER_INTERVAL APP_TIMER_TICKS(1) // 1 ms interrupt
  142. BLE_NUS_DEF(m_nus, NRF_SDH_BLE_TOTAL_LINK_COUNT); /**< BLE NUS service instance. */
  143. NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
  144. NRF_BLE_QWR_DEF(m_qwr); /**< Context for the Queued Write module.*/
  145. BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
  146. APP_TIMER_DEF(m_ms_timer_id);
  147. APP_TIMER_DEF(wakeup_timer_id);
  148. APP_TIMER_DEF(m_our_char_timer_id);
  149. nrf_drv_wdt_channel_id m_channel_id;
  150. void WdtRunMode();
  151. #define KEEPALIVE_INTERVAL_30_SEC 30*1000
  152. #define KEEPALIVE_INTERVAL_1_MIN 60*1000
  153. #define KEEPALIVE_INTERVAL_30_MIN 30*60*1000
  154. #define KEEPALIVE_INTERVAL_1_HOUR 60*60*1000
  155. #define KEEPALIVE_INTERVAL_1_DAY 24*60*6*1000
  156. #define WAKEUP_TIME_INVERVAL APP_TIMER_TICKS(KEEPALIVE_INTERVAL_1_HOUR)
  157. //#define WAKEUP_TIME_INVERVAL APP_TIMER_TICKS(KEEPALIVE_INTERVAL_30_SEC)
  158. char DEVICE_NAME[] = {'I', 'C', 'S', 'W', 'E', 'S', 0x44,0x33,0xC0,0xFF,0xFF,0xFF };
  159. /* Flag to check fds initialization. */
  160. static bool volatile m_fds_initialized;
  161. /* Array to map FDS events to strings. */
  162. static char const * fds_evt_str[] =
  163. {
  164. "FDS_EVT_INIT",
  165. "FDS_EVT_WRITE",
  166. "FDS_EVT_UPDATE",
  167. "FDS_EVT_DEL_RECORD",
  168. "FDS_EVT_DEL_FILE",
  169. "FDS_EVT_GC",
  170. };
  171. /* Keep track of the progress of a delete_all operation. */
  172. static struct
  173. {
  174. bool delete_next; //!< Delete next record.
  175. bool pending; //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
  176. } m_delete_all;
  177. static void uart_init(void);
  178. static void advertising_init(void);
  179. static void buttons_leds_init(bool * p_erase_bonds);
  180. static void log_init(void);
  181. static void power_management_init(void);
  182. void wakeup_timer_handler(void * p_context);
  183. static void leds_config(void);
  184. void Battery_Adc_Read(void);
  185. static void idle_state_handle(void);
  186. //static void advertising_start(void);
  187. static void timer_ms_timeout_handler(void * p_context);
  188. static void on_adv_evt(ble_adv_evt_t ble_adv_evt);
  189. uint8_t advertising_flag = 0;
  190. static void fds_evt_handler(fds_evt_t const * p_evt)
  191. {
  192. if (p_evt->result == NRF_SUCCESS)
  193. {
  194. NRF_LOG_INFO("Event: %s received (NRF_SUCCESS)",
  195. fds_evt_str[p_evt->id]);
  196. }
  197. else
  198. {
  199. NRF_LOG_INFO("Event: %s received (%s)",
  200. fds_evt_str[p_evt->id],
  201. fds_err_str(p_evt->result));
  202. }
  203. switch (p_evt->id)
  204. {
  205. case FDS_EVT_INIT:
  206. if (p_evt->result == NRF_SUCCESS)
  207. {
  208. m_fds_initialized = true;
  209. }
  210. break;
  211. case FDS_EVT_WRITE:
  212. {
  213. if (p_evt->result == NRF_SUCCESS)
  214. {
  215. NRF_LOG_INFO("Record ID:\t0x%04x", p_evt->write.record_id);
  216. NRF_LOG_INFO("File ID:\t0x%04x", p_evt->write.file_id);
  217. NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
  218. }
  219. } break;
  220. case FDS_EVT_DEL_RECORD:
  221. {
  222. if (p_evt->result == NRF_SUCCESS)
  223. {
  224. NRF_LOG_INFO("Record ID:\t0x%04x", p_evt->del.record_id);
  225. NRF_LOG_INFO("File ID:\t0x%04x", p_evt->del.file_id);
  226. NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
  227. }
  228. m_delete_all.pending = false;
  229. } break;
  230. default:
  231. break;
  232. }
  233. }
  234. void ReMac_Mapping();
  235. ble_gap_addr_t old_ble_addr;
  236. ble_gap_addr_t new_ble_addr;
  237. int SysStatus;
  238. int SysCounter;
  239. static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
  240. static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - 3; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
  241. static ble_uuid_t m_adv_uuids[] = /**< Universally unique service identifier. */
  242. {
  243. {BLE_UUID_NUS_SERVICE, NUS_SERVICE_UUID_TYPE}
  244. };
  245. APP_PWM_INSTANCE(PWM1,1); // Create the instance "PWM1" using TIMER1.
  246. static volatile bool ready_flag; // A flag indicating PWM status.
  247. #define SAMPLES_IN_BUFFER 5
  248. static nrf_saadc_value_t m_buffer_pool[SAMPLES_IN_BUFFER];
  249. int SysCounter;
  250. ble_advertising_t* p_m_advertising;
  251. void SendEmgData(void);
  252. void SendTestData(void);
  253. void SendRegData(void);
  254. void SendAliveData(void);
  255. void bsp_event_handler(bsp_event_t event);
  256. void saadc_callback(nrf_drv_saadc_evt_t const * p_event)
  257. {
  258. if (p_event->type == NRF_DRV_SAADC_EVT_DONE)
  259. {
  260. nrf_drv_saadc_buffer_convert(p_event->data.done.p_buffer, SAMPLES_IN_BUFFER);
  261. }
  262. for(uint8_t i = 1 ; i < SAMPLES_IN_BUFFER ; i++)
  263. {
  264. NRF_LOG_INFO("ADC:%04d\r\n",p_event->data.done.p_buffer[i]);
  265. }
  266. }
  267. void SaadcInit(void)
  268. {
  269. nrf_saadc_channel_config_t channel_config =
  270. NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN2);
  271. nrf_drv_saadc_init(NULL, saadc_callback);
  272. nrf_drv_saadc_channel_init(2, &channel_config);
  273. }
  274. void wdt_event_handler(void)
  275. {
  276. //bsp_board_leds_off();
  277. NRF_LOG_INFO("<< wdt_event_handler() >>");
  278. }
  279. void BootLoad_Reboot()
  280. {
  281. WdtRunMode();
  282. nrf_drv_wdt_channel_feed(m_channel_id);
  283. nrf_power_gpregret_set(0xB1);
  284. NVIC_SystemReset();
  285. }
  286. // ALREADY_DONE_FOR_YOU: This is a timer event handler
  287. // 1m sec Interrupt
  288. static void timer_timeout_handler(void * p_context)
  289. {
  290. uint32_t err_code;
  291. SystemTimer.MS_1++;
  292. SystemTimer.UART_LAST_RECV_TIMER++;
  293. SystemTimer.SEND_TIMER++;
  294. SystemTimer.BUZZER_TIMER--;
  295. SystemManager.BleConnectTime++;
  296. SystemTimer.TIM_KEY++;
  297. SystemTimer.SLEEP_TIMER++;
  298. // 500ms SystemManager.BleSendStatus
  299. if(SystemManager.BleConnected){
  300. if( SystemManager.BleSendStatus && (SystemTimer.SEND_TIMER%500 ==0))
  301. {
  302. NRF_LOG_INFO("SystemManager.BleConnected:%d\n", SystemManager.BleConnected);
  303. if( SystemManager.EmgSendButton == BUTTON_EMG ) // EMG
  304. {
  305. SendEmgData();
  306. SystemTimer.EMG_SEND_RUN = 0;
  307. }else if( SystemManager.EmgSendButton == BUTTON_TEST ) // TEST
  308. {
  309. SendTestData();
  310. SystemTimer.EMG_SEND_RUN = 0;
  311. //SystemManager.EmgSendButton = BUTTON_NONE;
  312. }else if( SystemManager.EmgSendButton == BUTTON_ALIVE ) // Alive
  313. {
  314. SendAliveData();
  315. SystemTimer.EMG_SEND_RUN = 0;
  316. //SystemManager.EmgSendButton = BUTTON_NONE;
  317. }else if( SystemManager.EmgSendButton == BUTTON_REG ) //
  318. {
  319. SendRegData();
  320. SystemTimer.EMG_SEND_RUN = 0;
  321. //SystemManager.EmgSendButton = 11;
  322. //ParkPowerOff();
  323. }
  324. }
  325. }else{
  326. //NRF_LOG_INFO("SystemManager.BleConnected:%d\n", SystemManager.BleConnected);
  327. // BLE ADVERTISE RECONNECT START
  328. }
  329. if( SystemTimer.SEND_TIMER > 3000 )
  330. {
  331. NVIC_SystemReset(); // SYSTEM RESET
  332. }
  333. switch(SystemManager.BuzzerType){
  334. case BUZZER_EMG: // EMG
  335. if(SystemManager.Batt > BATTERY_LOW_LEVEL){
  336. if( SystemTimer.BUZZER_TIMER == 150 )
  337. {
  338. app_pwm_channel_duty_set(&PWM1, 0, 0);
  339. }else if( SystemTimer.BUZZER_TIMER == 100 )
  340. {
  341. app_pwm_channel_duty_set(&PWM1, 0, 50);
  342. }else if( SystemTimer.BUZZER_TIMER < 50 )
  343. {
  344. app_pwm_channel_duty_set(&PWM1, 0, 0);
  345. SystemManager.BuzzerType = BUZZER_NONE;
  346. app_pwm_disable(&PWM1);
  347. }
  348. }else{
  349. if( SystemTimer.BUZZER_TIMER == 500 )
  350. {
  351. app_pwm_channel_duty_set(&PWM1, 0, 0);
  352. }else if( SystemTimer.BUZZER_TIMER == 450 )
  353. {
  354. app_pwm_channel_duty_set(&PWM1, 0, 50);
  355. }else if( SystemTimer.BUZZER_TIMER == 350 )
  356. {
  357. app_pwm_channel_duty_set(&PWM1, 0, 0);
  358. }else if( SystemTimer.BUZZER_TIMER == 300 )
  359. {
  360. app_pwm_channel_duty_set(&PWM1, 0, 50);
  361. }else if( SystemTimer.BUZZER_TIMER == 200 )
  362. {
  363. app_pwm_channel_duty_set(&PWM1, 0, 0);
  364. }else if( SystemTimer.BUZZER_TIMER == 150 )
  365. {
  366. app_pwm_channel_duty_set(&PWM1, 0, 50);
  367. }else if( SystemTimer.BUZZER_TIMER < 100 )
  368. {
  369. app_pwm_channel_duty_set(&PWM1, 0, 0);
  370. SystemManager.BuzzerType = BUZZER_NONE;
  371. app_pwm_disable(&PWM1);
  372. }
  373. }
  374. break;
  375. case BUZZER_TEST: //TEST
  376. if(SystemManager.Batt > BATTERY_LOW_LEVEL){
  377. if( SystemTimer.BUZZER_TIMER < 10 )
  378. {
  379. app_pwm_channel_duty_set(&PWM1, 0, 0);
  380. SystemManager.BuzzerType = BUZZER_NONE;
  381. app_pwm_disable(&PWM1);
  382. }
  383. }else{ // LOW BATTERY (20% Under)
  384. if( SystemTimer.BUZZER_TIMER == 500 )
  385. {
  386. app_pwm_channel_duty_set(&PWM1, 0, 0);
  387. }else if( SystemTimer.BUZZER_TIMER == 450 )
  388. {
  389. app_pwm_channel_duty_set(&PWM1, 0, 50);
  390. }else if( SystemTimer.BUZZER_TIMER == 350 )
  391. {
  392. app_pwm_channel_duty_set(&PWM1, 0, 0);
  393. }else if( SystemTimer.BUZZER_TIMER == 300 )
  394. {
  395. app_pwm_channel_duty_set(&PWM1, 0, 50);
  396. }else if( SystemTimer.BUZZER_TIMER == 200 )
  397. {
  398. app_pwm_channel_duty_set(&PWM1, 0, 0);
  399. }else if( SystemTimer.BUZZER_TIMER == 150 )
  400. {
  401. app_pwm_channel_duty_set(&PWM1, 0, 50);
  402. }else if( SystemTimer.BUZZER_TIMER < 100 )
  403. {
  404. app_pwm_channel_duty_set(&PWM1, 0, 0);
  405. SystemManager.BuzzerType = BUZZER_NONE;
  406. app_pwm_disable(&PWM1);
  407. }
  408. }
  409. break;
  410. case BUZZER_REG: //
  411. if( SystemTimer.BUZZER_TIMER < 100 )
  412. {
  413. app_pwm_channel_duty_set(&PWM1, 0, 0);
  414. }else if( SystemTimer.BUZZER_TIMER == 100 )
  415. {
  416. // app_pwm_channel_duty_set(&PWM1, 0, 50);
  417. }else if( SystemTimer.BUZZER_TIMER < 50 )
  418. {
  419. app_pwm_channel_duty_set(&PWM1, 0, 0);
  420. SystemManager.BuzzerType = BUZZER_NONE;
  421. app_pwm_disable(&PWM1);
  422. }
  423. break;
  424. case BUZZER_BOOT_LOADER: //BOOT LOAD REBOOT
  425. if( SystemTimer.BUZZER_TIMER == 800 )
  426. {
  427. app_pwm_channel_duty_set(&PWM1, 0, 0);
  428. }else if( SystemTimer.BUZZER_TIMER == 700 )
  429. {
  430. app_pwm_channel_duty_set(&PWM1, 0, 50);
  431. }else if( SystemTimer.BUZZER_TIMER == 500 )
  432. {
  433. app_pwm_channel_duty_set(&PWM1, 0, 0);
  434. }else if( SystemTimer.BUZZER_TIMER == 400 )
  435. {
  436. app_pwm_channel_duty_set(&PWM1, 0, 50);
  437. }else if( SystemTimer.BUZZER_TIMER == 200 )
  438. {
  439. app_pwm_channel_duty_set(&PWM1, 0, 0);
  440. }else if( SystemTimer.BUZZER_TIMER == 100 )
  441. {
  442. app_pwm_channel_duty_set(&PWM1, 0, 50);
  443. }else if( SystemTimer.BUZZER_TIMER < 100 )
  444. {
  445. app_pwm_channel_duty_set(&PWM1, 0, 0);
  446. SystemManager.BuzzerType = BUZZER_NONE;
  447. app_pwm_disable(&PWM1);
  448. BootLoad_Reboot();
  449. }
  450. break;
  451. case BUZZER_POWER_ON: //
  452. if( SystemTimer.BUZZER_TIMER == 250 )
  453. {
  454. app_pwm_channel_duty_set(&PWM1, 0, 0);
  455. }else if( SystemTimer.BUZZER_TIMER == 200 )
  456. {
  457. app_pwm_channel_duty_set(&PWM1, 0, 50);
  458. }
  459. else if( SystemTimer.BUZZER_TIMER == 150 )
  460. {
  461. app_pwm_channel_duty_set(&PWM1, 0, 0);
  462. }else if( SystemTimer.BUZZER_TIMER == 100 )
  463. {
  464. app_pwm_channel_duty_set(&PWM1, 0, 50);
  465. }else if( SystemTimer.BUZZER_TIMER < 50 )
  466. {
  467. app_pwm_channel_duty_set(&PWM1, 0, 0);
  468. SystemManager.BuzzerType = BUZZER_NONE;
  469. app_pwm_disable(&PWM1);
  470. SystemManager.GoSleep = 1;
  471. }
  472. break;
  473. }
  474. }
  475. /**@brief Function for assert macro callback.
  476. *
  477. * @details This function will be called in case of an assert in the SoftDevice.
  478. *
  479. * @warning This handler is an example only and does not fit a final product. You need to analyse
  480. * how your product is supposed to react in case of Assert.
  481. * @warning On assert from the SoftDevice, the system can only recover on reset.
  482. *
  483. * @param[in] line_num Line number of the failing ASSERT call.
  484. * @param[in] p_file_name File name of the failing ASSERT call.
  485. */
  486. void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
  487. {
  488. app_error_handler(DEAD_BEEF, line_num, p_file_name);
  489. }
  490. /**@brief Function for initializing the timer module.
  491. */
  492. static void timers_init(void)
  493. {
  494. ret_code_t err_code = app_timer_init();
  495. APP_ERROR_CHECK(err_code);
  496. app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
  497. app_timer_create(&m_ms_timer_id, APP_TIMER_MODE_REPEATED, timer_ms_timeout_handler);
  498. }
  499. /**@brief Function for the GAP initialization.
  500. *
  501. * @details This function will set up all the necessary GAP (Generic Access Profile) parameters of
  502. * the device. It also sets the permissions and appearance.
  503. */
  504. static void gap_params_init(void)
  505. {
  506. uint32_t err_code;
  507. ble_gap_conn_params_t gap_conn_params;
  508. ble_gap_conn_sec_mode_t sec_mode;
  509. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  510. err_code = sd_ble_gap_device_name_set(&sec_mode,
  511. (const uint8_t *) DEVICE_NAME,
  512. strlen(DEVICE_NAME));
  513. APP_ERROR_CHECK(err_code);
  514. memset(&gap_conn_params, 0, sizeof(gap_conn_params));
  515. gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
  516. gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
  517. gap_conn_params.slave_latency = SLAVE_LATENCY;
  518. gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT;
  519. err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
  520. APP_ERROR_CHECK(err_code);
  521. }
  522. /**@brief Function for handling Queued Write Module errors.
  523. *
  524. * @details A pointer to this function will be passed to each service which may need to inform the
  525. * application about an error.
  526. *
  527. * @param[in] nrf_error Error code containing information about what went wrong.
  528. */
  529. static void nrf_qwr_error_handler(uint32_t nrf_error)
  530. {
  531. APP_ERROR_HANDLER(nrf_error);
  532. }
  533. /**@brief Function for handling the data from the Nordic UART Service.
  534. *
  535. * @details This function will process the data received from the Nordic UART BLE Service and send
  536. * it to the UART module.
  537. *
  538. * @param[in] p_evt Nordic UART Service event.
  539. */
  540. /**@snippet [Handling the data received over BLE] */
  541. static void nus_data_handler(ble_nus_evt_t * p_evt)
  542. {
  543. uint32_t i;
  544. uint32_t err_code;
  545. uint8_t Aes_temp[16];
  546. uint8_t Aes_Dec_temp[16];
  547. switch(p_evt->type){
  548. case BLE_NUS_EVT_RX_DATA:
  549. NRF_LOG_RAW_INFO("BLE_NUS_EVT_RX_DATA (AES) => ");
  550. for (i = 0; i < p_evt->params.rx_data.length; i++)
  551. {
  552. NRF_LOG_RAW_INFO("0x%02x, ", *(p_evt->params.rx_data.p_data+i));
  553. }
  554. NRF_LOG_RAW_INFO("\n");
  555. for(i=0; i<16; i++){
  556. Aes_temp[i] = *(p_evt->params.rx_data.p_data+i);
  557. }
  558. WesDecryptEcb( &Aes_temp[0], &Aes_Dec_temp[0] );
  559. NRF_LOG_RAW_INFO("BLE_NUS_EVT_RX_DATA (ORG) => ");
  560. for (i=0; i<16; i++)
  561. {
  562. NRF_LOG_RAW_INFO("0x%02x, ", Aes_Dec_temp[i]);
  563. }
  564. NRF_LOG_RAW_INFO("\n");
  565. SystemManager.random_value[0] = Aes_Dec_temp[3];
  566. SystemManager.random_value[1] = Aes_Dec_temp[4];
  567. break;
  568. case BLE_NUS_EVT_TX_RDY:
  569. NRF_LOG_RAW_INFO("BLE_NUS_EVT_TX_RDY ======> \n");
  570. break;
  571. case BLE_NUS_EVT_COMM_STARTED:
  572. NRF_LOG_RAW_INFO("BLE_NUS_EVT_COMM_STARTED ======> \n");
  573. break;
  574. case BLE_NUS_EVT_COMM_STOPPED:
  575. NRF_LOG_RAW_INFO("BLE_NUS_EVT_COMM_STOPPED ======> \n");
  576. break;
  577. }
  578. }
  579. /**@snippet [Handling the data received over BLE] */
  580. /**@brief Function for initializing services that will be used by the application.
  581. */
  582. static void services_init(void)
  583. {
  584. uint32_t err_code;
  585. ble_nus_init_t nus_init;
  586. nrf_ble_qwr_init_t qwr_init = {0};
  587. // Initialize Queued Write Module.
  588. qwr_init.error_handler = nrf_qwr_error_handler;
  589. err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init);
  590. APP_ERROR_CHECK(err_code);
  591. // Initialize NUS.
  592. memset(&nus_init, 0, sizeof(nus_init));
  593. nus_init.data_handler = nus_data_handler;
  594. err_code = ble_nus_init(&m_nus, &nus_init);
  595. APP_ERROR_CHECK(err_code);
  596. }
  597. /**@brief Function for handling an event from the Connection Parameters Module.
  598. *
  599. * @details This function will be called for all events in the Connection Parameters Module
  600. * which are passed to the application.
  601. *
  602. * @note All this function does is to disconnect. This could have been done by simply setting
  603. * the disconnect_on_fail config parameter, but instead we use the event handler
  604. * mechanism to demonstrate its use.
  605. *
  606. * @param[in] p_evt Event received from the Connection Parameters Module.
  607. */
  608. static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
  609. {
  610. uint32_t err_code;
  611. if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
  612. {
  613. err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
  614. APP_ERROR_CHECK(err_code);
  615. }
  616. }
  617. /**@brief Function for handling errors from the Connection Parameters module.
  618. *
  619. * @param[in] nrf_error Error code containing information about what went wrong.
  620. */
  621. static void conn_params_error_handler(uint32_t nrf_error)
  622. {
  623. APP_ERROR_HANDLER(nrf_error);
  624. }
  625. /**@brief Function for initializing the Connection Parameters module.
  626. */
  627. static void conn_params_init(void)
  628. {
  629. uint32_t err_code;
  630. ble_conn_params_init_t cp_init;
  631. memset(&cp_init, 0, sizeof(cp_init));
  632. cp_init.p_conn_params = NULL;
  633. cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
  634. cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
  635. cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
  636. cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
  637. cp_init.disconnect_on_fail = false;
  638. cp_init.evt_handler = on_conn_params_evt;
  639. cp_init.error_handler = conn_params_error_handler;
  640. err_code = ble_conn_params_init(&cp_init);
  641. APP_ERROR_CHECK(err_code);
  642. }
  643. /**@brief Function for putting the chip into sleep mode.
  644. *
  645. * @note This function will not return.
  646. */
  647. static void sleep_mode_enter(void)
  648. {
  649. uint32_t err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  650. APP_ERROR_CHECK(err_code);
  651. // Prepare wakeup buttons.
  652. err_code = bsp_btn_ble_sleep_mode_prepare();
  653. APP_ERROR_CHECK(err_code);
  654. SysStatus = 300;
  655. // Go to system-off mode (this function will not return; wakeup will cause a reset).
  656. err_code = sd_power_system_off();
  657. APP_ERROR_CHECK(err_code);
  658. }
  659. /**@brief Function for handling advertising events.
  660. *
  661. * @details This function will be called for advertising events which are passed to the application.
  662. *
  663. * @param[in] ble_adv_evt Advertising event.
  664. */
  665. static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
  666. {
  667. uint32_t err_code;
  668. switch (ble_adv_evt)
  669. {
  670. case BLE_ADV_EVT_FAST:
  671. NRF_LOG_INFO("BLE_ADV_EVT_FAST");
  672. SystemManager.BleConnectTime = 0;
  673. err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
  674. SysStatus = 200;
  675. APP_ERROR_CHECK(err_code);
  676. break;
  677. case BLE_ADV_EVT_IDLE:
  678. NRF_LOG_INFO("BLE_ADV_EVT_IDLE");
  679. err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  680. APP_ERROR_CHECK(err_code);
  681. app_pwm_disable(&PWM1);
  682. app_timer_stop(m_ms_timer_id);
  683. app_timer_stop(m_our_char_timer_id);
  684. NVIC_SystemReset();
  685. app_timer_start(wakeup_timer_id, WAKEUP_TIME_INVERVAL, NULL);
  686. err_code = sd_app_evt_wait();
  687. APP_ERROR_CHECK(err_code);
  688. //StartRTC();
  689. //app_timer_start(wakeup_timer_id, APP_TIMER_TICKS(15000), NULL);
  690. // Enter System ON sleep mode
  691. //__WFE();
  692. // Make sure any pending events are cleared
  693. //__SEV();
  694. // __WFE();
  695. //sleep_mode_enter();
  696. // err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  697. //APP_ERROR_CHECK(err_code);
  698. //app_timer_start(wakeup_timer_id, APP_TIMER_TICKS(5000), NULL);
  699. // err_code = sd_app_evt_wait();
  700. //SysStatus = 201;
  701. //app_uart_close();
  702. //idle_state_handle();
  703. break;
  704. default:
  705. break;
  706. }
  707. }
  708. int localNameChg = 0;
  709. /**@brief Function for handling BLE events.
  710. *
  711. * @param[in] p_ble_evt Bluetooth stack event.
  712. * @param[in] p_context Unused.
  713. */
  714. static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
  715. {
  716. uint32_t err_code;
  717. switch (p_ble_evt->header.evt_id)
  718. {
  719. case BLE_GAP_EVT_ADV_REPORT :
  720. NRF_LOG_INFO("BLE_GAP_EVT_ADV_REPORT ");
  721. break;
  722. case BLE_GAP_EVT_SCAN_REQ_REPORT:
  723. #if 0
  724. NRF_LOG_INFO("BLE_GAP_EVT_SCAN_REQ_REPORT");
  725. ble_gap_evt_scan_req_report_t * p_scan_req_report_t = (ble_gap_evt_scan_req_report_t *)&p_ble_evt->evt.gap_evt.params.scan_req_report;
  726. NRF_LOG_INFO("Peer Address = 0x%02x:%02x:%02x:%02x:%02x:%02x",
  727. p_scan_req_report_t->peer_addr.addr[0],
  728. p_scan_req_report_t->peer_addr.addr[1],
  729. p_scan_req_report_t->peer_addr.addr[2],
  730. p_scan_req_report_t->peer_addr.addr[3],
  731. p_scan_req_report_t->peer_addr.addr[4],
  732. p_scan_req_report_t->peer_addr.addr[5]);
  733. NRF_LOG_INFO("RSSI value = %d dBm", p_scan_req_report_t->rssi);
  734. SystemManager.PeerAddr[0] = p_scan_req_report_t->peer_addr.addr[0];
  735. SystemManager.PeerAddr[1] = p_scan_req_report_t->peer_addr.addr[1];
  736. SystemManager.PeerAddr[2] = p_scan_req_report_t->peer_addr.addr[2];
  737. SystemManager.PeerAddr[3] = p_scan_req_report_t->peer_addr.addr[3];
  738. SystemManager.PeerAddr[4] = p_scan_req_report_t->peer_addr.addr[4];
  739. SystemManager.PeerAddr[5] = p_scan_req_report_t->peer_addr.addr[5];
  740. sprintf(SystemManager.StrPeerAddr, "%02x%02x%02x%02x%02x%02x", p_scan_req_report_t->peer_addr.addr[0],
  741. p_scan_req_report_t->peer_addr.addr[1],
  742. p_scan_req_report_t->peer_addr.addr[2],
  743. p_scan_req_report_t->peer_addr.addr[3],
  744. p_scan_req_report_t->peer_addr.addr[4],
  745. p_scan_req_report_t->peer_addr.addr[5]);
  746. SystemManager.StrPeerAddr[12] = 0;
  747. if( Key1Flag )
  748. break;
  749. if( strncmp( SystemManager.StrRegPeerAddr, SystemManager.StrPeerAddr, 12 ) != 0 )
  750. {
  751. NRF_LOG_INFO("Reg Receiver Arrived.\n");
  752. break;
  753. }
  754. NRF_LOG_INFO("Reg Receiver Arrived.\n");
  755. if( localNameChg++ == 2 )
  756. {
  757. ble_gap_conn_params_t gap_conn_params;
  758. ble_gap_conn_sec_mode_t sec_mode;
  759. // memcpy( &DEVICE_NAME[6], SystemManager.RegPeerAddr, 6); //
  760. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  761. sd_ble_gap_device_name_set(&sec_mode, (const uint8_t *)DEVICE_NAME, strlen(DEVICE_NAME));
  762. sd_ble_gap_adv_stop(p_m_advertising->adv_handle);
  763. memcpy( &p_m_advertising->adv_data.adv_data.p_data[14], &DEVICE_NAME[6], 6 );
  764. memcpy( &p_m_advertising->adv_data.scan_rsp_data.p_data[14], &DEVICE_NAME[6], 6 );
  765. //ble_advdata_encode(p_m_advertising->p_adv_data, p_m_advertising->adv_data.adv_data.p_data, &p_m_advertising->adv_data.adv_data.len);
  766. sd_ble_gap_adv_set_configure(&p_m_advertising->adv_handle, &p_m_advertising->adv_data, &p_m_advertising->adv_params);
  767. sd_ble_gap_adv_start(p_m_advertising->adv_handle, APP_BLE_CONN_CFG_TAG);
  768. NRF_LOG_INFO("Local Name Change = %d", err_code);
  769. }
  770. else if( localNameChg == 2)
  771. {
  772. }
  773. #endif
  774. break;
  775. case BLE_GAP_EVT_CONNECTED:
  776. NRF_LOG_INFO("<============ BLE_GAP_EVT_CONNECTED =========>");
  777. err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
  778. APP_ERROR_CHECK(err_code);
  779. m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
  780. err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
  781. APP_ERROR_CHECK(err_code);
  782. SystemManager.BleConnected = 1;
  783. SystemTimer.SEND_TIMER = 0;
  784. break;
  785. case BLE_GAP_EVT_DISCONNECTED:
  786. NRF_LOG_INFO("<============ BLE_GAP_EVT_DISCONNECTED =========>");
  787. // LED indication will be changed when advertising starts.
  788. m_conn_handle = BLE_CONN_HANDLE_INVALID;
  789. NVIC_SystemReset();
  790. #if 0
  791. err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  792. APP_ERROR_CHECK(err_code);
  793. app_pwm_disable(&PWM1);
  794. app_timer_stop(m_ms_timer_id);
  795. app_timer_stop(m_our_char_timer_id);
  796. app_timer_start(wakeup_timer_id, WAKEUP_TIME_INVERVAL, NULL);
  797. err_code = sd_app_evt_wait();
  798. APP_ERROR_CHECK(err_code);
  799. #endif
  800. break;
  801. case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
  802. NRF_LOG_DEBUG("PHY update request.");
  803. ble_gap_phys_t const phys =
  804. {
  805. .rx_phys = BLE_GAP_PHY_AUTO,
  806. .tx_phys = BLE_GAP_PHY_AUTO,
  807. };
  808. err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
  809. APP_ERROR_CHECK(err_code);
  810. break;
  811. case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
  812. // Pairing not supported
  813. err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
  814. APP_ERROR_CHECK(err_code);
  815. break;
  816. case BLE_GATTS_EVT_SYS_ATTR_MISSING:
  817. // No system attributes have been stored.
  818. err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
  819. APP_ERROR_CHECK(err_code);
  820. break;
  821. case BLE_GATTC_EVT_TIMEOUT:
  822. // Disconnect on GATT Client timeout event.
  823. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
  824. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  825. APP_ERROR_CHECK(err_code);
  826. break;
  827. case BLE_GATTS_EVT_TIMEOUT:
  828. // Disconnect on GATT Server timeout event.
  829. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
  830. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  831. APP_ERROR_CHECK(err_code);
  832. break;
  833. default:
  834. // No implementation needed.
  835. break;
  836. }
  837. }
  838. /**@brief Function for the SoftDevice initialization.
  839. *
  840. * @details This function initializes the SoftDevice and the BLE event interrupt.
  841. */
  842. static void ble_stack_init(void)
  843. {
  844. ret_code_t err_code;
  845. err_code = nrf_sdh_enable_request();
  846. APP_ERROR_CHECK(err_code);
  847. // Configure the BLE stack using the default settings.
  848. // Fetch the start address of the application RAM.
  849. uint32_t ram_start = 0;
  850. err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
  851. APP_ERROR_CHECK(err_code);
  852. // Enable BLE stack.
  853. err_code = nrf_sdh_ble_enable(&ram_start);
  854. APP_ERROR_CHECK(err_code);
  855. /* enable DCDC to save current */
  856. err_code = sd_power_dcdc_mode_set(NRF_POWER_DCDC_ENABLE);
  857. APP_ERROR_CHECK(err_code);
  858. // Register a handler for BLE events.
  859. NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
  860. }
  861. /**@brief Function for handling events from the GATT library. */
  862. void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
  863. {
  864. if ((m_conn_handle == p_evt->conn_handle) && (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED))
  865. {
  866. m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
  867. NRF_LOG_INFO("Data len is set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
  868. }
  869. NRF_LOG_DEBUG("ATT MTU exchange completed. central 0x%x peripheral 0x%x",
  870. p_gatt->att_mtu_desired_central,
  871. p_gatt->att_mtu_desired_periph);
  872. }
  873. /**@brief Function for initializing the GATT library. */
  874. void gatt_init(void)
  875. {
  876. ret_code_t err_code;
  877. err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
  878. APP_ERROR_CHECK(err_code);
  879. err_code = nrf_ble_gatt_att_mtu_periph_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
  880. APP_ERROR_CHECK(err_code);
  881. }
  882. /**@brief Function for handling events from the BSP module.
  883. *
  884. * @param[in] event Event generated by button press.
  885. */
  886. void bsp_event_handler(bsp_event_t event)
  887. {
  888. uint32_t err_code;
  889. NRF_LOG_INFO("BSP_EVENT_HANDLER => %d", event);
  890. switch (event)
  891. {
  892. case BSP_EVENT_DFU: //
  893. NRF_LOG_INFO("@@@@@@@ BSP_EVENT_DFU=>%d", event);
  894. break;
  895. case BSP_EVENT_ADVERTISING_START: //
  896. NRF_LOG_INFO("@@@@@@@ BSP_EVENT_ADVERTISING_START=>%d", event);
  897. break;
  898. case BSP_EVENT_ADVERTISING_STOP: //
  899. NRF_LOG_INFO("@@@@@@@ BSP_EVENT_ADVERTISING_STOP=>%d", event);
  900. break;
  901. case BSP_EVENT_SLEEP: //
  902. NRF_LOG_INFO("@@@@@@@ bsp_event_handler() -- BSP_EVENT_SLEEP");
  903. //sleep_mode_enter();
  904. break;
  905. case BSP_EVENT_WAKEUP: //
  906. NRF_LOG_INFO("@@@@@@@ BSP_EVENT_WAKEUP=>%d", event);
  907. advertising_flag = 0;
  908. break;
  909. case BSP_EVENT_DISCONNECT:
  910. NRF_LOG_INFO("bsp_event_handler() -- BSP_EVENT_DISCONNECT");
  911. err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  912. if (err_code != NRF_ERROR_INVALID_STATE)
  913. {
  914. APP_ERROR_CHECK(err_code);
  915. }
  916. break;
  917. case BSP_EVENT_WHITELIST_OFF:
  918. NRF_LOG_INFO("bsp_event_handler() -- BSP_EVENT_WHITELIST_OFF");
  919. if (m_conn_handle == BLE_CONN_HANDLE_INVALID)
  920. {
  921. err_code = ble_advertising_restart_without_whitelist(&m_advertising);
  922. if (err_code != NRF_ERROR_INVALID_STATE)
  923. {
  924. APP_ERROR_CHECK(err_code);
  925. }
  926. }
  927. break;
  928. case BSP_EVENT_KEY_1: // event 15 TEST
  929. Battery_Adc_Read();
  930. err_code = app_timer_start(m_ms_timer_id, TIMER_MS_INTERVAL, NULL);
  931. APP_ERROR_CHECK(err_code);
  932. err_code = app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
  933. APP_ERROR_CHECK(err_code);
  934. //strncpy( DEVICE_NAME, "ICSWES", 6);
  935. break;
  936. case BSP_EVENT_KEY_2: // event 16 EMG
  937. Battery_Adc_Read();
  938. err_code = app_timer_start(m_ms_timer_id, TIMER_MS_INTERVAL, NULL);
  939. APP_ERROR_CHECK(err_code);
  940. err_code = app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
  941. APP_ERROR_CHECK(err_code);
  942. break;
  943. default:
  944. break;
  945. }
  946. }
  947. /* *@brief Undo the changes that we did when advertising has the timeout.
  948. */
  949. void wakeup_timer_handler(void * p_context)
  950. {
  951. uint32_t err_code;
  952. app_timer_stop(wakeup_timer_id);
  953. app_timer_start(m_ms_timer_id, TIMER_MS_INTERVAL, NULL);
  954. app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
  955. bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, bsp_event_handler);
  956. APP_ERROR_CHECK(err_code);
  957. //err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
  958. err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
  959. APP_ERROR_CHECK(err_code);
  960. SystemManager.EmgSendButton = BUTTON_ALIVE;
  961. NRF_LOG_INFO("==> Alive Send");
  962. SystemTimer.EMG_SEND_RUN = 1;
  963. SystemTimer.SEND_TIMER = 0;
  964. }
  965. // 25ms Timer
  966. static void timer_ms_timeout_handler(void * p_context)
  967. {
  968. UNUSED_PARAMETER(p_context);
  969. HSDInRun();
  970. }
  971. /**@brief Function for handling app_uart events.
  972. *
  973. * @details This function will receive a single character from the app_uart module and append it to
  974. * a string. The string will be be sent over BLE when the last character received was a
  975. * 'new line' '\n' (hex 0x0A) or if the string has reached the maximum data length.
  976. */
  977. /**@snippet [Handling the data received over UART] */
  978. void uart_event_handle(app_uart_evt_t * p_event)
  979. {
  980. static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
  981. static uint8_t index = 0;
  982. uint32_t err_code;
  983. switch (p_event->evt_type)
  984. {
  985. case APP_UART_DATA_READY:
  986. NRF_LOG_DEBUG("uart_event_handle -- APP_UART_DATA_READY");
  987. UNUSED_VARIABLE(app_uart_get(&data_array[index]));
  988. index++;
  989. if ((data_array[index - 1] == '\n') ||
  990. (data_array[index - 1] == '\r') ||
  991. (index >= m_ble_nus_max_data_len))
  992. {
  993. if (index > 1)
  994. {
  995. NRF_LOG_DEBUG("Ready to send data over BLE NUS");
  996. NRF_LOG_HEXDUMP_DEBUG(data_array, index);
  997. do
  998. {
  999. uint16_t length = (uint16_t)index;
  1000. err_code = ble_nus_data_send(&m_nus, data_array, &length, m_conn_handle);
  1001. if ((err_code != NRF_ERROR_INVALID_STATE) &&
  1002. (err_code != NRF_ERROR_RESOURCES) &&
  1003. (err_code != NRF_ERROR_NOT_FOUND))
  1004. {
  1005. APP_ERROR_CHECK(err_code);
  1006. }
  1007. } while (err_code == NRF_ERROR_RESOURCES);
  1008. }
  1009. index = 0;
  1010. }
  1011. break;
  1012. case APP_UART_COMMUNICATION_ERROR:
  1013. NRF_LOG_DEBUG("uart_event_handle -- APP_UART_COMMUNICATION_ERROR");
  1014. APP_ERROR_HANDLER(p_event->data.error_communication);
  1015. break;
  1016. case APP_UART_FIFO_ERROR:
  1017. NRF_LOG_DEBUG("uart_event_handle -- APP_UART_FIFO_ERROR");
  1018. APP_ERROR_HANDLER(p_event->data.error_code);
  1019. break;
  1020. case APP_UART_TX_EMPTY:
  1021. NRF_LOG_DEBUG("uart_event_handle -- APP_UART_TX_EMPTY");
  1022. break;
  1023. case APP_UART_DATA:
  1024. NRF_LOG_DEBUG("uart_event_handle -- APP_UART_DATA");
  1025. break;
  1026. default:
  1027. break;
  1028. }
  1029. }
  1030. /**@snippet [Handling the data received over UART] */
  1031. /**@brief Function for initializing the UART module.
  1032. */
  1033. /**@snippet [UART Initialization] */
  1034. static void uart_init(void)
  1035. {
  1036. uint32_t err_code;
  1037. app_uart_comm_params_t const comm_params =
  1038. {
  1039. .rx_pin_no = RX_PIN_NUMBER,
  1040. .tx_pin_no = TX_PIN_NUMBER,
  1041. .rts_pin_no = RTS_PIN_NUMBER,
  1042. .cts_pin_no = CTS_PIN_NUMBER,
  1043. .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
  1044. .use_parity = false,
  1045. #if defined (UART_PRESENT)
  1046. .baud_rate = NRF_UART_BAUDRATE_115200
  1047. #else
  1048. .baud_rate = NRF_UARTE_BAUDRATE_115200
  1049. #endif
  1050. };
  1051. APP_UART_FIFO_INIT(&comm_params,
  1052. UART_RX_BUF_SIZE,
  1053. UART_TX_BUF_SIZE,
  1054. uart_event_handle,
  1055. APP_IRQ_PRIORITY_LOWEST,
  1056. err_code);
  1057. APP_ERROR_CHECK(err_code);
  1058. }
  1059. /**@snippet [UART Initialization] */
  1060. /**@brief Function for initializing the Advertising functionality.
  1061. */
  1062. static void advertising_init(void)
  1063. {
  1064. //p_m_advertising->adv_data.adv_data.p_data = p_m_advertising->enc_advdata;
  1065. ret_code_t err_code;
  1066. ble_advertising_init_t init;
  1067. char plevel = 0xfe;
  1068. ble_advdata_conn_int_t connParams;
  1069. connParams.min_conn_interval = 0x20;
  1070. connParams.max_conn_interval = 0x28;
  1071. memset(&init, 0, sizeof(init));
  1072. init.advdata.name_type = BLE_ADVDATA_FULL_NAME;
  1073. init.advdata.include_appearance = false;
  1074. init.advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_LIMITED_DISC_MODE;
  1075. init.advdata.p_tx_power_level = &plevel;
  1076. init.advdata.p_slave_conn_int = &connParams;
  1077. // Prepare the scan response manufacturer specific data packet
  1078. ble_advdata_manuf_data_t manuf_data_response;
  1079. uint8_t data_response[] = "M";
  1080. manuf_data_response.company_identifier = 0x0059;
  1081. manuf_data_response.data.p_data = data_response;
  1082. manuf_data_response.data.size = sizeof(data_response);
  1083. init.srdata.name_type = BLE_ADVDATA_FULL_NAME;
  1084. init.srdata.p_manuf_specific_data = &manuf_data_response;
  1085. init.config.ble_adv_fast_enabled = true;
  1086. init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
  1087. init.config.ble_adv_fast_timeout = APP_ADV_DURATION;
  1088. init.evt_handler = on_adv_evt;
  1089. err_code = ble_advertising_init(&m_advertising, &init);
  1090. APP_ERROR_CHECK(err_code);
  1091. ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
  1092. p_m_advertising = &m_advertising;
  1093. }
  1094. /**@brief Function for initializing buttons and leds.
  1095. *
  1096. * @param[out] p_erase_bonds Will be true if the clear bonding button was pressed to wake the application up.
  1097. */
  1098. static void buttons_leds_init(bool * p_erase_bonds)
  1099. {
  1100. bsp_event_t startup_event;
  1101. uint32_t err_code = bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, bsp_event_handler);
  1102. APP_ERROR_CHECK(err_code);
  1103. err_code = bsp_btn_ble_init(NULL, &startup_event);
  1104. APP_ERROR_CHECK(err_code);
  1105. *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
  1106. }
  1107. /**@brief Function for initializing the nrf log module.
  1108. */
  1109. static void log_init(void)
  1110. {
  1111. ret_code_t err_code = NRF_LOG_INIT(NULL);
  1112. APP_ERROR_CHECK(err_code);
  1113. NRF_LOG_DEFAULT_BACKENDS_INIT();
  1114. }
  1115. /**@brief Function for initializing power management.
  1116. */
  1117. static void power_management_init(void)
  1118. {
  1119. ret_code_t err_code;
  1120. err_code = nrf_pwr_mgmt_init();
  1121. APP_ERROR_CHECK(err_code);
  1122. }
  1123. /**@brief Function for handling the idle state (main loop).
  1124. *
  1125. * @details If there is no pending log operation, then sleep until next the next event occurs.
  1126. */
  1127. static void idle_state_handle(void)
  1128. {
  1129. if (NRF_LOG_PROCESS() == false)
  1130. {
  1131. nrf_pwr_mgmt_run();
  1132. }
  1133. }
  1134. /**@brief Function for starting advertising.
  1135. */
  1136. void advertising_start(void)
  1137. {
  1138. uint32_t err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
  1139. APP_ERROR_CHECK(err_code);
  1140. advertising_flag = 1;
  1141. }
  1142. static void leds_config(void)
  1143. {
  1144. bsp_board_init(BSP_INIT_LEDS);
  1145. }
  1146. void Battery_Adc_Read(void)
  1147. {
  1148. uint32_t avr = 0;
  1149. nrf_delay_ms(5);
  1150. nrf_drv_saadc_sample_convert(NRF_SAADC_INPUT_AIN2, &m_buffer_pool[0]);
  1151. nrf_delay_ms(5);
  1152. nrf_drv_saadc_sample_convert(NRF_SAADC_INPUT_AIN2, &m_buffer_pool[1]);
  1153. nrf_delay_ms(5);
  1154. nrf_drv_saadc_sample_convert(NRF_SAADC_INPUT_AIN2, &m_buffer_pool[2]);
  1155. avr = m_buffer_pool[0] + m_buffer_pool[1] + m_buffer_pool[2];
  1156. avr /= 3;
  1157. SystemManager.Batt = (((float)avr*0.708)-200.0)*(100.0/(330.0-200.0));
  1158. if(SystemManager.Batt > 100)
  1159. SystemManager.Batt = 100;
  1160. NRF_LOG_INFO("Vol:%d -- [%d]\r\n",(int)((float)avr*0.708), SystemManager.Batt);
  1161. #if 0
  1162. if(nrf_drv_saadc_sample_convert(NRF_SAADC_INPUT_AIN2, m_buffer_pool) == NRF_SUCCESS)
  1163. {
  1164. // SystemManager.Batt = (((float)m_buffer_pool[0]*0.708)/330.0)*100;
  1165. SystemManager.Batt = (((float)m_buffer_pool[0]*0.708)-200.0)*(100.0/(330.0-200.0));
  1166. if(SystemManager.Batt > 100)
  1167. SystemManager.Batt = 100;
  1168. NRF_LOG_INFO("Vol:%d -- [%d]\r\n",(int)((float)m_buffer_pool[0]*0.708), SystemManager.Batt);
  1169. }
  1170. #endif
  1171. }
  1172. void Buzzer_Select(uint8_t state)
  1173. {
  1174. switch(state){
  1175. case BUZZER_NONE:
  1176. break;
  1177. case BUZZER_EMG:
  1178. if( SystemManager.BuzzerType == BUZZER_NONE )
  1179. {
  1180. SystemManager.BuzzerType = 1;
  1181. if(SystemManager.Batt > BATTERY_LOW_LEVEL)
  1182. SystemTimer.BUZZER_TIMER = 200;
  1183. else
  1184. SystemTimer.BUZZER_TIMER = 600;
  1185. app_pwm_enable(&PWM1);
  1186. app_pwm_channel_duty_set(&PWM1, 0, 50);
  1187. }
  1188. break;
  1189. case BUZZER_TEST:
  1190. if( SystemManager.BuzzerType == BUZZER_NONE )
  1191. {
  1192. SystemManager.BuzzerType = 2;
  1193. if(SystemManager.Batt > BATTERY_LOW_LEVEL)
  1194. SystemTimer.BUZZER_TIMER = 100;
  1195. else
  1196. SystemTimer.BUZZER_TIMER = 600;
  1197. app_pwm_enable(&PWM1);
  1198. app_pwm_channel_duty_set(&PWM1, 0, 50);
  1199. }
  1200. break;
  1201. case BUZZER_REG:
  1202. if( SystemManager.BuzzerType == BUZZER_NONE )
  1203. {
  1204. SystemManager.BuzzerType = 3;
  1205. SystemTimer.BUZZER_TIMER = 500;
  1206. app_pwm_enable(&PWM1);
  1207. app_pwm_channel_duty_set(&PWM1, 0, 50);
  1208. }
  1209. break;
  1210. case BUZZER_BOOT_LOADER:
  1211. if( SystemManager.BuzzerType == BUZZER_NONE )
  1212. {
  1213. SystemManager.BuzzerType = 4;
  1214. SystemTimer.BUZZER_TIMER = 1000;
  1215. app_pwm_enable(&PWM1);
  1216. app_pwm_channel_duty_set(&PWM1, 0, 50);
  1217. }
  1218. break;
  1219. case BUZZER_POWER_ON:
  1220. if( SystemManager.BuzzerType == BUZZER_NONE )
  1221. {
  1222. SystemManager.BuzzerType = BUZZER_POWER_ON;
  1223. SystemTimer.BUZZER_TIMER = 300;
  1224. app_pwm_enable(&PWM1);
  1225. app_pwm_channel_duty_set(&PWM1, 0, 50);
  1226. }
  1227. break;
  1228. }
  1229. }
  1230. // EMG
  1231. void SendEmgData(void)
  1232. {
  1233. static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
  1234. static uint8_t index = 0;
  1235. uint32_t err_code;
  1236. uint16_t length;
  1237. int i;
  1238. NRF_LOG_INFO("SendEmgData(%d)", SystemManager.Batt);
  1239. data_array[0] = COMMAND_TYPE;
  1240. data_array[1] = UID_VALUE_01;
  1241. data_array[2] = UID_VALUE_02;
  1242. data_array[3] = UID_VALUE_03;
  1243. data_array[4] = UID_VALUE_04;
  1244. data_array[5] = SITE_VALUE_01;
  1245. data_array[6] = SITE_VALUE_02;
  1246. data_array[7] = SITE_VALUE_03;
  1247. data_array[8] = SITE_VALUE_04;
  1248. data_array[9] = new_ble_addr.addr[3];
  1249. data_array[10] = new_ble_addr.addr[4];
  1250. data_array[11] = new_ble_addr.addr[5];
  1251. data_array[12] = COMMAND_EMG;
  1252. data_array[13] = SystemManager.Batt;
  1253. data_array[14] = VER_HIGH_VALUE;
  1254. data_array[15] = VER_LOW_VALUE;
  1255. data_array[16] = SystemManager.random_value[1];
  1256. length = COMMAND_LENGTH;
  1257. WesEncryptEcb( &data_array[1] );
  1258. err_code = ble_nus_data_send(&m_nus, data_array, &length, m_conn_handle);
  1259. for( i=0; i<17; i++)
  1260. {
  1261. NRF_LOG_RAW_INFO("%02x ", data_array[i]);
  1262. }
  1263. NRF_LOG_RAW_INFO("\n");
  1264. SystemManager.BleSendStatus = err_code;
  1265. if ((err_code != NRF_ERROR_RESOURCES)&&(err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_ERROR_BUSY) && (err_code != NRF_ERROR_NOT_FOUND))// (or anything else you want to filter out...)
  1266. {
  1267. APP_ERROR_CHECK(err_code);
  1268. }
  1269. }
  1270. // Test
  1271. void SendTestData(void)
  1272. {
  1273. static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
  1274. static uint8_t index = 0;
  1275. uint32_t err_code;
  1276. uint16_t length;
  1277. NRF_LOG_INFO("SendTestData()");
  1278. data_array[0] = COMMAND_TYPE;
  1279. data_array[1] = UID_VALUE_01;
  1280. data_array[2] = UID_VALUE_02;
  1281. data_array[3] = UID_VALUE_03;
  1282. data_array[4] = UID_VALUE_04;
  1283. data_array[5] = SITE_VALUE_01;
  1284. data_array[6] = SITE_VALUE_02;
  1285. data_array[7] = SITE_VALUE_03;
  1286. data_array[8] = SITE_VALUE_04;
  1287. data_array[9] = new_ble_addr.addr[3];
  1288. data_array[10] = new_ble_addr.addr[4];
  1289. data_array[11] = new_ble_addr.addr[5];
  1290. data_array[12] = COMMAND_TEST;
  1291. data_array[13] = SystemManager.Batt;
  1292. data_array[14] = VER_HIGH_VALUE;
  1293. data_array[15] = VER_LOW_VALUE;
  1294. data_array[16] = SystemManager.random_value[1];
  1295. length = COMMAND_LENGTH;
  1296. WesEncryptEcb( &data_array[1] );
  1297. err_code = ble_nus_data_send(&m_nus, data_array, &length, m_conn_handle);
  1298. SystemManager.BleSendStatus = err_code;
  1299. if ((err_code != NRF_ERROR_RESOURCES)&&(err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_ERROR_BUSY) && (err_code != NRF_ERROR_NOT_FOUND))// (or anything else you want to filter out...)
  1300. {
  1301. APP_ERROR_CHECK(err_code);
  1302. }
  1303. }
  1304. void SendAliveData(void)
  1305. {
  1306. static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
  1307. static uint8_t index = 0;
  1308. uint32_t err_code;
  1309. uint16_t length;
  1310. NRF_LOG_INFO("SendAliveData()");
  1311. data_array[0] = COMMAND_TYPE;
  1312. data_array[1] = UID_VALUE_01;
  1313. data_array[2] = UID_VALUE_02;
  1314. data_array[3] = UID_VALUE_03;
  1315. data_array[4] = UID_VALUE_04;
  1316. data_array[5] = SITE_VALUE_01;
  1317. data_array[6] = SITE_VALUE_02;
  1318. data_array[7] = SITE_VALUE_03;
  1319. data_array[8] = SITE_VALUE_04;
  1320. data_array[9] = new_ble_addr.addr[3];
  1321. data_array[10] = new_ble_addr.addr[4];
  1322. data_array[11] = new_ble_addr.addr[5];
  1323. data_array[12] = COMMAND_ALIVE;
  1324. data_array[13] = SystemManager.Batt;
  1325. data_array[14] = VER_HIGH_VALUE;
  1326. data_array[15] = VER_LOW_VALUE;
  1327. data_array[16] = SystemManager.random_value[1];
  1328. length = COMMAND_LENGTH;
  1329. WesEncryptEcb( &data_array[1] );
  1330. err_code = ble_nus_data_send(&m_nus, data_array, &length, m_conn_handle);
  1331. SystemManager.BleSendStatus = err_code;
  1332. if ((err_code != NRF_ERROR_RESOURCES)&&(err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_ERROR_BUSY) && (err_code != NRF_ERROR_NOT_FOUND))// (or anything else you want to filter out...)
  1333. {
  1334. APP_ERROR_CHECK(err_code);
  1335. }
  1336. }
  1337. //
  1338. void SendRegData(void)
  1339. {
  1340. static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
  1341. static uint8_t index = 0;
  1342. uint32_t err_code;
  1343. uint16_t length;
  1344. NRF_LOG_INFO("SendRegData()");
  1345. data_array[0] = COMMAND_TYPE;
  1346. data_array[1] = UID_VALUE_01;
  1347. data_array[2] = UID_VALUE_02;
  1348. data_array[3] = UID_VALUE_03;
  1349. data_array[4] = UID_VALUE_04;
  1350. data_array[5] = SITE_VALUE_01;
  1351. data_array[6] = SITE_VALUE_02;
  1352. data_array[7] = SITE_VALUE_03;
  1353. data_array[8] = SITE_VALUE_04;
  1354. data_array[9] = new_ble_addr.addr[3];
  1355. data_array[10] = new_ble_addr.addr[4];
  1356. data_array[11] = new_ble_addr.addr[5];
  1357. data_array[12] = COMMAND_REG;
  1358. data_array[13] = SystemManager.Batt;
  1359. data_array[14] = VER_HIGH_VALUE;
  1360. data_array[15] = VER_LOW_VALUE;
  1361. data_array[16] = SystemManager.random_value[1];
  1362. length = COMMAND_LENGTH;
  1363. WesEncryptEcb( &data_array[1] );
  1364. err_code = ble_nus_data_send(&m_nus, data_array, &length, m_conn_handle);
  1365. SystemManager.BleSendStatus = err_code;
  1366. if ((err_code != NRF_ERROR_RESOURCES)&&(err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_ERROR_BUSY) && (err_code != NRF_ERROR_NOT_FOUND))// (or anything else you want to filter out...)
  1367. {
  1368. APP_ERROR_CHECK(err_code);
  1369. }else{
  1370. }
  1371. }
  1372. void pwm_ready_callback(uint32_t pwm_id) // PWM callback function
  1373. {
  1374. ready_flag = true;
  1375. }
  1376. void pwmInit(void)
  1377. {
  1378. ret_code_t err_code;
  1379. app_pwm_config_t pwm1_cfg = APP_PWM_DEFAULT_CONFIG_1CH(370L, 7); //1000L -> 1Khz, 500L -> 2Khz, 370L -> 2.7Khz
  1380. /* Switch the polarity of the second channel. */
  1381. //pwm1_cfg.pin_polarity[0] = APP_PWM_POLARITY_ACTIVE_LOW;
  1382. pwm1_cfg.pin_polarity[0] = APP_PWM_POLARITY_ACTIVE_HIGH;
  1383. /* Initialize and enable PWM. */
  1384. err_code = app_pwm_init(&PWM1,&pwm1_cfg,pwm_ready_callback);
  1385. APP_ERROR_CHECK(err_code);
  1386. }
  1387. #define SND_WDT_SLEEP_CONFIG \
  1388. { \
  1389. .behaviour = (nrf_wdt_behaviour_t)NRFX_WDT_CONFIG_BEHAVIOUR, \
  1390. .reload_value = SLEEP_WDT_LIMIT, \
  1391. NRFX_WDT_IRQ_CONFIG \
  1392. }
  1393. void WdtRunMode()
  1394. {
  1395. ret_code_t err_code;
  1396. uint64_t time = 10*60*60*1000;
  1397. uint64_t ticks = (time * 32768ULL) / 1000;
  1398. // NRFX_ASSERT(ticks <= UINT32_MAX);
  1399. NRF_LOG_INFO("===>> ticks is [%d]", ticks);
  1400. nrf_wdt_reload_value_set((uint32_t) ticks);
  1401. }
  1402. void WdtSleepMode()
  1403. {
  1404. uint32_t err_code;
  1405. nrf_drv_wdt_config_t config = SND_WDT_SLEEP_CONFIG;
  1406. err_code = nrf_drv_wdt_init(&config, wdt_event_handler);
  1407. APP_ERROR_CHECK(err_code);
  1408. err_code = nrf_drv_wdt_channel_alloc(&m_channel_id);
  1409. APP_ERROR_CHECK(err_code);
  1410. nrf_drv_wdt_enable();
  1411. }
  1412. void ReMac_Mapping()
  1413. {
  1414. ble_gap_addr_t dd;
  1415. dd.addr_id_peer = 0;
  1416. dd.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
  1417. sd_ble_gap_addr_get(&old_ble_addr);
  1418. dd.addr[0] = IES200_1ST_MAC;
  1419. dd.addr[1] = IES200_2ST_MAC;
  1420. dd.addr[2] = IES200_3ST_MAC;
  1421. dd.addr[3] = old_ble_addr.addr[3];
  1422. dd.addr[4] = old_ble_addr.addr[4];
  1423. dd.addr[5] = old_ble_addr.addr[5];
  1424. sd_ble_gap_addr_set(&dd);
  1425. sd_ble_gap_addr_get(&new_ble_addr);
  1426. DEVICE_NAME[9] = dd.addr[3];
  1427. DEVICE_NAME[10] = dd.addr[4];
  1428. DEVICE_NAME[11] = dd.addr[5];
  1429. NRF_LOG_INFO("MAC Address : %02X %02X %02X", dd.addr[3], dd.addr[4], dd.addr[5]);
  1430. }
  1431. /**@brief Application main function.
  1432. */
  1433. int main(void)
  1434. {
  1435. uint32_t err_code = NRF_SUCCESS;
  1436. bool erase_bonds;
  1437. uint8_t flash_buf = 0x00;
  1438. NRF_LOG_RAW_INFO("\n===========================================================\n\n");
  1439. NRF_LOG_RAW_INFO("ICS-200B Program Start --- Ver 1.10 2022/04/04");
  1440. NRF_LOG_RAW_INFO("\n===========================================================\n\n");
  1441. // Initialize.
  1442. //uart_init();
  1443. SaadcInit();
  1444. log_init();
  1445. /* Register first to receive an event when initialization is complete. */
  1446. (void) fds_register(fds_evt_handler);
  1447. pwmInit();
  1448. err_code = fds_init();
  1449. APP_ERROR_CHECK(err_code);
  1450. timers_init();
  1451. HSDInInit();
  1452. SystemManager.GpReg = nrf_power_gpregret_get();
  1453. buttons_leds_init(&erase_bonds);
  1454. power_management_init();
  1455. ble_stack_init();
  1456. ReMac_Mapping();
  1457. SystemManager.ResetReason = NRF_POWER->RESETREAS;
  1458. SystemManager.BleSendStatus = -1;
  1459. gap_params_init();
  1460. gatt_init();
  1461. services_init();
  1462. advertising_init();
  1463. conn_params_init();
  1464. err_code = app_timer_create(&wakeup_timer_id, APP_TIMER_MODE_SINGLE_SHOT, wakeup_timer_handler);
  1465. APP_ERROR_CHECK(err_code);
  1466. err_code = app_timer_create(&m_ms_timer_id, APP_TIMER_MODE_REPEATED, timer_ms_timeout_handler);
  1467. APP_ERROR_CHECK(err_code);
  1468. //err_code = app_timer_start(m_ms_timer_id, TIMER_MS_INTERVAL, NULL);
  1469. //APP_ERROR_CHECK(err_code);
  1470. //err_code = app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
  1471. //APP_ERROR_CHECK(err_code);
  1472. // Start execution.
  1473. //printf("\r\nUART started.\r\n");
  1474. NRF_LOG_INFO("Debug logging for UART over RTT started.");
  1475. //advertising_start();
  1476. ParkSysInit();
  1477. bsp_board_leds_off();
  1478. SystemManager.SendRepeat = 0;
  1479. SystemManager.SendRepeatTimerLimit = 30000; // on time
  1480. err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  1481. APP_ERROR_CHECK(err_code);
  1482. if( SystemManager.GpReg == 0x00 )
  1483. {
  1484. err_code = app_timer_start(m_ms_timer_id, TIMER_MS_INTERVAL, NULL);
  1485. APP_ERROR_CHECK(err_code);
  1486. err_code = app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
  1487. APP_ERROR_CHECK(err_code);
  1488. SystemManager.EmgSendButton = BUTTON_EMG;
  1489. SystemTimer.EMG_SEND_RUN = 1;
  1490. SystemTimer.SEND_TIMER = 0;
  1491. Buzzer_Select(BUZZER_POWER_ON);
  1492. for (;;)
  1493. {
  1494. idle_state_handle();
  1495. if( SystemManager.GoSleep == 1 )
  1496. {
  1497. app_timer_stop(m_ms_timer_id);
  1498. app_timer_stop(m_our_char_timer_id);
  1499. break;
  1500. }
  1501. }
  1502. nrf_power_gpregret_set(0x02);
  1503. }
  1504. #if 0
  1505. else if( SystemManager.GpReg == 0x04 )
  1506. {
  1507. err_code = app_timer_start(m_ms_timer_id, TIMER_MS_INTERVAL, NULL);
  1508. APP_ERROR_CHECK(err_code);
  1509. err_code = app_timer_start(m_our_char_timer_id, OUR_CHAR_TIMER_INTERVAL, NULL);
  1510. APP_ERROR_CHECK(err_code);
  1511. SystemManager.EmgSendButton = BUTTON_REG;
  1512. SystemTimer.EMG_SEND_RUN = 1;
  1513. SystemTimer.SEND_TIMER = 0;
  1514. Buzzer_Select(BUZZER_POWER_ON);
  1515. for (;;)
  1516. {
  1517. idle_state_handle();
  1518. if( SystemManager.GoSleep == 1 )
  1519. {
  1520. app_timer_stop(m_ms_timer_id);
  1521. app_timer_stop(m_our_char_timer_id);
  1522. break;
  1523. }
  1524. }
  1525. nrf_power_gpregret_set(0x02);
  1526. }
  1527. #endif
  1528. WdtSleepMode();
  1529. nrf_drv_wdt_channel_feed(m_channel_id);
  1530. // WdtRunMode();
  1531. app_timer_start(wakeup_timer_id, WAKEUP_TIME_INVERVAL, NULL); // Wake Up Timer Reset
  1532. err_code = sd_app_evt_wait(); // jakuja GOTO SLEEP MODE
  1533. APP_ERROR_CHECK(err_code);
  1534. // <---------------------------------------------------------------->
  1535. Battery_Adc_Read();
  1536. // Enter main loop.
  1537. for (;;)
  1538. {
  1539. SysCounter++;
  1540. idle_state_handle();
  1541. }
  1542. }
  1543. /**
  1544. * @}
  1545. */