ble_drv.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2016 - 2018 Glenn Ruben Bakke
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #if BLUETOOTH_SD
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include <stdbool.h>
  30. #include "py/runtime.h"
  31. #include "ble_drv.h"
  32. #include "mpconfigport.h"
  33. #include "nrf_sdm.h"
  34. #include "ble_gap.h"
  35. #include "ble.h" // sd_ble_uuid_encode
  36. #include "drivers/flash.h"
  37. #include "mphalport.h"
  38. #define BLE_DRIVER_VERBOSE 0
  39. #if BLE_DRIVER_VERBOSE
  40. #define BLE_DRIVER_LOG printf
  41. #else
  42. #define BLE_DRIVER_LOG(...)
  43. #endif
  44. #define BLE_ADV_LENGTH_FIELD_SIZE 1
  45. #define BLE_ADV_AD_TYPE_FIELD_SIZE 1
  46. #define BLE_AD_TYPE_FLAGS_DATA_SIZE 1
  47. #define MSEC_TO_UNITS(TIME, RESOLUTION) (((TIME) * 1000) / (RESOLUTION))
  48. #define UNIT_0_625_MS (625)
  49. #define UNIT_10_MS (10000)
  50. #define APP_CFG_NON_CONN_ADV_TIMEOUT 0 // Disable timeout.
  51. #define NON_CONNECTABLE_ADV_INTERVAL MSEC_TO_UNITS(100, UNIT_0_625_MS)
  52. #define BLE_MIN_CONN_INTERVAL MSEC_TO_UNITS(12, UNIT_0_625_MS)
  53. #define BLE_MAX_CONN_INTERVAL MSEC_TO_UNITS(12, UNIT_0_625_MS)
  54. #define BLE_SLAVE_LATENCY 0
  55. #define BLE_CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS)
  56. #if (BLUETOOTH_SD == 110)
  57. #define MAX_TX_IN_PROGRESS (6)
  58. #else
  59. #define MAX_TX_IN_PROGRESS (10)
  60. #endif
  61. #if !defined(GATT_MTU_SIZE_DEFAULT) && defined(BLE_GATT_ATT_MTU_DEFAULT)
  62. #define GATT_MTU_SIZE_DEFAULT BLE_GATT_ATT_MTU_DEFAULT
  63. #endif
  64. #define SD_TEST_OR_ENABLE() \
  65. if (ble_drv_stack_enabled() == 0) { \
  66. (void)ble_drv_stack_enable(); \
  67. }
  68. static volatile bool m_adv_in_progress;
  69. static volatile uint8_t m_tx_in_progress;
  70. static ble_drv_gap_evt_callback_t gap_event_handler;
  71. static ble_drv_gatts_evt_callback_t gatts_event_handler;
  72. static mp_obj_t mp_gap_observer;
  73. static mp_obj_t mp_gatts_observer;
  74. #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  75. static volatile bool m_primary_service_found;
  76. static volatile bool m_characteristic_found;
  77. static volatile bool m_write_done;
  78. static volatile ble_drv_adv_evt_callback_t adv_event_handler;
  79. static volatile ble_drv_gattc_evt_callback_t gattc_event_handler;
  80. static volatile ble_drv_disc_add_service_callback_t disc_add_service_handler;
  81. static volatile ble_drv_disc_add_char_callback_t disc_add_char_handler;
  82. static volatile ble_drv_gattc_char_data_callback_t gattc_char_data_handle;
  83. static mp_obj_t mp_adv_observer;
  84. static mp_obj_t mp_gattc_observer;
  85. static mp_obj_t mp_gattc_disc_service_observer;
  86. static mp_obj_t mp_gattc_disc_char_observer;
  87. static mp_obj_t mp_gattc_char_data_observer;
  88. #endif
  89. #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  90. #include "nrf_nvic.h"
  91. #define BLE_GAP_ADV_MAX_SIZE BLE_GATT_ATT_MTU_DEFAULT
  92. #define BLE_DRV_CONN_CONFIG_TAG 1
  93. static uint8_t m_adv_handle;
  94. static uint8_t m_scan_buffer[BLE_GAP_SCAN_BUFFER_MIN];
  95. nrf_nvic_state_t nrf_nvic_state = {0};
  96. #endif
  97. #if (BLUETOOTH_SD == 110)
  98. void softdevice_assert_handler(uint32_t pc, uint16_t line_number, const uint8_t * p_file_name) {
  99. BLE_DRIVER_LOG("ERROR: SoftDevice assert!!!");
  100. }
  101. #else
  102. void softdevice_assert_handler(uint32_t id, uint32_t pc, uint32_t info) {
  103. BLE_DRIVER_LOG("ERROR: SoftDevice assert!!!");
  104. }
  105. #endif
  106. uint32_t ble_drv_stack_enable(void) {
  107. m_adv_in_progress = false;
  108. m_tx_in_progress = 0;
  109. #if (BLUETOOTH_SD == 110)
  110. #if BLUETOOTH_LFCLK_RC
  111. uint32_t err_code = sd_softdevice_enable(NRF_CLOCK_LFCLKSRC_RC_250_PPM_250MS_CALIBRATION,
  112. softdevice_assert_handler);
  113. #else
  114. uint32_t err_code = sd_softdevice_enable(NRF_CLOCK_LFCLKSRC_XTAL_20_PPM,
  115. softdevice_assert_handler);
  116. #endif // BLUETOOTH_LFCLK_RC
  117. #endif // (BLUETOOTH_SD == 110)
  118. #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  119. #if BLUETOOTH_LFCLK_RC
  120. nrf_clock_lf_cfg_t clock_config = {
  121. .source = NRF_CLOCK_LF_SRC_RC,
  122. .rc_ctiv = 16,
  123. .rc_temp_ctiv = 2,
  124. .accuracy = NRF_CLOCK_LF_ACCURACY_250_PPM
  125. };
  126. #else
  127. nrf_clock_lf_cfg_t clock_config = {
  128. .source = NRF_CLOCK_LF_SRC_XTAL,
  129. .rc_ctiv = 0,
  130. .rc_temp_ctiv = 0,
  131. .accuracy = NRF_CLOCK_LF_ACCURACY_20_PPM
  132. };
  133. #endif // BLUETOOTH_LFCLK_RC
  134. uint32_t err_code = sd_softdevice_enable(&clock_config,
  135. softdevice_assert_handler);
  136. #endif // (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  137. BLE_DRIVER_LOG("SoftDevice enable status: " UINT_FMT "\n", (uint16_t)err_code);
  138. err_code = sd_nvic_EnableIRQ(SD_EVT_IRQn);
  139. BLE_DRIVER_LOG("IRQ enable status: " UINT_FMT "\n", (uint16_t)err_code);
  140. #if (BLUETOOTH_SD == 110)
  141. ble_enable_params_t ble_enable_params;
  142. memset(&ble_enable_params, 0x00, sizeof(ble_enable_params));
  143. ble_enable_params.gatts_enable_params.attr_tab_size = BLE_GATTS_ATTR_TAB_SIZE_DEFAULT;
  144. ble_enable_params.gatts_enable_params.service_changed = 0;
  145. #else
  146. ble_cfg_t ble_conf;
  147. uint32_t app_ram_start_cfg = 0x200039c0;
  148. ble_conf.conn_cfg.conn_cfg_tag = BLE_DRV_CONN_CONFIG_TAG;
  149. ble_conf.conn_cfg.params.gap_conn_cfg.conn_count = 2;
  150. ble_conf.conn_cfg.params.gap_conn_cfg.event_length = 3;
  151. err_code = sd_ble_cfg_set(BLE_CONN_CFG_GAP, &ble_conf, app_ram_start_cfg);
  152. BLE_DRIVER_LOG("BLE_CONN_CFG_GAP status: " UINT_FMT "\n", (uint16_t)err_code);
  153. memset(&ble_conf, 0, sizeof(ble_conf));
  154. ble_conf.gap_cfg.role_count_cfg.periph_role_count = 1;
  155. ble_conf.gap_cfg.role_count_cfg.central_role_count = 1;
  156. ble_conf.gap_cfg.role_count_cfg.central_sec_count = 0;
  157. err_code = sd_ble_cfg_set(BLE_GAP_CFG_ROLE_COUNT, &ble_conf, app_ram_start_cfg);
  158. BLE_DRIVER_LOG("BLE_GAP_CFG_ROLE_COUNT status: " UINT_FMT "\n", (uint16_t)err_code);
  159. memset(&ble_conf, 0, sizeof(ble_conf));
  160. ble_conf.conn_cfg.conn_cfg_tag = BLE_DRV_CONN_CONFIG_TAG;
  161. ble_conf.conn_cfg.params.gatts_conn_cfg.hvn_tx_queue_size = MAX_TX_IN_PROGRESS;
  162. err_code = sd_ble_cfg_set(BLE_CONN_CFG_GATTS, &ble_conf, app_ram_start_cfg);
  163. BLE_DRIVER_LOG("BLE_CONN_CFG_GATTS status: " UINT_FMT "\n", (uint16_t)err_code);
  164. #endif
  165. #if (BLUETOOTH_SD == 110)
  166. err_code = sd_ble_enable(&ble_enable_params);
  167. #else
  168. uint32_t app_ram_start = 0x200039c0;
  169. err_code = sd_ble_enable(&app_ram_start); // 8K SD headroom from linker script.
  170. BLE_DRIVER_LOG("BLE ram size: " UINT_FMT "\n", (uint16_t)app_ram_start);
  171. #endif
  172. BLE_DRIVER_LOG("BLE enable status: " UINT_FMT "\n", (uint16_t)err_code);
  173. // set up security mode
  174. ble_gap_conn_params_t gap_conn_params;
  175. ble_gap_conn_sec_mode_t sec_mode;
  176. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  177. const char device_name[] = "micr";
  178. if ((err_code = sd_ble_gap_device_name_set(&sec_mode,
  179. (const uint8_t *)device_name,
  180. strlen(device_name))) != 0) {
  181. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  182. "Cannot apply GAP parameters."));
  183. }
  184. // set connection parameters
  185. memset(&gap_conn_params, 0, sizeof(gap_conn_params));
  186. gap_conn_params.min_conn_interval = BLE_MIN_CONN_INTERVAL;
  187. gap_conn_params.max_conn_interval = BLE_MAX_CONN_INTERVAL;
  188. gap_conn_params.slave_latency = BLE_SLAVE_LATENCY;
  189. gap_conn_params.conn_sup_timeout = BLE_CONN_SUP_TIMEOUT;
  190. if (sd_ble_gap_ppcp_set(&gap_conn_params) != 0) {
  191. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  192. "Cannot set PPCP parameters."));
  193. }
  194. return err_code;
  195. }
  196. void ble_drv_stack_disable(void) {
  197. sd_softdevice_disable();
  198. }
  199. uint8_t ble_drv_stack_enabled(void) {
  200. uint8_t is_enabled;
  201. uint32_t err_code = sd_softdevice_is_enabled(&is_enabled);
  202. (void)err_code;
  203. BLE_DRIVER_LOG("Is enabled status: " UINT_FMT "\n", (uint16_t)err_code);
  204. return is_enabled;
  205. }
  206. void ble_drv_address_get(ble_drv_addr_t * p_addr) {
  207. SD_TEST_OR_ENABLE();
  208. ble_gap_addr_t local_ble_addr;
  209. #if (BLUETOOTH_SD == 110)
  210. uint32_t err_code = sd_ble_gap_address_get(&local_ble_addr);
  211. #else
  212. uint32_t err_code = sd_ble_gap_addr_get(&local_ble_addr);
  213. #endif
  214. if (err_code != 0) {
  215. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  216. "Can not query for the device address."));
  217. }
  218. BLE_DRIVER_LOG("ble address, type: " HEX2_FMT ", " \
  219. "address: " HEX2_FMT ":" HEX2_FMT ":" HEX2_FMT ":" \
  220. HEX2_FMT ":" HEX2_FMT ":" HEX2_FMT "\n", \
  221. local_ble_addr.addr_type, \
  222. local_ble_addr.addr[5], local_ble_addr.addr[4], local_ble_addr.addr[3], \
  223. local_ble_addr.addr[2], local_ble_addr.addr[1], local_ble_addr.addr[0]);
  224. p_addr->addr_type = local_ble_addr.addr_type;
  225. memcpy(p_addr->addr, local_ble_addr.addr, 6);
  226. }
  227. bool ble_drv_uuid_add_vs(uint8_t * p_uuid, uint8_t * idx) {
  228. SD_TEST_OR_ENABLE();
  229. if (sd_ble_uuid_vs_add((ble_uuid128_t const *)p_uuid, idx) != 0) {
  230. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  231. "Can not add Vendor Specific 128-bit UUID."));
  232. }
  233. return true;
  234. }
  235. bool ble_drv_service_add(ubluepy_service_obj_t * p_service_obj) {
  236. SD_TEST_OR_ENABLE();
  237. if (p_service_obj->p_uuid->type > BLE_UUID_TYPE_BLE) {
  238. ble_uuid_t uuid;
  239. uuid.type = p_service_obj->p_uuid->uuid_vs_idx;
  240. uuid.uuid = p_service_obj->p_uuid->value[0];
  241. uuid.uuid += p_service_obj->p_uuid->value[1] << 8;
  242. if (sd_ble_gatts_service_add(p_service_obj->type,
  243. &uuid,
  244. &p_service_obj->handle) != 0) {
  245. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  246. "Can not add Service."));
  247. }
  248. } else if (p_service_obj->p_uuid->type == BLE_UUID_TYPE_BLE) {
  249. BLE_DRIVER_LOG("adding service\n");
  250. ble_uuid_t uuid;
  251. uuid.type = p_service_obj->p_uuid->type;
  252. uuid.uuid = p_service_obj->p_uuid->value[0];
  253. uuid.uuid += p_service_obj->p_uuid->value[1] << 8;
  254. if (sd_ble_gatts_service_add(p_service_obj->type,
  255. &uuid,
  256. &p_service_obj->handle) != 0) {
  257. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  258. "Can not add Service."));
  259. }
  260. }
  261. return true;
  262. }
  263. bool ble_drv_characteristic_add(ubluepy_characteristic_obj_t * p_char_obj) {
  264. ble_gatts_char_md_t char_md;
  265. ble_gatts_attr_md_t cccd_md;
  266. ble_gatts_attr_t attr_char_value;
  267. ble_uuid_t uuid;
  268. ble_gatts_attr_md_t attr_md;
  269. memset(&char_md, 0, sizeof(char_md));
  270. char_md.char_props.broadcast = (p_char_obj->props & UBLUEPY_PROP_BROADCAST) ? 1 : 0;
  271. char_md.char_props.read = (p_char_obj->props & UBLUEPY_PROP_READ) ? 1 : 0;
  272. char_md.char_props.write_wo_resp = (p_char_obj->props & UBLUEPY_PROP_WRITE_WO_RESP) ? 1 : 0;
  273. char_md.char_props.write = (p_char_obj->props & UBLUEPY_PROP_WRITE) ? 1 : 0;
  274. char_md.char_props.notify = (p_char_obj->props & UBLUEPY_PROP_NOTIFY) ? 1 : 0;
  275. char_md.char_props.indicate = (p_char_obj->props & UBLUEPY_PROP_INDICATE) ? 1 : 0;
  276. #if 0
  277. char_md.char_props.auth_signed_wr = (p_char_obj->props & UBLUEPY_PROP_NOTIFY) ? 1 : 0;
  278. #endif
  279. char_md.p_char_user_desc = NULL;
  280. char_md.p_char_pf = NULL;
  281. char_md.p_user_desc_md = NULL;
  282. char_md.p_sccd_md = NULL;
  283. // if cccd
  284. if (p_char_obj->attrs & UBLUEPY_ATTR_CCCD) {
  285. memset(&cccd_md, 0, sizeof(cccd_md));
  286. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm);
  287. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm);
  288. cccd_md.vloc = BLE_GATTS_VLOC_STACK;
  289. char_md.p_cccd_md = &cccd_md;
  290. } else {
  291. char_md.p_cccd_md = NULL;
  292. }
  293. uuid.type = p_char_obj->p_uuid->type;
  294. uuid.uuid = p_char_obj->p_uuid->value[0];
  295. uuid.uuid += p_char_obj->p_uuid->value[1] << 8;
  296. memset(&attr_md, 0, sizeof(attr_md));
  297. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
  298. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
  299. attr_md.vloc = BLE_GATTS_VLOC_STACK;
  300. attr_md.rd_auth = 0;
  301. attr_md.wr_auth = 0;
  302. attr_md.vlen = 1;
  303. memset(&attr_char_value, 0, sizeof(attr_char_value));
  304. attr_char_value.p_uuid = &uuid;
  305. attr_char_value.p_attr_md = &attr_md;
  306. attr_char_value.init_len = sizeof(uint8_t);
  307. attr_char_value.init_offs = 0;
  308. attr_char_value.max_len = (GATT_MTU_SIZE_DEFAULT - 3);
  309. ble_gatts_char_handles_t handles;
  310. if (sd_ble_gatts_characteristic_add(p_char_obj->service_handle,
  311. &char_md,
  312. &attr_char_value,
  313. &handles) != 0) {
  314. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  315. "Can not add Characteristic."));
  316. }
  317. // apply handles to object instance
  318. p_char_obj->handle = handles.value_handle;
  319. p_char_obj->user_desc_handle = handles.user_desc_handle;
  320. p_char_obj->cccd_handle = handles.cccd_handle;
  321. p_char_obj->sccd_handle = handles.sccd_handle;
  322. return true;
  323. }
  324. bool ble_drv_advertise_data(ubluepy_advertise_data_t * p_adv_params) {
  325. SD_TEST_OR_ENABLE();
  326. uint8_t byte_pos = 0;
  327. uint8_t adv_data[BLE_GAP_ADV_MAX_SIZE];
  328. if (p_adv_params->device_name_len > 0) {
  329. ble_gap_conn_sec_mode_t sec_mode;
  330. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  331. if (sd_ble_gap_device_name_set(&sec_mode,
  332. p_adv_params->p_device_name,
  333. p_adv_params->device_name_len) != 0) {
  334. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  335. "Can not apply device name in the stack."));
  336. }
  337. BLE_DRIVER_LOG("Device name applied\n");
  338. adv_data[byte_pos] = (BLE_ADV_AD_TYPE_FIELD_SIZE + p_adv_params->device_name_len);
  339. byte_pos += BLE_ADV_LENGTH_FIELD_SIZE;
  340. adv_data[byte_pos] = BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME;
  341. byte_pos += BLE_ADV_AD_TYPE_FIELD_SIZE;
  342. memcpy(&adv_data[byte_pos], p_adv_params->p_device_name, p_adv_params->device_name_len);
  343. // increment position counter to see if it fits, and in case more content should
  344. // follow in this adv packet.
  345. byte_pos += p_adv_params->device_name_len;
  346. }
  347. // Add FLAGS only if manually controlled data has not been used.
  348. if (p_adv_params->data_len == 0) {
  349. // set flags, default to disc mode
  350. adv_data[byte_pos] = (BLE_ADV_AD_TYPE_FIELD_SIZE + BLE_AD_TYPE_FLAGS_DATA_SIZE);
  351. byte_pos += BLE_ADV_LENGTH_FIELD_SIZE;
  352. adv_data[byte_pos] = BLE_GAP_AD_TYPE_FLAGS;
  353. byte_pos += BLE_AD_TYPE_FLAGS_DATA_SIZE;
  354. adv_data[byte_pos] = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
  355. byte_pos += 1;
  356. }
  357. if (p_adv_params->num_of_services > 0) {
  358. bool type_16bit_present = false;
  359. bool type_128bit_present = false;
  360. for (uint8_t i = 0; i < p_adv_params->num_of_services; i++) {
  361. ubluepy_service_obj_t * p_service = (ubluepy_service_obj_t *)p_adv_params->p_services[i];
  362. if (p_service->p_uuid->type == UBLUEPY_UUID_16_BIT) {
  363. type_16bit_present = true;
  364. }
  365. if (p_service->p_uuid->type == UBLUEPY_UUID_128_BIT) {
  366. type_128bit_present = true;
  367. }
  368. }
  369. if (type_16bit_present) {
  370. uint8_t size_byte_pos = byte_pos;
  371. // skip length byte for now, apply total length post calculation
  372. byte_pos += BLE_ADV_LENGTH_FIELD_SIZE;
  373. adv_data[byte_pos] = BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE;
  374. byte_pos += BLE_ADV_AD_TYPE_FIELD_SIZE;
  375. uint8_t uuid_total_size = 0;
  376. uint8_t encoded_size = 0;
  377. for (uint8_t i = 0; i < p_adv_params->num_of_services; i++) {
  378. ubluepy_service_obj_t * p_service = (ubluepy_service_obj_t *)p_adv_params->p_services[i];
  379. ble_uuid_t uuid;
  380. uuid.type = p_service->p_uuid->type;
  381. uuid.uuid = p_service->p_uuid->value[0];
  382. uuid.uuid += p_service->p_uuid->value[1] << 8;
  383. // calculate total size of uuids
  384. if (sd_ble_uuid_encode(&uuid, &encoded_size, NULL) != 0) {
  385. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  386. "Can not encode UUID, to check length."));
  387. }
  388. // do encoding into the adv buffer
  389. if (sd_ble_uuid_encode(&uuid, &encoded_size, &adv_data[byte_pos]) != 0) {
  390. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  391. "Can encode UUID into the advertisment packet."));
  392. }
  393. BLE_DRIVER_LOG("encoded uuid for service %u: ", 0);
  394. for (uint8_t j = 0; j < encoded_size; j++) {
  395. BLE_DRIVER_LOG(HEX2_FMT " ", adv_data[byte_pos + j]);
  396. }
  397. BLE_DRIVER_LOG("\n");
  398. uuid_total_size += encoded_size; // size of entry
  399. byte_pos += encoded_size; // relative to adv data packet
  400. BLE_DRIVER_LOG("ADV: uuid size: %u, type: %u, uuid: %x%x, vs_idx: %u\n",
  401. encoded_size, p_service->p_uuid->type,
  402. p_service->p_uuid->value[1],
  403. p_service->p_uuid->value[0],
  404. p_service->p_uuid->uuid_vs_idx);
  405. }
  406. adv_data[size_byte_pos] = (BLE_ADV_AD_TYPE_FIELD_SIZE + uuid_total_size);
  407. }
  408. if (type_128bit_present) {
  409. uint8_t size_byte_pos = byte_pos;
  410. // skip length byte for now, apply total length post calculation
  411. byte_pos += BLE_ADV_LENGTH_FIELD_SIZE;
  412. adv_data[byte_pos] = BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE;
  413. byte_pos += BLE_ADV_AD_TYPE_FIELD_SIZE;
  414. uint8_t uuid_total_size = 0;
  415. uint8_t encoded_size = 0;
  416. for (uint8_t i = 0; i < p_adv_params->num_of_services; i++) {
  417. ubluepy_service_obj_t * p_service = (ubluepy_service_obj_t *)p_adv_params->p_services[i];
  418. ble_uuid_t uuid;
  419. uuid.type = p_service->p_uuid->uuid_vs_idx;
  420. uuid.uuid = p_service->p_uuid->value[0];
  421. uuid.uuid += p_service->p_uuid->value[1] << 8;
  422. // calculate total size of uuids
  423. if (sd_ble_uuid_encode(&uuid, &encoded_size, NULL) != 0) {
  424. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  425. "Can not encode UUID, to check length."));
  426. }
  427. // do encoding into the adv buffer
  428. if (sd_ble_uuid_encode(&uuid, &encoded_size, &adv_data[byte_pos]) != 0) {
  429. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  430. "Can encode UUID into the advertisment packet."));
  431. }
  432. BLE_DRIVER_LOG("encoded uuid for service %u: ", 0);
  433. for (uint8_t j = 0; j < encoded_size; j++) {
  434. BLE_DRIVER_LOG(HEX2_FMT " ", adv_data[byte_pos + j]);
  435. }
  436. BLE_DRIVER_LOG("\n");
  437. uuid_total_size += encoded_size; // size of entry
  438. byte_pos += encoded_size; // relative to adv data packet
  439. BLE_DRIVER_LOG("ADV: uuid size: %u, type: %x%x, uuid: %u, vs_idx: %u\n",
  440. encoded_size, p_service->p_uuid->type,
  441. p_service->p_uuid->value[1],
  442. p_service->p_uuid->value[0],
  443. p_service->p_uuid->uuid_vs_idx);
  444. }
  445. adv_data[size_byte_pos] = (BLE_ADV_AD_TYPE_FIELD_SIZE + uuid_total_size);
  446. }
  447. }
  448. if ((p_adv_params->data_len > 0) && (p_adv_params->p_data != NULL)) {
  449. if (p_adv_params->data_len + byte_pos > BLE_GAP_ADV_MAX_SIZE) {
  450. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  451. "Can not fit data into the advertisment packet."));
  452. }
  453. memcpy(adv_data, p_adv_params->p_data, p_adv_params->data_len);
  454. byte_pos += p_adv_params->data_len;
  455. }
  456. // scan response data not set
  457. uint32_t err_code;
  458. #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  459. const ble_gap_adv_data_t m_adv_data = {
  460. .adv_data.p_data = adv_data,
  461. .adv_data.len = byte_pos,
  462. .scan_rsp_data.p_data = NULL,
  463. .scan_rsp_data.len = 0
  464. };
  465. #endif
  466. static ble_gap_adv_params_t m_adv_params;
  467. memset(&m_adv_params, 0, sizeof(m_adv_params));
  468. // initialize advertising params
  469. if (p_adv_params->connectable) {
  470. #if (BLUETOOTH_SD == 110)
  471. m_adv_params.type = BLE_GAP_ADV_TYPE_ADV_IND;
  472. #else
  473. m_adv_params.properties.type = BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED;
  474. #endif
  475. } else {
  476. #if (BLUETOOTH_SD == 110)
  477. m_adv_params.type = BLE_GAP_ADV_TYPE_ADV_NONCONN_IND;
  478. #else
  479. m_adv_params.properties.type = BLE_GAP_ADV_TYPE_NONCONNECTABLE_SCANNABLE_UNDIRECTED;
  480. #endif
  481. }
  482. #if (BLUETOOTH_SD == 110)
  483. m_adv_params.fp = BLE_GAP_ADV_FP_ANY;
  484. m_adv_params.timeout = 0; // infinite advertisment
  485. #else
  486. m_adv_params.properties.anonymous = 0;
  487. m_adv_params.properties.include_tx_power = 0;
  488. m_adv_params.filter_policy = 0;
  489. m_adv_params.max_adv_evts = 0; // infinite advertisment
  490. m_adv_params.primary_phy = BLE_GAP_PHY_AUTO;
  491. m_adv_params.secondary_phy = BLE_GAP_PHY_AUTO;
  492. m_adv_params.scan_req_notification = 0; // Do not raise scan request notifications when scanned.
  493. #endif
  494. m_adv_params.p_peer_addr = NULL; // undirected advertisement
  495. m_adv_params.interval = MSEC_TO_UNITS(100, UNIT_0_625_MS); // approx 8 ms
  496. #if (BLUETOOTH_SD == 110)
  497. if ((err_code = sd_ble_gap_adv_data_set(adv_data, byte_pos, NULL, 0)) != 0) {
  498. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  499. "Can not apply advertisment data. status: 0x" HEX2_FMT, (uint16_t)err_code));
  500. }
  501. #else
  502. if ((err_code = sd_ble_gap_adv_set_configure(&m_adv_handle, &m_adv_data, &m_adv_params)) != 0) {
  503. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  504. "Can not apply advertisment data. status: 0x" HEX2_FMT, (uint16_t)err_code));
  505. }
  506. #endif
  507. BLE_DRIVER_LOG("Set Adv data size: " UINT_FMT "\n", byte_pos);
  508. ble_drv_advertise_stop();
  509. #if (BLUETOOTH_SD == 110)
  510. err_code = sd_ble_gap_adv_start(&m_adv_params);
  511. #else
  512. uint8_t conf_tag = BLE_DRV_CONN_CONFIG_TAG; // Could also be set to tag from sd_ble_cfg_set
  513. err_code = sd_ble_gap_adv_start(m_adv_handle, conf_tag);
  514. #endif
  515. if (err_code != 0) {
  516. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  517. "Can not start advertisment. status: 0x" HEX2_FMT, (uint16_t)err_code));
  518. }
  519. m_adv_in_progress = true;
  520. return true;
  521. }
  522. void ble_drv_advertise_stop(void) {
  523. if (m_adv_in_progress == true) {
  524. uint32_t err_code;
  525. #if (BLUETOOTH_SD == 110)
  526. if ((err_code = sd_ble_gap_adv_stop()) != 0) {
  527. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  528. "Can not stop advertisment. status: 0x" HEX2_FMT, (uint16_t)err_code));
  529. }
  530. #else
  531. if ((err_code = sd_ble_gap_adv_stop(m_adv_handle)) != 0) {
  532. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  533. "Can not stop advertisment. status: 0x" HEX2_FMT, (uint16_t)err_code));
  534. }
  535. #endif
  536. }
  537. m_adv_in_progress = false;
  538. }
  539. void ble_drv_attr_s_read(uint16_t conn_handle, uint16_t handle, uint16_t len, uint8_t * p_data) {
  540. ble_gatts_value_t gatts_value;
  541. memset(&gatts_value, 0, sizeof(gatts_value));
  542. gatts_value.len = len;
  543. gatts_value.offset = 0;
  544. gatts_value.p_value = p_data;
  545. uint32_t err_code = sd_ble_gatts_value_get(conn_handle,
  546. handle,
  547. &gatts_value);
  548. if (err_code != 0) {
  549. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  550. "Can not read attribute value. status: 0x" HEX2_FMT, (uint16_t)err_code));
  551. }
  552. }
  553. void ble_drv_attr_s_write(uint16_t conn_handle, uint16_t handle, uint16_t len, uint8_t * p_data) {
  554. ble_gatts_value_t gatts_value;
  555. memset(&gatts_value, 0, sizeof(gatts_value));
  556. gatts_value.len = len;
  557. gatts_value.offset = 0;
  558. gatts_value.p_value = p_data;
  559. uint32_t err_code = sd_ble_gatts_value_set(conn_handle, handle, &gatts_value);
  560. if (err_code != 0) {
  561. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  562. "Can not write attribute value. status: 0x" HEX2_FMT, (uint16_t)err_code));
  563. }
  564. }
  565. void ble_drv_attr_s_notify(uint16_t conn_handle, uint16_t handle, uint16_t len, uint8_t * p_data) {
  566. uint16_t hvx_len = len;
  567. ble_gatts_hvx_params_t hvx_params;
  568. memset(&hvx_params, 0, sizeof(hvx_params));
  569. hvx_params.handle = handle;
  570. hvx_params.type = BLE_GATT_HVX_NOTIFICATION;
  571. hvx_params.offset = 0;
  572. hvx_params.p_len = &hvx_len;
  573. hvx_params.p_data = p_data;
  574. while (m_tx_in_progress > MAX_TX_IN_PROGRESS) {
  575. ;
  576. }
  577. BLE_DRIVER_LOG("Request TX, m_tx_in_progress: %u\n", m_tx_in_progress);
  578. uint32_t err_code;
  579. if ((err_code = sd_ble_gatts_hvx(conn_handle, &hvx_params)) != 0) {
  580. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  581. "Can not notify attribute value. status: 0x" HEX2_FMT, (uint16_t)err_code));
  582. }
  583. m_tx_in_progress++;
  584. BLE_DRIVER_LOG("Queued TX, m_tx_in_progress: %u\n", m_tx_in_progress);
  585. }
  586. void ble_drv_gap_event_handler_set(mp_obj_t obj, ble_drv_gap_evt_callback_t evt_handler) {
  587. mp_gap_observer = obj;
  588. gap_event_handler = evt_handler;
  589. }
  590. void ble_drv_gatts_event_handler_set(mp_obj_t obj, ble_drv_gatts_evt_callback_t evt_handler) {
  591. mp_gatts_observer = obj;
  592. gatts_event_handler = evt_handler;
  593. }
  594. #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  595. void ble_drv_gattc_event_handler_set(mp_obj_t obj, ble_drv_gattc_evt_callback_t evt_handler) {
  596. mp_gattc_observer = obj;
  597. gattc_event_handler = evt_handler;
  598. }
  599. void ble_drv_adv_report_handler_set(mp_obj_t obj, ble_drv_adv_evt_callback_t evt_handler) {
  600. mp_adv_observer = obj;
  601. adv_event_handler = evt_handler;
  602. }
  603. void ble_drv_attr_c_read(uint16_t conn_handle, uint16_t handle, mp_obj_t obj, ble_drv_gattc_char_data_callback_t cb) {
  604. mp_gattc_char_data_observer = obj;
  605. gattc_char_data_handle = cb;
  606. uint32_t err_code = sd_ble_gattc_read(conn_handle,
  607. handle,
  608. 0);
  609. if (err_code != 0) {
  610. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  611. "Can not read attribute value. status: 0x" HEX2_FMT, (uint16_t)err_code));
  612. }
  613. while (gattc_char_data_handle != NULL) {
  614. ;
  615. }
  616. }
  617. void ble_drv_attr_c_write(uint16_t conn_handle, uint16_t handle, uint16_t len, uint8_t * p_data, bool w_response) {
  618. ble_gattc_write_params_t write_params;
  619. if (w_response) {
  620. write_params.write_op = BLE_GATT_OP_WRITE_REQ;
  621. } else {
  622. write_params.write_op = BLE_GATT_OP_WRITE_CMD;
  623. }
  624. write_params.flags = BLE_GATT_EXEC_WRITE_FLAG_PREPARED_CANCEL;
  625. write_params.handle = handle;
  626. write_params.offset = 0;
  627. write_params.len = len;
  628. write_params.p_value = p_data;
  629. m_write_done = !w_response;
  630. uint32_t err_code = sd_ble_gattc_write(conn_handle, &write_params);
  631. if (err_code != 0) {
  632. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  633. "Can not write attribute value. status: 0x" HEX2_FMT, (uint16_t)err_code));
  634. }
  635. while (m_write_done != true) {
  636. ;
  637. }
  638. }
  639. void ble_drv_scan_start(bool cont) {
  640. SD_TEST_OR_ENABLE();
  641. ble_gap_scan_params_t scan_params;
  642. memset(&scan_params, 0, sizeof(ble_gap_scan_params_t));
  643. scan_params.extended = 0;
  644. scan_params.active = 1;
  645. scan_params.interval = MSEC_TO_UNITS(100, UNIT_0_625_MS);
  646. scan_params.window = MSEC_TO_UNITS(100, UNIT_0_625_MS);
  647. scan_params.timeout = 0; // Infinite
  648. ble_data_t scan_buffer = {
  649. .p_data = m_scan_buffer,
  650. .len = BLE_GAP_SCAN_BUFFER_MIN
  651. };
  652. uint32_t err_code;
  653. ble_gap_scan_params_t * p_scan_params = &scan_params;
  654. if (cont) {
  655. p_scan_params = NULL;
  656. }
  657. if ((err_code = sd_ble_gap_scan_start(p_scan_params, &scan_buffer)) != 0) {
  658. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  659. "Can not start scanning. status: 0x" HEX2_FMT, (uint16_t)err_code));
  660. }
  661. }
  662. void ble_drv_scan_stop(void) {
  663. sd_ble_gap_scan_stop();
  664. }
  665. void ble_drv_connect(uint8_t * p_addr, uint8_t addr_type) {
  666. SD_TEST_OR_ENABLE();
  667. ble_gap_scan_params_t scan_params;
  668. memset(&scan_params, 0, sizeof(ble_gap_scan_params_t));
  669. scan_params.extended = 0;
  670. scan_params.active = 1;
  671. scan_params.interval = MSEC_TO_UNITS(100, UNIT_0_625_MS);
  672. scan_params.window = MSEC_TO_UNITS(100, UNIT_0_625_MS);
  673. scan_params.timeout = 0; // infinite
  674. ble_gap_addr_t addr;
  675. memset(&addr, 0, sizeof(addr));
  676. addr.addr_type = addr_type;
  677. memcpy(addr.addr, p_addr, 6);
  678. BLE_DRIVER_LOG("GAP CONNECTING: "HEX2_FMT":"HEX2_FMT":"HEX2_FMT":"HEX2_FMT":"HEX2_FMT":"HEX2_FMT", type: %d\n",
  679. addr.addr[0], addr.addr[1], addr.addr[2], addr.addr[3], addr.addr[4], addr.addr[5], addr.addr_type);
  680. ble_gap_conn_params_t conn_params;
  681. // set connection parameters
  682. memset(&conn_params, 0, sizeof(conn_params));
  683. conn_params.min_conn_interval = BLE_MIN_CONN_INTERVAL;
  684. conn_params.max_conn_interval = BLE_MAX_CONN_INTERVAL;
  685. conn_params.slave_latency = BLE_SLAVE_LATENCY;
  686. conn_params.conn_sup_timeout = BLE_CONN_SUP_TIMEOUT;
  687. uint8_t conn_tag = BLE_DRV_CONN_CONFIG_TAG;
  688. uint32_t err_code;
  689. if ((err_code = sd_ble_gap_connect(&addr,
  690. &scan_params,
  691. &conn_params,
  692. conn_tag)) != 0) {
  693. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError,
  694. "Can not connect. status: 0x" HEX2_FMT, (uint16_t)err_code));
  695. }
  696. }
  697. bool ble_drv_discover_services(mp_obj_t obj, uint16_t conn_handle, uint16_t start_handle, ble_drv_disc_add_service_callback_t cb) {
  698. BLE_DRIVER_LOG("Discover primary services. Conn handle: 0x" HEX2_FMT "\n",
  699. conn_handle);
  700. mp_gattc_disc_service_observer = obj;
  701. disc_add_service_handler = cb;
  702. m_primary_service_found = false;
  703. uint32_t err_code;
  704. err_code = sd_ble_gattc_primary_services_discover(conn_handle,
  705. start_handle,
  706. NULL);
  707. if (err_code != 0) {
  708. return false;
  709. }
  710. // busy loop until last service has been iterated
  711. while (disc_add_service_handler != NULL) {
  712. ;
  713. }
  714. if (m_primary_service_found) {
  715. return true;
  716. } else {
  717. return false;
  718. }
  719. }
  720. bool ble_drv_discover_characteristic(mp_obj_t obj,
  721. uint16_t conn_handle,
  722. uint16_t start_handle,
  723. uint16_t end_handle,
  724. ble_drv_disc_add_char_callback_t cb) {
  725. BLE_DRIVER_LOG("Discover characteristicts. Conn handle: 0x" HEX2_FMT "\n",
  726. conn_handle);
  727. mp_gattc_disc_char_observer = obj;
  728. disc_add_char_handler = cb;
  729. ble_gattc_handle_range_t handle_range;
  730. handle_range.start_handle = start_handle;
  731. handle_range.end_handle = end_handle;
  732. m_characteristic_found = false;
  733. uint32_t err_code;
  734. err_code = sd_ble_gattc_characteristics_discover(conn_handle, &handle_range);
  735. if (err_code != 0) {
  736. return false;
  737. }
  738. // busy loop until last service has been iterated
  739. while (disc_add_char_handler != NULL) {
  740. ;
  741. }
  742. if (m_characteristic_found) {
  743. return true;
  744. } else {
  745. return false;
  746. }
  747. }
  748. void ble_drv_discover_descriptors(void) {
  749. }
  750. #endif // (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  751. static void sd_evt_handler(uint32_t evt_id) {
  752. switch (evt_id) {
  753. #if MICROPY_MBFS
  754. case NRF_EVT_FLASH_OPERATION_SUCCESS:
  755. flash_operation_finished(FLASH_STATE_SUCCESS);
  756. break;
  757. case NRF_EVT_FLASH_OPERATION_ERROR:
  758. flash_operation_finished(FLASH_STATE_ERROR);
  759. break;
  760. #endif
  761. default:
  762. // unhandled event!
  763. break;
  764. }
  765. }
  766. static void ble_evt_handler(ble_evt_t * p_ble_evt) {
  767. // S132 event ranges.
  768. // Common 0x01 -> 0x0F
  769. // GAP 0x10 -> 0x2F
  770. // GATTC 0x30 -> 0x4F
  771. // GATTS 0x50 -> 0x6F
  772. // L2CAP 0x70 -> 0x8F
  773. switch (p_ble_evt->header.evt_id) {
  774. case BLE_GAP_EVT_CONNECTED:
  775. BLE_DRIVER_LOG("GAP CONNECT\n");
  776. m_adv_in_progress = false;
  777. gap_event_handler(mp_gap_observer, p_ble_evt->header.evt_id, p_ble_evt->evt.gap_evt.conn_handle, p_ble_evt->header.evt_len - (2 * sizeof(uint16_t)), NULL);
  778. ble_gap_conn_params_t conn_params;
  779. (void)sd_ble_gap_ppcp_get(&conn_params);
  780. (void)sd_ble_gap_conn_param_update(p_ble_evt->evt.gap_evt.conn_handle, &conn_params);
  781. break;
  782. case BLE_GAP_EVT_DISCONNECTED:
  783. BLE_DRIVER_LOG("GAP DISCONNECT\n");
  784. gap_event_handler(mp_gap_observer, p_ble_evt->header.evt_id, p_ble_evt->evt.gap_evt.conn_handle, p_ble_evt->header.evt_len - (2 * sizeof(uint16_t)), NULL);
  785. break;
  786. case BLE_GATTS_EVT_HVC:
  787. gatts_event_handler(mp_gatts_observer, p_ble_evt->header.evt_id, p_ble_evt->evt.gatts_evt.params.hvc.handle, p_ble_evt->header.evt_len - (2 * sizeof(uint16_t)), NULL);
  788. break;
  789. case BLE_GATTS_EVT_WRITE:
  790. BLE_DRIVER_LOG("GATTS write\n");
  791. uint16_t handle = p_ble_evt->evt.gatts_evt.params.write.handle;
  792. uint16_t data_len = p_ble_evt->evt.gatts_evt.params.write.len;
  793. uint8_t * p_data = &p_ble_evt->evt.gatts_evt.params.write.data[0];
  794. gatts_event_handler(mp_gatts_observer, p_ble_evt->header.evt_id, handle, data_len, p_data);
  795. break;
  796. case BLE_GAP_EVT_CONN_PARAM_UPDATE:
  797. BLE_DRIVER_LOG("GAP CONN PARAM UPDATE\n");
  798. break;
  799. case BLE_GATTS_EVT_SYS_ATTR_MISSING:
  800. // No system attributes have been stored.
  801. (void)sd_ble_gatts_sys_attr_set(p_ble_evt->evt.gatts_evt.conn_handle, NULL, 0, 0);
  802. break;
  803. #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  804. case BLE_GATTS_EVT_HVN_TX_COMPLETE:
  805. #else
  806. case BLE_EVT_TX_COMPLETE:
  807. #endif
  808. BLE_DRIVER_LOG("BLE EVT TX COMPLETE\n");
  809. #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  810. BLE_DRIVER_LOG("HVN_TX_COMPLETE, count: %u\n", p_ble_evt->evt.gatts_evt.params.hvn_tx_complete.count);
  811. m_tx_in_progress -= p_ble_evt->evt.gatts_evt.params.hvn_tx_complete.count;
  812. BLE_DRIVER_LOG("TX_COMPLETE, m_tx_in_progress: %u\n", m_tx_in_progress);
  813. #else
  814. BLE_DRIVER_LOG("TX_COMPLETE, count: %u\n", p_ble_evt->evt.common_evt.params.tx_complete.count);
  815. m_tx_in_progress -= p_ble_evt->evt.common_evt.params.tx_complete.count;
  816. BLE_DRIVER_LOG("TX_COMPLETE, m_tx_in_progress: %u\n", m_tx_in_progress);
  817. #endif
  818. break;
  819. case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
  820. BLE_DRIVER_LOG("BLE EVT SEC PARAMS REQUEST\n");
  821. // pairing not supported
  822. (void)sd_ble_gap_sec_params_reply(p_ble_evt->evt.gatts_evt.conn_handle,
  823. BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP,
  824. NULL, NULL);
  825. break;
  826. #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  827. case BLE_GAP_EVT_ADV_REPORT:
  828. BLE_DRIVER_LOG("BLE EVT ADV REPORT\n");
  829. ble_drv_adv_data_t adv_data = {
  830. .p_peer_addr = p_ble_evt->evt.gap_evt.params.adv_report.peer_addr.addr,
  831. .addr_type = p_ble_evt->evt.gap_evt.params.adv_report.peer_addr.addr_type,
  832. .is_scan_resp = p_ble_evt->evt.gap_evt.params.adv_report.type.scan_response,
  833. .rssi = p_ble_evt->evt.gap_evt.params.adv_report.rssi,
  834. .data_len = p_ble_evt->evt.gap_evt.params.adv_report.data.len,
  835. .p_data = p_ble_evt->evt.gap_evt.params.adv_report.data.p_data,
  836. // .adv_type =
  837. };
  838. // TODO: Fix unsafe callback to possible undefined callback...
  839. adv_event_handler(mp_adv_observer,
  840. p_ble_evt->header.evt_id,
  841. &adv_data);
  842. break;
  843. case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
  844. BLE_DRIVER_LOG("BLE EVT CONN PARAM UPDATE REQUEST\n");
  845. (void)sd_ble_gap_conn_param_update(p_ble_evt->evt.gap_evt.conn_handle,
  846. &p_ble_evt->evt.gap_evt.params.conn_param_update_request.conn_params);
  847. break;
  848. case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
  849. BLE_DRIVER_LOG("BLE EVT PRIMARY SERVICE DISCOVERY RESPONSE\n");
  850. BLE_DRIVER_LOG(">>> service count: %d\n", p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count);
  851. for (uint16_t i = 0; i < p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count; i++) {
  852. ble_gattc_service_t * p_service = &p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[i];
  853. ble_drv_service_data_t service;
  854. service.uuid_type = p_service->uuid.type;
  855. service.uuid = p_service->uuid.uuid;
  856. service.start_handle = p_service->handle_range.start_handle;
  857. service.end_handle = p_service->handle_range.end_handle;
  858. disc_add_service_handler(mp_gattc_disc_service_observer, &service);
  859. }
  860. if (p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count > 0) {
  861. m_primary_service_found = true;
  862. }
  863. // mark end of service discovery
  864. disc_add_service_handler = NULL;
  865. break;
  866. case BLE_GATTC_EVT_CHAR_DISC_RSP:
  867. BLE_DRIVER_LOG("BLE EVT CHAR DISCOVERY RESPONSE\n");
  868. BLE_DRIVER_LOG(">>> characteristic count: %d\n", p_ble_evt->evt.gattc_evt.params.char_disc_rsp.count);
  869. for (uint16_t i = 0; i < p_ble_evt->evt.gattc_evt.params.char_disc_rsp.count; i++) {
  870. ble_gattc_char_t * p_char = &p_ble_evt->evt.gattc_evt.params.char_disc_rsp.chars[i];
  871. ble_drv_char_data_t char_data;
  872. char_data.uuid_type = p_char->uuid.type;
  873. char_data.uuid = p_char->uuid.uuid;
  874. char_data.decl_handle = p_char->handle_decl;
  875. char_data.value_handle = p_char->handle_value;
  876. char_data.props |= (p_char->char_props.broadcast) ? UBLUEPY_PROP_BROADCAST : 0;
  877. char_data.props |= (p_char->char_props.read) ? UBLUEPY_PROP_READ : 0;
  878. char_data.props |= (p_char->char_props.write_wo_resp) ? UBLUEPY_PROP_WRITE_WO_RESP : 0;
  879. char_data.props |= (p_char->char_props.write) ? UBLUEPY_PROP_WRITE : 0;
  880. char_data.props |= (p_char->char_props.notify) ? UBLUEPY_PROP_NOTIFY : 0;
  881. char_data.props |= (p_char->char_props.indicate) ? UBLUEPY_PROP_INDICATE : 0;
  882. #if 0
  883. char_data.props |= (p_char->char_props.auth_signed_wr) ? UBLUEPY_PROP_NOTIFY : 0;
  884. #endif
  885. disc_add_char_handler(mp_gattc_disc_char_observer, &char_data);
  886. }
  887. if (p_ble_evt->evt.gattc_evt.params.char_disc_rsp.count > 0) {
  888. m_characteristic_found = true;
  889. }
  890. // mark end of characteristic discovery
  891. disc_add_char_handler = NULL;
  892. break;
  893. case BLE_GATTC_EVT_READ_RSP:
  894. BLE_DRIVER_LOG("BLE EVT READ RESPONSE, offset: 0x"HEX2_FMT", length: 0x"HEX2_FMT"\n",
  895. p_ble_evt->evt.gattc_evt.params.read_rsp.offset,
  896. p_ble_evt->evt.gattc_evt.params.read_rsp.len);
  897. gattc_char_data_handle(mp_gattc_char_data_observer,
  898. p_ble_evt->evt.gattc_evt.params.read_rsp.len,
  899. p_ble_evt->evt.gattc_evt.params.read_rsp.data);
  900. // mark end of read
  901. gattc_char_data_handle = NULL;
  902. break;
  903. case BLE_GATTC_EVT_WRITE_RSP:
  904. BLE_DRIVER_LOG("BLE EVT WRITE RESPONSE\n");
  905. m_write_done = true;
  906. break;
  907. case BLE_GATTC_EVT_HVX:
  908. BLE_DRIVER_LOG("BLE EVT HVX RESPONSE\n");
  909. break;
  910. case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
  911. BLE_DRIVER_LOG("GATTS EVT EXCHANGE MTU REQUEST\n");
  912. (void)sd_ble_gatts_exchange_mtu_reply(p_ble_evt->evt.gatts_evt.conn_handle, 23); // MAX MTU size
  913. break;
  914. #endif // (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140)
  915. default:
  916. BLE_DRIVER_LOG(">>> unhandled evt: 0x" HEX2_FMT "\n", p_ble_evt->header.evt_id);
  917. break;
  918. }
  919. }
  920. static uint8_t m_ble_evt_buf[sizeof(ble_evt_t) + (GATT_MTU_SIZE_DEFAULT)] __attribute__ ((aligned (4)));
  921. #ifdef NRF51
  922. void SWI2_IRQHandler(void) {
  923. #else
  924. void SWI2_EGU2_IRQHandler(void) {
  925. #endif
  926. uint32_t evt_id;
  927. while (sd_evt_get(&evt_id) != NRF_ERROR_NOT_FOUND) {
  928. sd_evt_handler(evt_id);
  929. }
  930. while (1) {
  931. uint16_t evt_len = sizeof(m_ble_evt_buf);
  932. uint32_t err_code = sd_ble_evt_get(m_ble_evt_buf, &evt_len);
  933. if (err_code != NRF_SUCCESS) {
  934. // Possible error conditions:
  935. // * NRF_ERROR_NOT_FOUND: no events left, break
  936. // * NRF_ERROR_DATA_SIZE: retry with a bigger data buffer
  937. // (currently not handled, TODO)
  938. // * NRF_ERROR_INVALID_ADDR: pointer is not aligned, should
  939. // not happen.
  940. // In all cases, it's best to simply stop now.
  941. if (err_code == NRF_ERROR_DATA_SIZE) {
  942. BLE_DRIVER_LOG("NRF_ERROR_DATA_SIZE\n");
  943. }
  944. break;
  945. }
  946. ble_evt_handler((ble_evt_t *)m_ble_evt_buf);
  947. }
  948. }
  949. #endif // BLUETOOTH_SD