nrf_ble_es.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /**
  2. * Copyright (c) 2016 - 2020, Nordic Semiconductor ASA
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without modification,
  7. * are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form, except as embedded into a Nordic
  13. * Semiconductor ASA integrated circuit in a product or a software update for
  14. * such product, must reproduce the above copyright notice, this list of
  15. * conditions and the following disclaimer in the documentation and/or other
  16. * materials provided with the distribution.
  17. *
  18. * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
  19. * contributors may be used to endorse or promote products derived from this
  20. * software without specific prior written permission.
  21. *
  22. * 4. This software, with or without modification, must only be used with a
  23. * Nordic Semiconductor ASA integrated circuit.
  24. *
  25. * 5. Any software provided in binary form under this license must not be reverse
  26. * engineered, decompiled, modified and/or disassembled.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
  29. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31. * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
  32. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  34. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *
  39. */
  40. #include <string.h>
  41. #include "nrf_ble_es.h"
  42. #include "app_error.h"
  43. #include "fds.h"
  44. #include "es_adv.h"
  45. #include "es_battery_voltage.h"
  46. #include "es_flash.h"
  47. #include "es_gatts.h"
  48. #include "es_security.h"
  49. #include "es_slot.h"
  50. #include "es_stopwatch.h"
  51. #include "escs_defs.h"
  52. #include "nrf_sdh_ble.h"
  53. static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; //!< Connection handle.
  54. static nrf_ble_escs_t m_ble_ecs; //!< Struct identifying the Eddystone Config Service.
  55. static nrf_ble_es_evt_handler_t m_evt_handler; //!< Event handler.
  56. uint8_t m_adv_handle = BLE_GAP_ADV_SET_HANDLE_NOT_SET; //!< Advertising handle used to identify an advertising set.
  57. /**@brief Function for invoking registered callback.
  58. *
  59. * @param[in] evt Event to issue to callback.
  60. */
  61. static void handle_evt(nrf_ble_es_evt_t evt)
  62. {
  63. if (m_evt_handler != NULL)
  64. {
  65. m_evt_handler(evt);
  66. }
  67. }
  68. /**@brief Function resetting MAC address. Will resume advertisement. */
  69. static void new_address_set(void)
  70. {
  71. ret_code_t err_code;
  72. uint8_t bytes_available;
  73. ble_gap_addr_t new_address;
  74. new_address.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC;
  75. // Randomize the MAC address on every EID generation
  76. (void)sd_rand_application_bytes_available_get(&bytes_available);
  77. while (bytes_available < BLE_GAP_ADDR_LEN)
  78. {
  79. // wait for SD to acquire enough RNs
  80. (void)sd_rand_application_bytes_available_get(&bytes_available);
  81. }
  82. (void)sd_rand_application_vector_get(new_address.addr, BLE_GAP_ADDR_LEN);
  83. // Stop advertising to ensure that it is possible to change the address.
  84. (void)sd_ble_gap_adv_stop(m_adv_handle);
  85. do
  86. {
  87. err_code = sd_ble_gap_addr_set(&new_address);
  88. } while (err_code == NRF_ERROR_INVALID_STATE);
  89. APP_ERROR_CHECK(err_code);
  90. if (es_adv_remain_connectable_get())
  91. {
  92. es_adv_start_connectable_adv();
  93. }
  94. else
  95. {
  96. es_adv_start_non_connctable_adv();
  97. }
  98. }
  99. /**@brief Function updating MAC address if required.
  100. *
  101. * @param[in] demand_new_mac If 'true', mac address will be updated on next invocation when not connected.
  102. * If 'false', simply check if we have an outstanding demand for new MAC and update if not connected.
  103. */
  104. static void check_and_update_mac_address(bool demand_new_mac)
  105. {
  106. static bool reset_mac_address = false;
  107. if (demand_new_mac)
  108. {
  109. reset_mac_address = true;
  110. }
  111. // Not possible to update MAC address while in a connection
  112. if (m_conn_handle != BLE_CONN_HANDLE_INVALID)
  113. {
  114. return;
  115. }
  116. else if (reset_mac_address)
  117. {
  118. reset_mac_address = false;
  119. new_address_set();
  120. }
  121. }
  122. /**@brief Function to lock the beacon (change lock state characteristic to LOCKED)
  123. */
  124. static void lock_beacon(void)
  125. {
  126. m_ble_ecs.lock_state = NRF_BLE_ESCS_LOCK_STATE_LOCKED;
  127. }
  128. /**@brief Function for handling BLE event from the SoftDevice.
  129. *
  130. * @param[in] p_ble_evt Pointer to BLE event.
  131. */
  132. static void on_ble_evt(ble_evt_t const * p_ble_evt)
  133. {
  134. ret_code_t err_code;
  135. es_flash_flags_t flash_flag = {{0}};
  136. const es_slot_reg_t * p_reg = es_slot_get_registry();
  137. switch (p_ble_evt->header.evt_id)
  138. {
  139. case BLE_GAP_EVT_CONNECTED:
  140. m_conn_handle = p_ble_evt->evt.common_evt.conn_handle;
  141. *(m_ble_ecs.p_active_slot) = 0;
  142. break;
  143. case BLE_GAP_EVT_DISCONNECTED:
  144. m_conn_handle = BLE_CONN_HANDLE_INVALID;
  145. for (uint32_t i = 0; i < APP_MAX_ADV_SLOTS; ++i)
  146. {
  147. err_code = es_slot_write_to_flash(i);
  148. APP_ERROR_CHECK(err_code);
  149. flash_flag.slot_is_empty[i] = !p_reg->slots[i].configured;
  150. }
  151. err_code = es_flash_access_flags(&flash_flag, ES_FLASH_ACCESS_WRITE);
  152. APP_ERROR_CHECK(err_code);
  153. es_flash_beacon_config_t beacon_config;
  154. beacon_config.adv_interval = es_adv_interval_get();
  155. beacon_config.remain_connectable = es_adv_remain_connectable_get();
  156. err_code = es_flash_access_beacon_config(&beacon_config, ES_FLASH_ACCESS_WRITE);
  157. APP_ERROR_CHECK(err_code);
  158. if (m_ble_ecs.lock_state == NRF_BLE_ESCS_LOCK_STATE_UNLOCKED)
  159. {
  160. lock_beacon();
  161. }
  162. check_and_update_mac_address(false);
  163. break;
  164. default:
  165. // No implementation needed.
  166. break;
  167. }
  168. }
  169. /**@brief Callback function to receive messages from the security module
  170. *
  171. * @details Need to be passed in during es_security_init(). The security
  172. * module will callback anytime a particular security process is completed
  173. *
  174. * @params[in] slot_no Index of the slot
  175. * @params[in] msg_type Message type corersponding to different security components
  176. */
  177. static void nrf_ble_escs_security_cb(uint8_t slot_no, es_security_msg_t msg_type)
  178. {
  179. nrf_ble_escs_eid_id_key_t encrypted_id_key;
  180. nrf_ble_escs_public_ecdh_key_t pub_ecdh_key;
  181. ret_code_t err_code;
  182. static ble_gatts_value_t value;
  183. switch (msg_type)
  184. {
  185. case ES_SECURITY_MSG_UNLOCKED:
  186. m_ble_ecs.lock_state = NRF_BLE_ESCS_LOCK_STATE_UNLOCKED;
  187. break;
  188. case ES_SECURITY_MSG_EID:
  189. es_slot_eid_ready(slot_no);
  190. #ifdef MAC_RANDOMIZED
  191. check_and_update_mac_address(true);
  192. #endif // MAC_RANDOMIZED
  193. break;
  194. case ES_SECURITY_MSG_IK:
  195. es_security_encrypted_eid_id_key_get(slot_no, (uint8_t *)encrypted_id_key.key);
  196. // Set the EID ID key in the slot so it can be exposed in the characteristic
  197. es_slot_encrypted_eid_id_key_set(slot_no, &encrypted_id_key);
  198. break;
  199. case ES_SECURITY_MSG_ECDH:
  200. es_security_pub_ecdh_get(slot_no, (uint8_t *)pub_ecdh_key.key);
  201. // Set the characteristic to the ECDH key value
  202. value.len = sizeof(nrf_ble_escs_public_ecdh_key_t);
  203. value.offset = 0;
  204. value.p_value = (uint8_t *)pub_ecdh_key.key;
  205. if (m_conn_handle != BLE_CONN_HANDLE_INVALID)
  206. {
  207. err_code = sd_ble_gatts_value_set(m_ble_ecs.conn_handle,
  208. m_ble_ecs.pub_ecdh_key_handles.value_handle,
  209. &value);
  210. if (err_code != NRF_SUCCESS)
  211. {
  212. APP_ERROR_CHECK(err_code);
  213. }
  214. }
  215. break;
  216. case ES_SECURITY_MSG_STORE_TIME:
  217. // Every 24 hours any EID slots time is stored to flash to allow for power lock_state_handles
  218. // recovery. Only time needs to be stored, but just store the entire slot anyway for API simplicity.
  219. err_code = es_slot_write_to_flash(slot_no);
  220. APP_ERROR_CHECK(err_code);
  221. break;
  222. default:
  223. APP_ERROR_CHECK(NRF_ERROR_INVALID_PARAM); // Should never happen
  224. break;
  225. }
  226. }
  227. /**@brief Function for handling advertisement events from 'es_adv'.
  228. *
  229. * @param[in] evt Advertisement event to handle.
  230. */
  231. static void adv_evt_handler(es_adv_evt_t evt)
  232. {
  233. switch (evt)
  234. {
  235. case ES_ADV_EVT_NON_CONN_ADV:
  236. handle_evt(NRF_BLE_ES_EVT_ADVERTISEMENT_SENT);
  237. es_security_update_time();
  238. break;
  239. case ES_ADV_EVT_CONNECTABLE_ADV_STARTED:
  240. handle_evt(NRF_BLE_ES_EVT_CONNECTABLE_ADV_STARTED);
  241. break;
  242. case ES_ADV_EVT_CONNECTABLE_ADV_STOPPED:
  243. handle_evt(NRF_BLE_ES_EVT_CONNECTABLE_ADV_STOPPED);
  244. break;
  245. default:
  246. break;
  247. }
  248. }
  249. /**@brief Initialize the ECS with initial values for the characteristics and other necessary modules */
  250. static void ble_escs_init(void)
  251. {
  252. ret_code_t err_code;
  253. nrf_ble_escs_init_t ecs_init;
  254. nrf_ble_escs_init_params_t init_params;
  255. int8_t tx_powers[ESCS_NUM_OF_SUPPORTED_TX_POWER] = ESCS_SUPPORTED_TX_POWER;
  256. /*Init the broadcast capabilities characteristic*/
  257. memset(&init_params.broadcast_cap, 0, sizeof(init_params.broadcast_cap));
  258. init_params.broadcast_cap.vers_byte = ES_SPEC_VERSION_BYTE;
  259. init_params.broadcast_cap.max_supp_total_slots = APP_MAX_ADV_SLOTS;
  260. init_params.broadcast_cap.max_supp_eid_slots = APP_MAX_EID_SLOTS;
  261. init_params.broadcast_cap.cap_bitfield = ( (APP_IS_VARIABLE_ADV_SUPPORTED << ESCS_BROADCAST_VAR_ADV_SUPPORTED_Pos)
  262. | (APP_IS_VARIABLE_TX_POWER_SUPPORTED << ESCS_BROADCAST_VAR_TX_POWER_SUPPORTED_Pos))
  263. & (ESCS_BROADCAST_VAR_RFU_MASK);
  264. init_params.broadcast_cap.supp_frame_types = ( (APP_IS_URL_SUPPORTED << ESCS_FRAME_TYPE_URL_SUPPORTED_Pos)
  265. | (APP_IS_UID_SUPPORTED << ESCS_FRAME_TYPE_UID_SUPPORTED_Pos)
  266. | (APP_IS_TLM_SUPPORTED << ESCS_FRAME_TYPE_TLM_SUPPORTED_Pos)
  267. | (APP_IS_EID_SUPPORTED << ESCS_FRAME_TYPE_EID_SUPPORTED_Pos))
  268. & (ESCS_FRAME_TYPE_RFU_MASK);
  269. memcpy(init_params.broadcast_cap.supp_radio_tx_power, tx_powers, ESCS_NUM_OF_SUPPORTED_TX_POWER);
  270. init_params.adv_interval = APP_CFG_NON_CONN_ADV_INTERVAL_MS;
  271. init_params.adv_tx_pwr = APP_CFG_DEFAULT_RADIO_TX_POWER;
  272. init_params.radio_tx_pwr = 0x00;
  273. init_params.factory_reset = 0;
  274. init_params.remain_connectable.r_is_non_connectable_supported = APP_IS_REMAIN_CONNECTABLE_SUPPORTED;
  275. // Initialize evt handlers and the service
  276. memset(&ecs_init, 0, sizeof(ecs_init));
  277. ecs_init.write_evt_handler = es_gatts_handle_write;
  278. ecs_init.read_evt_handler = es_gatts_handle_read;
  279. ecs_init.p_init_vals = &(init_params);
  280. err_code = nrf_ble_escs_init(&m_ble_ecs, &ecs_init);
  281. APP_ERROR_CHECK(err_code);
  282. }
  283. /**@brief Function for initializing 'es_adv' module. */
  284. static void adv_init(void)
  285. {
  286. ret_code_t err_code;
  287. es_flash_beacon_config_t beacon_config;
  288. err_code = es_flash_access_beacon_config(&beacon_config, ES_FLASH_ACCESS_READ);
  289. if (err_code == FDS_ERR_NOT_FOUND)
  290. {
  291. beacon_config.adv_interval = APP_CFG_NON_CONN_ADV_INTERVAL_MS;
  292. beacon_config.remain_connectable = false;
  293. }
  294. else
  295. {
  296. APP_ERROR_CHECK(err_code);
  297. }
  298. es_adv_init(m_ble_ecs.uuid_type,
  299. adv_evt_handler,
  300. beacon_config.adv_interval,
  301. beacon_config.remain_connectable,
  302. &m_adv_handle);
  303. }
  304. /**@brief Function for initializing es_slots module. */
  305. static void adv_slots_init(void)
  306. {
  307. uint8_t default_frame_data[DEFAULT_FRAME_LENGTH] = DEFAULT_FRAME_DATA;
  308. es_slot_t default_adv_slot = {.slot_no = 0,
  309. .radio_tx_pwr = DEFAULT_FRAME_TX_POWER,
  310. .adv_frame.type = DEFAULT_FRAME_TYPE,
  311. .adv_frame.length = DEFAULT_FRAME_LENGTH,
  312. .adv_custom_tx_power = false,
  313. .configured = true};
  314. memcpy(&default_adv_slot.adv_frame.frame, default_frame_data, DEFAULT_FRAME_LENGTH);
  315. es_slots_init(&default_adv_slot);
  316. }
  317. void nrf_ble_es_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_context)
  318. {
  319. ret_code_t err_code;
  320. es_adv_on_ble_evt(p_ble_evt);
  321. err_code = nrf_ble_escs_on_ble_evt(&m_ble_ecs, p_ble_evt);
  322. APP_ERROR_CHECK(err_code);
  323. on_ble_evt(p_ble_evt);
  324. es_flash_on_ble_evt(p_ble_evt);
  325. }
  326. NRF_SDH_BLE_OBSERVER(m_es_observer, NRF_BLE_ES_BLE_OBSERVER_PRIO, nrf_ble_es_on_ble_evt, NULL);
  327. void nrf_ble_es_on_start_connectable_advertising(void)
  328. {
  329. es_adv_start_connectable_adv();
  330. }
  331. void nrf_ble_es_init(nrf_ble_es_evt_handler_t evt_handler)
  332. {
  333. ret_code_t err_code;
  334. m_evt_handler = evt_handler;
  335. m_conn_handle = BLE_CONN_HANDLE_INVALID;
  336. es_stopwatch_init();
  337. err_code = es_gatts_init(&m_ble_ecs);
  338. APP_ERROR_CHECK(err_code);
  339. err_code = es_flash_init();
  340. APP_ERROR_CHECK(err_code);
  341. while (es_flash_num_pending_ops() > 0)
  342. {
  343. ; // Busy wait while initialization of FDS module completes
  344. }
  345. err_code = es_security_init(nrf_ble_escs_security_cb);
  346. APP_ERROR_CHECK(err_code);
  347. es_adv_timers_init();
  348. ble_escs_init();
  349. adv_slots_init();
  350. es_battery_voltage_init();
  351. adv_init();
  352. es_adv_start_non_connctable_adv();
  353. }