ble_cts_c.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /**
  2. * Copyright (c) 2012 - 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 "sdk_common.h"
  41. #if NRF_MODULE_ENABLED(BLE_CTS_C)
  42. #include <string.h>
  43. #include "ble.h"
  44. #include "ble_srv_common.h"
  45. #include "ble_gattc.h"
  46. #include "ble_cts_c.h"
  47. #include "ble_date_time.h"
  48. #include "ble_db_discovery.h"
  49. #define NRF_LOG_MODULE_NAME ble_cts_c
  50. #include "nrf_log.h"
  51. NRF_LOG_MODULE_REGISTER();
  52. #define CTS_YEAR_MIN 1582 /**< The lowest valid Current Time year is the year when the Western calendar was introduced. */
  53. #define CTS_YEAR_MAX 9999 /**< The highest possible Current Time year. */
  54. #define CTS_C_CURRENT_TIME_EXPECTED_LENGTH 10 /**< | Year |Month |Day |Hours |Minutes |Seconds |Weekday |Fraction|Reason |
  55. | 2 bytes |1 byte |1 byte |1 byte |1 byte |1 byte |1 byte |1 byte |1 byte | = 10 bytes. */
  56. /**@brief Function for intercepting errors of GATTC and the BLE GATT Queue.
  57. *
  58. * @param[in] nrf_error Error code.
  59. * @param[in] p_ctx Parameter from the event handler.
  60. * @param[in] conn_handle Connection handle.
  61. */
  62. static void gatt_error_handler(uint32_t nrf_error,
  63. void * p_ctx,
  64. uint16_t conn_handle)
  65. {
  66. ble_cts_c_t * p_cts = (ble_cts_c_t *)p_ctx;
  67. NRF_LOG_DEBUG("A GATT Client error has occurred on conn_handle: 0X%X", conn_handle);
  68. if (p_cts->error_handler != NULL)
  69. {
  70. p_cts->error_handler(nrf_error);
  71. }
  72. }
  73. /**@brief Function for handling events from the Database Discovery module.
  74. *
  75. * @details This function handles an event from the Database Discovery module, and determines
  76. * whether it relates to the discovery of Current Time Service at the peer. If it does, this function
  77. * calls the application's event handler to indicate that the Current Time Service was
  78. * discovered at the peer. The function also populates the event with service-related
  79. * information before providing it to the application.
  80. *
  81. * @param[in] p_evt Pointer to the event received from the Database Discovery module.
  82. *
  83. */
  84. void ble_cts_c_on_db_disc_evt(ble_cts_c_t * p_cts, ble_db_discovery_evt_t * p_evt)
  85. {
  86. NRF_LOG_DEBUG("Database Discovery handler called with event 0x%x", p_evt->evt_type);
  87. ble_cts_c_evt_t evt;
  88. const ble_gatt_db_char_t * p_chars = p_evt->params.discovered_db.charateristics;
  89. evt.conn_handle = p_evt->conn_handle;
  90. // Check if the Current Time Service was discovered.
  91. if ( (p_evt->evt_type == BLE_DB_DISCOVERY_COMPLETE)
  92. && (p_evt->params.discovered_db.srv_uuid.uuid == BLE_UUID_CURRENT_TIME_SERVICE)
  93. && (p_evt->params.discovered_db.srv_uuid.type == BLE_UUID_TYPE_BLE))
  94. {
  95. // Find the handles of the Current Time characteristic.
  96. for (uint32_t i = 0; i < p_evt->params.discovered_db.char_count; i++)
  97. {
  98. if (p_evt->params.discovered_db.charateristics[i].characteristic.uuid.uuid ==
  99. BLE_UUID_CURRENT_TIME_CHAR)
  100. {
  101. // Found Current Time characteristic. Store CCCD and value handle and break.
  102. evt.params.char_handles.cts_handle = p_chars->characteristic.handle_value;
  103. evt.params.char_handles.cts_cccd_handle = p_chars->cccd_handle;
  104. break;
  105. }
  106. }
  107. NRF_LOG_INFO("Current Time Service discovered at peer.");
  108. evt.evt_type = BLE_CTS_C_EVT_DISCOVERY_COMPLETE;
  109. }
  110. else if ((p_evt->evt_type == BLE_DB_DISCOVERY_SRV_NOT_FOUND) ||
  111. (p_evt->evt_type == BLE_DB_DISCOVERY_ERROR))
  112. {
  113. evt.evt_type = BLE_CTS_C_EVT_DISCOVERY_FAILED;
  114. }
  115. else
  116. {
  117. return;
  118. }
  119. p_cts->evt_handler(p_cts, &evt);
  120. }
  121. uint32_t ble_cts_c_init(ble_cts_c_t * p_cts, ble_cts_c_init_t const * p_cts_init)
  122. {
  123. // Verify that the parameters needed to initialize this instance of CTS are not NULL.
  124. VERIFY_PARAM_NOT_NULL(p_cts);
  125. VERIFY_PARAM_NOT_NULL(p_cts_init);
  126. VERIFY_PARAM_NOT_NULL(p_cts_init->error_handler);
  127. VERIFY_PARAM_NOT_NULL(p_cts_init->evt_handler);
  128. VERIFY_PARAM_NOT_NULL(p_cts_init->p_gatt_queue);
  129. static ble_uuid_t cts_uuid;
  130. BLE_UUID_BLE_ASSIGN(cts_uuid, BLE_UUID_CURRENT_TIME_SERVICE);
  131. p_cts->evt_handler = p_cts_init->evt_handler;
  132. p_cts->error_handler = p_cts_init->error_handler;
  133. p_cts->conn_handle = BLE_CONN_HANDLE_INVALID;
  134. p_cts->char_handles.cts_handle = BLE_GATT_HANDLE_INVALID;
  135. p_cts->char_handles.cts_cccd_handle = BLE_GATT_HANDLE_INVALID;
  136. p_cts->p_gatt_queue = p_cts_init->p_gatt_queue;
  137. return ble_db_discovery_evt_register(&cts_uuid);
  138. }
  139. /**@brief Function for decoding a read from the Current Time characteristic.
  140. *
  141. * @param[in] p_time Current Time structure.
  142. * @param[in] p_data Pointer to the buffer containing the Current Time.
  143. * @param[in] length Length of the buffer containing the Current Time.
  144. *
  145. * @retval NRF_SUCCESS If the time struct is valid.
  146. * @retval NRF_ERROR_DATA_SIZE If the length does not match the expected size of the data.
  147. */
  148. static uint32_t current_time_decode(current_time_char_t * p_time,
  149. uint8_t const * p_data,
  150. uint32_t const length)
  151. {
  152. //lint -save -e415 -e416 "Access of out of bounds pointer" "Creation of out of bounds pointer"
  153. if (length != CTS_C_CURRENT_TIME_EXPECTED_LENGTH)
  154. {
  155. // Return to prevent accessing the out-of-bounds data.
  156. return NRF_ERROR_DATA_SIZE;
  157. }
  158. NRF_LOG_DEBUG("Current Time read response data:");
  159. NRF_LOG_HEXDUMP_DEBUG(p_data, 10);
  160. uint32_t index = 0;
  161. // Date.
  162. index += ble_date_time_decode(&p_time->exact_time_256.day_date_time.date_time, p_data);
  163. // Day of week.
  164. p_time->exact_time_256.day_date_time.day_of_week = p_data[index++];
  165. // Fractions of a second.
  166. p_time->exact_time_256.fractions256 = p_data[index++];
  167. // Reason for updating the time.
  168. p_time->adjust_reason.manual_time_update = (p_data[index] >> 0) & 0x01;
  169. p_time->adjust_reason.external_reference_time_update = (p_data[index] >> 1) & 0x01;
  170. p_time->adjust_reason.change_of_time_zone = (p_data[index] >> 2) & 0x01;
  171. p_time->adjust_reason.change_of_daylight_savings_time = (p_data[index] >> 3) & 0x01;
  172. //lint -restore
  173. return NRF_SUCCESS;
  174. }
  175. /**@brief Function for decoding a read from the Current Time characteristic.
  176. *
  177. * @param[in] p_time Current Time struct.
  178. *
  179. * @retval NRF_SUCCESS If the time struct is valid.
  180. * @retval NRF_ERROR_INVALID_DATA If the time is out of bounds.
  181. */
  182. static uint32_t current_time_validate(current_time_char_t * p_time)
  183. {
  184. // Year.
  185. if ( (p_time->exact_time_256.day_date_time.date_time.year > CTS_YEAR_MAX)
  186. || ((p_time->exact_time_256.day_date_time.date_time.year < CTS_YEAR_MIN)
  187. && (p_time->exact_time_256.day_date_time.date_time.year != 0)))
  188. {
  189. return NRF_ERROR_INVALID_DATA;
  190. }
  191. // Month.
  192. if (p_time->exact_time_256.day_date_time.date_time.month > 12)
  193. {
  194. return NRF_ERROR_INVALID_DATA;
  195. }
  196. // Day.
  197. if (p_time->exact_time_256.day_date_time.date_time.day > 31)
  198. {
  199. return NRF_ERROR_INVALID_DATA;
  200. }
  201. // Hours.
  202. if (p_time->exact_time_256.day_date_time.date_time.hours > 23)
  203. {
  204. return NRF_ERROR_INVALID_DATA;
  205. }
  206. // Minutes.
  207. if (p_time->exact_time_256.day_date_time.date_time.minutes > 59)
  208. {
  209. return NRF_ERROR_INVALID_DATA;
  210. }
  211. // Seconds.
  212. if (p_time->exact_time_256.day_date_time.date_time.seconds > 59)
  213. {
  214. return NRF_ERROR_INVALID_DATA;
  215. }
  216. // Day of week.
  217. if (p_time->exact_time_256.day_date_time.day_of_week > 7)
  218. {
  219. return NRF_ERROR_INVALID_DATA;
  220. }
  221. return NRF_SUCCESS;
  222. }
  223. /**@brief Function for reading the Current Time. The time is decoded, and then validated.
  224. * Depending on the outcome, the CTS event handler will be called with
  225. * the Current Time event or an invalid time event.
  226. *
  227. * @param[in] p_cts Current Time Service client structure.
  228. * @param[in] p_ble_evt Event received from the BLE stack.
  229. */
  230. static void current_time_read(ble_cts_c_t * p_cts, ble_evt_t const * p_ble_evt)
  231. {
  232. ble_cts_c_evt_t evt;
  233. uint32_t err_code = NRF_SUCCESS;
  234. // Check whether the event is on the same connection as this CTS instance
  235. if (p_cts->conn_handle != p_ble_evt->evt.gattc_evt.conn_handle)
  236. {
  237. return;
  238. }
  239. if (p_ble_evt->evt.gattc_evt.gatt_status == BLE_GATT_STATUS_SUCCESS)
  240. {
  241. err_code = current_time_decode(&evt.params.current_time,
  242. p_ble_evt->evt.gattc_evt.params.read_rsp.data,
  243. p_ble_evt->evt.gattc_evt.params.read_rsp.len);
  244. if (err_code != NRF_SUCCESS)
  245. {
  246. // The data length was invalid. Decoding was not completed.
  247. evt.evt_type = BLE_CTS_C_EVT_INVALID_TIME;
  248. }
  249. else
  250. {
  251. // Verify that the time is valid.
  252. err_code = current_time_validate(&evt.params.current_time);
  253. if (err_code != NRF_SUCCESS)
  254. {
  255. // Invalid time received.
  256. evt.evt_type = BLE_CTS_C_EVT_INVALID_TIME;
  257. }
  258. else
  259. {
  260. // Valid time reveiced.
  261. evt.evt_type = BLE_CTS_C_EVT_CURRENT_TIME;
  262. }
  263. }
  264. p_cts->evt_handler(p_cts, &evt);
  265. }
  266. }
  267. /**@brief Function for handling the Disconnect event.
  268. *
  269. * @param[in] p_cts Current Time Service client structure.
  270. * @param[in] p_ble_evt Event received from the BLE stack.
  271. */
  272. static void on_disconnect(ble_cts_c_t * p_cts, ble_evt_t const * p_ble_evt)
  273. {
  274. if (p_cts->conn_handle == p_ble_evt->evt.gap_evt.conn_handle)
  275. {
  276. p_cts->conn_handle = BLE_CONN_HANDLE_INVALID;
  277. }
  278. if (ble_cts_c_is_cts_discovered(p_cts))
  279. {
  280. // There was a valid instance of CTS on the peer. Send an event to the
  281. // application, so that it can do any clean up related to this module.
  282. ble_cts_c_evt_t evt;
  283. evt.evt_type = BLE_CTS_C_EVT_DISCONN_COMPLETE;
  284. p_cts->evt_handler(p_cts, &evt);
  285. p_cts->char_handles.cts_handle = BLE_GATT_HANDLE_INVALID;
  286. p_cts->char_handles.cts_cccd_handle = BLE_GATT_HANDLE_INVALID;
  287. }
  288. }
  289. void ble_cts_c_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_context)
  290. {
  291. ble_cts_c_t * p_cts = (ble_cts_c_t *)p_context;
  292. NRF_LOG_DEBUG("BLE event handler called with event 0x%x", p_ble_evt->header.evt_id);
  293. switch (p_ble_evt->header.evt_id)
  294. {
  295. case BLE_GATTC_EVT_READ_RSP:
  296. current_time_read(p_cts, p_ble_evt);
  297. break;
  298. case BLE_GAP_EVT_DISCONNECTED:
  299. on_disconnect(p_cts, p_ble_evt);
  300. break;
  301. default:
  302. // No implementation needed.
  303. break;
  304. }
  305. }
  306. uint32_t ble_cts_c_current_time_read(ble_cts_c_t const * p_cts)
  307. {
  308. if (!ble_cts_c_is_cts_discovered(p_cts))
  309. {
  310. return NRF_ERROR_NOT_FOUND;
  311. }
  312. nrf_ble_gq_req_t read_req;
  313. memset(&read_req, 0, sizeof(nrf_ble_gq_req_t));
  314. read_req.type = NRF_BLE_GQ_REQ_GATTC_READ;
  315. read_req.error_handler.cb = gatt_error_handler;
  316. read_req.error_handler.p_ctx = (ble_cts_c_t *)p_cts;
  317. read_req.params.gattc_read.handle = p_cts->char_handles.cts_handle;
  318. read_req.params.gattc_read.offset = 0;
  319. return nrf_ble_gq_item_add(p_cts->p_gatt_queue, &read_req, p_cts->conn_handle);
  320. }
  321. uint32_t ble_cts_c_handles_assign(ble_cts_c_t * p_cts,
  322. const uint16_t conn_handle,
  323. const ble_cts_c_handles_t * p_peer_handles)
  324. {
  325. VERIFY_PARAM_NOT_NULL(p_cts);
  326. p_cts->conn_handle = conn_handle;
  327. if (p_peer_handles != NULL)
  328. {
  329. p_cts->char_handles.cts_cccd_handle = p_peer_handles->cts_cccd_handle;
  330. p_cts->char_handles.cts_handle = p_peer_handles->cts_handle;
  331. }
  332. return nrf_ble_gq_conn_handle_register(p_cts->p_gatt_queue, conn_handle);
  333. }
  334. #endif // NRF_MODULE_ENABLED(BLE_CTS_C)