gap.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #include "gap.h"
  2. #include "app_entry.h"
  3. #include "ble.h"
  4. #include "cmsis_os.h"
  5. #include "otp.h"
  6. #include "dev_info_service.h"
  7. #include "battery_service.h"
  8. #include "serial_service.h"
  9. #include <applications/bt/bt_service/bt.h>
  10. #include <furi-hal.h>
  11. #define GAP_TAG "BLE"
  12. #define FAST_ADV_TIMEOUT 30000
  13. #define INITIAL_ADV_TIMEOUT 60000
  14. #define BD_ADDR_SIZE_LOCAL 6
  15. typedef struct {
  16. uint16_t gap_svc_handle;
  17. uint16_t dev_name_char_handle;
  18. uint16_t appearance_char_handle;
  19. uint16_t connection_handle;
  20. uint8_t adv_svc_uuid_len;
  21. uint8_t adv_svc_uuid[20];
  22. } GapSvc;
  23. typedef struct {
  24. GapSvc gap_svc;
  25. GapState state;
  26. uint8_t mac_address[BD_ADDR_SIZE_LOCAL];
  27. Bt* bt;
  28. osTimerId advertise_timer;
  29. osThreadAttr_t thread_attr;
  30. osThreadId_t thread_id;
  31. } Gap;
  32. // Identity root key
  33. static const uint8_t gap_irk[16] = {0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0};
  34. // Encryption root key
  35. static const uint8_t gap_erk[16] = {0xfe,0xdc,0xba,0x09,0x87,0x65,0x43,0x21,0xfe,0xdc,0xba,0x09,0x87,0x65,0x43,0x21};
  36. // Appearence characteristic UUID
  37. static const uint8_t gap_appearence_char_uuid[] = {0x00, 0x86};
  38. // Default MAC address
  39. static const uint8_t gap_default_mac_addr[] = {0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x72};
  40. static Gap* gap = NULL;
  41. static void gap_advertise(GapState new_state);
  42. static void gap_app(void *arg);
  43. SVCCTL_UserEvtFlowStatus_t SVCCTL_App_Notification( void *pckt )
  44. {
  45. hci_event_pckt *event_pckt;
  46. evt_le_meta_event *meta_evt;
  47. evt_blue_aci *blue_evt;
  48. hci_le_phy_update_complete_event_rp0 *evt_le_phy_update_complete;
  49. uint8_t tx_phy;
  50. uint8_t rx_phy;
  51. tBleStatus ret = BLE_STATUS_INVALID_PARAMS;
  52. event_pckt = (hci_event_pckt*) ((hci_uart_pckt *) pckt)->data;
  53. switch (event_pckt->evt) {
  54. case EVT_DISCONN_COMPLETE:
  55. {
  56. hci_disconnection_complete_event_rp0 *disconnection_complete_event = (hci_disconnection_complete_event_rp0 *) event_pckt->data;
  57. if (disconnection_complete_event->Connection_Handle == gap->gap_svc.connection_handle) {
  58. gap->gap_svc.connection_handle = 0;
  59. gap->state = GapStateIdle;
  60. FURI_LOG_I(GAP_TAG, "Disconnect from client");
  61. }
  62. // Restart advertising
  63. gap_advertise(GapStateAdvFast);
  64. furi_hal_power_insomnia_exit();
  65. }
  66. break;
  67. case EVT_LE_META_EVENT:
  68. meta_evt = (evt_le_meta_event*) event_pckt->data;
  69. switch (meta_evt->subevent) {
  70. case EVT_LE_CONN_UPDATE_COMPLETE:
  71. FURI_LOG_D(GAP_TAG, "Connection update event");
  72. break;
  73. case EVT_LE_PHY_UPDATE_COMPLETE:
  74. evt_le_phy_update_complete = (hci_le_phy_update_complete_event_rp0*)meta_evt->data;
  75. if(evt_le_phy_update_complete->Status) {
  76. FURI_LOG_E(GAP_TAG, "Update PHY failed, status %d", evt_le_phy_update_complete->Status);
  77. } else {
  78. FURI_LOG_I(GAP_TAG, "Update PHY succeed");
  79. }
  80. ret = hci_le_read_phy(gap->gap_svc.connection_handle,&tx_phy,&rx_phy);
  81. if(ret) {
  82. FURI_LOG_E(GAP_TAG, "Read PHY failed, status: %d", ret);
  83. } else {
  84. FURI_LOG_I(GAP_TAG, "PHY Params TX= %d, RX= %d ", tx_phy, rx_phy);
  85. }
  86. break;
  87. case EVT_LE_CONN_COMPLETE:
  88. furi_hal_power_insomnia_enter();
  89. hci_le_connection_complete_event_rp0* connection_complete_event = (hci_le_connection_complete_event_rp0 *) meta_evt->data;
  90. FURI_LOG_I(GAP_TAG, "Connection complete for connection handle 0x%x", connection_complete_event->Connection_Handle);
  91. // Stop advertising as connection completed
  92. osTimerStop(gap->advertise_timer);
  93. // Update connection status and handle
  94. gap->state = GapStateConnected;
  95. gap->gap_svc.connection_handle = connection_complete_event->Connection_Handle;
  96. // Start pairing by sending security request
  97. aci_gap_slave_security_req(connection_complete_event->Connection_Handle);
  98. break;
  99. default:
  100. break;
  101. }
  102. break;
  103. case EVT_VENDOR:
  104. blue_evt = (evt_blue_aci*) event_pckt->data;
  105. switch (blue_evt->ecode) {
  106. aci_gap_pairing_complete_event_rp0 *pairing_complete;
  107. case EVT_BLUE_GAP_LIMITED_DISCOVERABLE:
  108. FURI_LOG_I(GAP_TAG, "Limited discoverable event");
  109. break;
  110. case EVT_BLUE_GAP_PASS_KEY_REQUEST:
  111. {
  112. // Generate random PIN code
  113. uint32_t pin = rand() % 999999;
  114. aci_gap_pass_key_resp(gap->gap_svc.connection_handle, pin);
  115. FURI_LOG_I(GAP_TAG, "Pass key request event. Pin: %d", pin);
  116. bt_pin_code_show(gap->bt, pin);
  117. }
  118. break;
  119. case EVT_BLUE_GAP_AUTHORIZATION_REQUEST:
  120. FURI_LOG_I(GAP_TAG, "Authorization request event");
  121. break;
  122. case EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED:
  123. FURI_LOG_I(GAP_TAG, "Slave security initiated");
  124. break;
  125. case EVT_BLUE_GAP_BOND_LOST:
  126. FURI_LOG_I(GAP_TAG, "Bond lost event. Start rebonding");
  127. aci_gap_allow_rebond(gap->gap_svc.connection_handle);
  128. break;
  129. case EVT_BLUE_GAP_DEVICE_FOUND:
  130. FURI_LOG_I(GAP_TAG, "Device found event");
  131. break;
  132. case EVT_BLUE_GAP_ADDR_NOT_RESOLVED:
  133. FURI_LOG_I(GAP_TAG, "Address not resolved event");
  134. break;
  135. case EVT_BLUE_GAP_KEYPRESS_NOTIFICATION:
  136. FURI_LOG_I(GAP_TAG, "Key press notification event");
  137. break;
  138. case EVT_BLUE_GAP_NUMERIC_COMPARISON_VALUE:
  139. FURI_LOG_I(GAP_TAG, "Hex_value = %lx",
  140. ((aci_gap_numeric_comparison_value_event_rp0 *)(blue_evt->data))->Numeric_Value);
  141. aci_gap_numeric_comparison_value_confirm_yesno(gap->gap_svc.connection_handle, 1);
  142. break;
  143. case (EVT_BLUE_GAP_PAIRING_CMPLT):
  144. {
  145. pairing_complete = (aci_gap_pairing_complete_event_rp0*)blue_evt->data;
  146. if (pairing_complete->Status) {
  147. FURI_LOG_E(GAP_TAG, "Pairing failed with status: %d. Terminating connection", pairing_complete->Status);
  148. aci_gap_terminate(gap->gap_svc.connection_handle, 5);
  149. } else {
  150. FURI_LOG_I(GAP_TAG, "Pairing complete");
  151. }
  152. }
  153. break;
  154. case EVT_BLUE_GAP_PROCEDURE_COMPLETE:
  155. FURI_LOG_I(GAP_TAG, "Procedure complete event");
  156. break;
  157. }
  158. default:
  159. break;
  160. }
  161. return SVCCTL_UserEvtFlowEnable;
  162. }
  163. void SVCCTL_SvcInit() {
  164. // Dummy function to prevent unused services initialization
  165. // TODO refactor (disable all services in WPAN config)
  166. }
  167. static void set_advertisment_service_uid(uint8_t* uid, uint8_t uid_len) {
  168. gap->gap_svc.adv_svc_uuid_len = 1;
  169. if(uid_len == 2) {
  170. gap->gap_svc.adv_svc_uuid[0] = AD_TYPE_16_BIT_SERV_UUID;
  171. } else if (uid_len == 4) {
  172. gap->gap_svc.adv_svc_uuid[0] = AD_TYPE_32_BIT_SERV_UUID;
  173. } else if(uid_len == 16) {
  174. gap->gap_svc.adv_svc_uuid[0] = AD_TYPE_128_BIT_SERV_UUID_CMPLT_LIST;
  175. }
  176. memcpy(&gap->gap_svc.adv_svc_uuid[1], uid, uid_len);
  177. gap->gap_svc.adv_svc_uuid_len += uid_len;
  178. }
  179. GapState gap_get_status() {
  180. return gap->state;
  181. }
  182. void gap_init_mac_address(Gap* gap) {
  183. uint8_t *otp_addr;
  184. uint32_t udn;
  185. uint32_t company_id;
  186. uint32_t device_id;
  187. udn = LL_FLASH_GetUDN();
  188. if(udn != 0xFFFFFFFF) {
  189. company_id = LL_FLASH_GetSTCompanyID();
  190. device_id = LL_FLASH_GetDeviceID();
  191. gap->mac_address[0] = (uint8_t)(udn & 0x000000FF);
  192. gap->mac_address[1] = (uint8_t)( (udn & 0x0000FF00) >> 8 );
  193. gap->mac_address[2] = (uint8_t)( (udn & 0x00FF0000) >> 16 );
  194. gap->mac_address[3] = (uint8_t)device_id;
  195. gap->mac_address[4] = (uint8_t)(company_id & 0x000000FF);;
  196. gap->mac_address[5] = (uint8_t)( (company_id & 0x0000FF00) >> 8 );
  197. } else {
  198. otp_addr = OTP_Read(0);
  199. if(otp_addr) {
  200. memcpy(gap->mac_address, ((OTP_ID0_t*)otp_addr)->bd_address, sizeof(gap->mac_address));
  201. } else {
  202. memcpy(gap->mac_address, gap_default_mac_addr, sizeof(gap->mac_address));
  203. }
  204. }
  205. }
  206. static void gap_init_svc(Gap* gap) {
  207. tBleStatus status;
  208. uint32_t srd_bd_addr[2];
  209. //HCI Reset to synchronise BLE Stack*/
  210. hci_reset();
  211. // Configure mac address
  212. gap_init_mac_address(gap);
  213. aci_hal_write_config_data(CONFIG_DATA_PUBADDR_OFFSET, CONFIG_DATA_PUBADDR_LEN, (uint8_t*)gap->mac_address);
  214. /* Static random Address
  215. * The two upper bits shall be set to 1
  216. * The lowest 32bits is read from the UDN to differentiate between devices
  217. * The RNG may be used to provide a random number on each power on
  218. */
  219. srd_bd_addr[1] = 0x0000ED6E;
  220. srd_bd_addr[0] = LL_FLASH_GetUDN();
  221. aci_hal_write_config_data( CONFIG_DATA_RANDOM_ADDRESS_OFFSET, CONFIG_DATA_RANDOM_ADDRESS_LEN, (uint8_t*)srd_bd_addr );
  222. // Set Identity root key used to derive LTK and CSRK
  223. aci_hal_write_config_data( CONFIG_DATA_IR_OFFSET, CONFIG_DATA_IR_LEN, (uint8_t*)gap_irk );
  224. // Set Encryption root key used to derive LTK and CSRK
  225. aci_hal_write_config_data( CONFIG_DATA_ER_OFFSET, CONFIG_DATA_ER_LEN, (uint8_t*)gap_erk );
  226. // Set TX Power to 0 dBm
  227. aci_hal_set_tx_power_level(1, 0x19);
  228. // Initialize GATT interface
  229. aci_gatt_init();
  230. // Initialize GAP interface
  231. const char *name = furi_hal_version_get_device_name_ptr();
  232. aci_gap_init(GAP_PERIPHERAL_ROLE, 0, strlen(name),
  233. &gap->gap_svc.gap_svc_handle, &gap->gap_svc.dev_name_char_handle, &gap->gap_svc.appearance_char_handle);
  234. // Set GAP characteristics
  235. status = aci_gatt_update_char_value(gap->gap_svc.gap_svc_handle, gap->gap_svc.dev_name_char_handle, 0, strlen(name), (uint8_t *) name);
  236. if (status) {
  237. FURI_LOG_E(GAP_TAG, "Failed updating name characteristic: %d", status);
  238. }
  239. status = aci_gatt_update_char_value(gap->gap_svc.gap_svc_handle, gap->gap_svc.appearance_char_handle, 0, 2, gap_appearence_char_uuid);
  240. if(status) {
  241. FURI_LOG_E(GAP_TAG, "Failed updating appearence characteristic: %d", status);
  242. }
  243. // Set default PHY
  244. hci_le_set_default_phy(ALL_PHYS_PREFERENCE, TX_2M_PREFERRED, RX_2M_PREFERRED);
  245. // Set I/O capability
  246. aci_gap_set_io_capability(IO_CAP_DISPLAY_ONLY);
  247. // Setup authentication
  248. aci_gap_set_authentication_requirement(1, 1, 1, 0, 8, 16, 1, 0, PUBLIC_ADDR);
  249. // Configure whitelist
  250. aci_gap_configure_whitelist();
  251. }
  252. static void gap_advertise(GapState new_state)
  253. {
  254. tBleStatus status;
  255. uint16_t min_interval;
  256. uint16_t max_interval;
  257. if (new_state == GapStateAdvFast) {
  258. min_interval = 0x80; // 80 ms
  259. max_interval = 0xa0; // 100 ms
  260. } else {
  261. min_interval = 0x0640; // 1 s
  262. max_interval = 0x0fa0; // 2.5 s
  263. }
  264. // Stop advertising timer
  265. osTimerStop(gap->advertise_timer);
  266. if ((new_state == GapStateAdvLowPower) && ((gap->state == GapStateAdvFast) || (gap->state == GapStateAdvLowPower))) {
  267. // Stop advertising
  268. status = aci_gap_set_non_discoverable();
  269. if (status) {
  270. FURI_LOG_E(GAP_TAG, "Stop Advertising Failed, result: %d", status);
  271. }
  272. }
  273. // Configure advertising
  274. gap->state = new_state;
  275. const char* name = furi_hal_version_get_ble_local_device_name_ptr();
  276. status = aci_gap_set_discoverable(ADV_IND, min_interval, max_interval, PUBLIC_ADDR, 0,
  277. strlen(name), (uint8_t*)name,
  278. gap->gap_svc.adv_svc_uuid_len, gap->gap_svc.adv_svc_uuid, 0, 0);
  279. if(status) {
  280. FURI_LOG_E(GAP_TAG, "Set discoverable err: %d", status);
  281. }
  282. osTimerStart(gap->advertise_timer, INITIAL_ADV_TIMEOUT);
  283. }
  284. static void gap_advertise_request(Gap* gap) {
  285. osThreadFlagsSet(gap->thread_id, 1);
  286. }
  287. static void gap_advetise_timer_callback(void* context) {
  288. furi_assert(context);
  289. Gap* gap = context;
  290. gap_advertise_request(gap);
  291. }
  292. bool gap_init() {
  293. if (APPE_Status() != BleGlueStatusStarted) {
  294. return false;
  295. }
  296. gap = furi_alloc(sizeof(Gap));
  297. srand(DWT->CYCCNT);
  298. // Open Bt record
  299. gap->bt = furi_record_open("bt");
  300. // Create advertising timer
  301. gap->advertise_timer = osTimerNew(gap_advetise_timer_callback, osTimerOnce, &gap, NULL);
  302. // Initialization of HCI & GATT & GAP layer
  303. gap_init_svc(gap);
  304. // Initialization of the BLE Services
  305. SVCCTL_Init();
  306. // Initialization of the BLE App Context
  307. gap->state = GapStateIdle;
  308. gap->gap_svc.connection_handle = 0xFFFF;
  309. // Thread configuration
  310. gap->thread_attr.name = "BLE advertising";
  311. gap->thread_attr.stack_size = 512;
  312. gap->thread_id = osThreadNew(gap_app, NULL, &gap->thread_attr);
  313. // Start Device Information service
  314. dev_info_svc_start();
  315. // Start Battery service
  316. battery_svc_start();
  317. // Start Serial application
  318. serial_svc_start();
  319. // Configure advirtise service UUID
  320. uint8_t adv_service_uid[2];
  321. adv_service_uid[0] = 0x80 | furi_hal_version_get_hw_color();
  322. adv_service_uid[1] = 0x30;
  323. set_advertisment_service_uid(adv_service_uid, sizeof(adv_service_uid));
  324. gap_advertise(GapStateAdvFast);
  325. return true;
  326. }
  327. static void gap_app(void *arg) {
  328. // TODO Exit from app, stop service, clean memory
  329. while(1) {
  330. osThreadFlagsWait(1, osFlagsWaitAny, osWaitForever);
  331. gap_advertise(GapStateAdvLowPower);
  332. }
  333. }