spp_and_gatt_streamer.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*
  2. * Copyright (C) 2014 BlueKitchen GmbH
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. Neither the name of the copyright holders nor the names of
  14. * contributors may be used to endorse or promote products derived
  15. * from this software without specific prior written permission.
  16. * 4. Any redistribution, use, or modification is done solely for
  17. * personal benefit and not for any commercial purpose or for
  18. * monetary gain.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
  21. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  23. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
  24. * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  25. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  26. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  27. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  28. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  29. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. * SUCH DAMAGE.
  32. *
  33. * Please inquire about commercial licensing options at
  34. * contact@bluekitchen-gmbh.com
  35. *
  36. */
  37. #define BTSTACK_FILE__ "spp_and_gatt_streamer.c"
  38. // *****************************************************************************
  39. /* EXAMPLE_START(spp_and_le_streamer): Dual mode example
  40. *
  41. * @text The SPP and LE Streamer example combines the Bluetooth Classic SPP Streamer
  42. * and the Bluetooth LE Streamer into a single application.
  43. *
  44. * @text In this Section, we only point out the differences to the individual examples
  45. * and how how the stack is configured.
  46. *
  47. * @text Note: To test, please run the example, and then:
  48. * - for SPP pair from a remote device, and open the Virtual Serial Port,
  49. * - for LE use some GATT Explorer, e.g. LightBlue, BLExplr, to enable notifications.
  50. *
  51. */
  52. // *****************************************************************************
  53. #include <stdint.h>
  54. #include <stdio.h>
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include <inttypes.h>
  58. #include "btstack.h"
  59. #include "spp_and_gatt_streamer.h"
  60. int btstack_main(int argc, const char * argv[]);
  61. #define RFCOMM_SERVER_CHANNEL 1
  62. #define HEARTBEAT_PERIOD_MS 1000
  63. #define TEST_COD 0x1234
  64. #define NUM_ROWS 25
  65. #define NUM_COLS 40
  66. #define DATA_VOLUME (10 * 1000 * 1000)
  67. /*
  68. * @section Advertisements
  69. *
  70. * @text The Flags attribute in the Advertisement Data indicates if a device is in dual-mode or not.
  71. * Flag 0x06 indicates LE General Discoverable, BR/EDR not supported although we're actually using BR/EDR.
  72. * In the past, there have been problems with Anrdoid devices when the flag was not set.
  73. * Setting it should prevent the remote implementation to try to use GATT over LE/EDR, which is not
  74. * implemented by BTstack. So, setting the flag seems like the safer choice (while it's technically incorrect).
  75. */
  76. /* LISTING_START(advertisements): Advertisement data: Flag 0x06 indicates LE-only device */
  77. const uint8_t adv_data[] = {
  78. // Flags general discoverable, BR/EDR not supported
  79. 0x02, 0x01, 0x06,
  80. // Name
  81. 0x0c, 0x09, 'L', 'E', ' ', 'S', 't', 'r', 'e', 'a', 'm', 'e', 'r',
  82. };
  83. static btstack_packet_callback_registration_t hci_event_callback_registration;
  84. uint8_t adv_data_len = sizeof(adv_data);
  85. static uint8_t test_data[NUM_ROWS * NUM_COLS];
  86. // SPP
  87. static uint8_t spp_service_buffer[150];
  88. static uint16_t spp_test_data_len;
  89. static uint16_t rfcomm_mtu;
  90. static uint16_t rfcomm_cid = 0;
  91. // static uint32_t data_to_send = DATA_VOLUME;
  92. // LE
  93. static uint16_t att_mtu;
  94. static int counter = 'A';
  95. static int le_notification_enabled;
  96. static uint16_t le_test_data_len;
  97. static hci_con_handle_t le_connection_handle;
  98. #ifdef ENABLE_GATT_OVER_CLASSIC
  99. static uint8_t gatt_service_buffer[70];
  100. #endif
  101. /*
  102. * @section Track throughput
  103. * @text We calculate the throughput by setting a start time and measuring the amount of
  104. * data sent. After a configurable REPORT_INTERVAL_MS, we print the throughput in kB/s
  105. * and reset the counter and start time.
  106. */
  107. /* LISTING_START(tracking): Tracking throughput */
  108. #define REPORT_INTERVAL_MS 3000
  109. static uint32_t test_data_transferred;
  110. static uint32_t test_data_start;
  111. static void test_reset(void){
  112. test_data_start = btstack_run_loop_get_time_ms();
  113. test_data_transferred = 0;
  114. }
  115. static void test_track_transferred(int bytes_sent){
  116. test_data_transferred += bytes_sent;
  117. // evaluate
  118. uint32_t now = btstack_run_loop_get_time_ms();
  119. uint32_t time_passed = now - test_data_start;
  120. if (time_passed < REPORT_INTERVAL_MS) return;
  121. // print speed
  122. int bytes_per_second = test_data_transferred * 1000 / time_passed;
  123. printf("%u bytes -> %u.%03u kB/s\n", (int) test_data_transferred, (int) bytes_per_second / 1000, bytes_per_second % 1000);
  124. // restart
  125. test_data_start = now;
  126. test_data_transferred = 0;
  127. }
  128. /* LISTING_END(tracking): Tracking throughput */
  129. static void spp_create_test_data(void){
  130. int x,y;
  131. for (y=0;y<NUM_ROWS;y++){
  132. for (x=0;x<NUM_COLS-2;x++){
  133. test_data[y*NUM_COLS+x] = '0' + (x % 10);
  134. }
  135. test_data[y*NUM_COLS+NUM_COLS-2] = '\n';
  136. test_data[y*NUM_COLS+NUM_COLS-1] = '\r';
  137. }
  138. }
  139. static void spp_send_packet(void){
  140. rfcomm_send(rfcomm_cid, (uint8_t*) test_data, spp_test_data_len);
  141. test_track_transferred(spp_test_data_len);
  142. #if 0
  143. if (data_to_send <= spp_test_data_len){
  144. printf("SPP Streamer: enough data send, closing channel\n");
  145. rfcomm_disconnect(rfcomm_cid);
  146. rfcomm_cid = 0;
  147. return;
  148. }
  149. data_to_send -= spp_test_data_len;
  150. #endif
  151. rfcomm_request_can_send_now_event(rfcomm_cid);
  152. }
  153. static void le_streamer(void){
  154. // check if we can send
  155. if (!le_notification_enabled) return;
  156. // create test data
  157. counter++;
  158. if (counter > 'Z') counter = 'A';
  159. memset(test_data, counter, sizeof(test_data));
  160. // send
  161. att_server_notify(le_connection_handle, ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE, (uint8_t*) test_data, le_test_data_len);
  162. // track
  163. test_track_transferred(le_test_data_len);
  164. // request next send event
  165. att_server_request_can_send_now_event(le_connection_handle);
  166. }
  167. /*
  168. * @section HCI Packet Handler
  169. *
  170. * @text The packet handler of the combined example is just the combination of the individual packet handlers.
  171. */
  172. static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  173. UNUSED(channel);
  174. UNUSED(size);
  175. bd_addr_t event_addr;
  176. uint16_t conn_interval;
  177. hci_con_handle_t con_handle;
  178. switch (packet_type) {
  179. case HCI_EVENT_PACKET:
  180. switch (hci_event_packet_get_type(packet)) {
  181. case HCI_EVENT_PIN_CODE_REQUEST:
  182. // inform about pin code request
  183. printf("Pin code request - using '0000'\n");
  184. hci_event_pin_code_request_get_bd_addr(packet, event_addr);
  185. gap_pin_code_response(event_addr, "0000");
  186. break;
  187. case HCI_EVENT_USER_CONFIRMATION_REQUEST:
  188. // inform about user confirmation request
  189. printf("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", little_endian_read_32(packet, 8));
  190. printf("SSP User Confirmation Auto accept\n");
  191. break;
  192. case HCI_EVENT_LE_META:
  193. switch (hci_event_le_meta_get_subevent_code(packet)) {
  194. case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
  195. // print connection parameters (without using float operations)
  196. con_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
  197. conn_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
  198. printf("LE Connection - Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
  199. printf("LE Connection - Connection Latency: %u\n", hci_subevent_le_connection_complete_get_conn_latency(packet));
  200. // request min con interval 15 ms for iOS 11+
  201. printf("LE Connection - Request 15 ms connection interval\n");
  202. gap_request_connection_parameter_update(con_handle, 12, 12, 0, 0x0048);
  203. break;
  204. case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
  205. // print connection parameters (without using float operations)
  206. con_handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
  207. conn_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
  208. printf("LE Connection - Connection Param update - connection interval %u.%02u ms, latency %u\n", conn_interval * 125 / 100,
  209. 25 * (conn_interval & 3), hci_subevent_le_connection_update_complete_get_conn_latency(packet));
  210. break;
  211. default:
  212. break;
  213. }
  214. break;
  215. case HCI_EVENT_DISCONNECTION_COMPLETE:
  216. // re-enable page/inquiry scan again
  217. gap_discoverable_control(1);
  218. gap_connectable_control(1);
  219. // re-enable advertisements
  220. gap_advertisements_enable(1);
  221. le_notification_enabled = 0;
  222. break;
  223. default:
  224. break;
  225. }
  226. break;
  227. default:
  228. break;
  229. }
  230. }
  231. /*
  232. * @section RFCOMM Packet Handler
  233. *
  234. * @text The RFCOMM packet handler accepts incoming connection and triggers sending of RFCOMM data on RFCOMM_EVENT_CAN_SEND_NOW
  235. */
  236. static void rfcomm_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  237. UNUSED(channel);
  238. bd_addr_t event_addr;
  239. uint8_t rfcomm_channel_nr;
  240. switch (packet_type) {
  241. case HCI_EVENT_PACKET:
  242. switch (hci_event_packet_get_type(packet)) {
  243. case RFCOMM_EVENT_INCOMING_CONNECTION:
  244. // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
  245. rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
  246. rfcomm_channel_nr = rfcomm_event_incoming_connection_get_server_channel(packet);
  247. rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
  248. printf("RFCOMM channel %u requested for %s\n", rfcomm_channel_nr, bd_addr_to_str(event_addr));
  249. rfcomm_accept_connection(rfcomm_cid);
  250. break;
  251. case RFCOMM_EVENT_CHANNEL_OPENED:
  252. // data: event(8), len(8), status (8), address (48), server channel(8), rfcomm_cid(16), max frame size(16)
  253. if (rfcomm_event_channel_opened_get_status(packet)) {
  254. printf("RFCOMM channel open failed, status %u\n", rfcomm_event_channel_opened_get_status(packet));
  255. } else {
  256. rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
  257. rfcomm_mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
  258. printf("RFCOMM channel open succeeded. New RFCOMM Channel ID %u, max frame size %u\n", rfcomm_cid, rfcomm_mtu);
  259. spp_test_data_len = rfcomm_mtu;
  260. if (spp_test_data_len > sizeof(test_data)){
  261. spp_test_data_len = sizeof(test_data);
  262. }
  263. // disable page/inquiry scan to get max performance
  264. gap_discoverable_control(0);
  265. gap_connectable_control(0);
  266. // disable advertisements
  267. gap_advertisements_enable(0);
  268. test_reset();
  269. rfcomm_request_can_send_now_event(rfcomm_cid);
  270. }
  271. break;
  272. case RFCOMM_EVENT_CAN_SEND_NOW:
  273. spp_send_packet();
  274. break;
  275. case RFCOMM_EVENT_CHANNEL_CLOSED:
  276. printf("RFCOMM channel closed\n");
  277. rfcomm_cid = 0;
  278. break;
  279. default:
  280. break;
  281. }
  282. break;
  283. case RFCOMM_DATA_PACKET:
  284. test_track_transferred(size);
  285. #if 0
  286. printf("RCV: '");
  287. for (i=0;i<size;i++){
  288. putchar(packet[i]);
  289. }
  290. printf("'\n");
  291. #endif
  292. break;
  293. default:
  294. break;
  295. }
  296. }
  297. /*
  298. * @section ATT Packet Handler
  299. *
  300. * @text The packet handler is used to track the ATT MTU Exchange and trigger ATT send
  301. */
  302. /* LISTING_START(attPacketHandler): Packet Handler */
  303. static void att_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  304. UNUSED(channel);
  305. UNUSED(size);
  306. switch (packet_type) {
  307. case HCI_EVENT_PACKET:
  308. switch (hci_event_packet_get_type(packet)) {
  309. case ATT_EVENT_CONNECTED:
  310. le_connection_handle = att_event_connected_get_handle(packet);
  311. att_mtu = att_server_get_mtu(le_connection_handle);
  312. le_test_data_len = btstack_min(att_server_get_mtu(le_connection_handle) - 3, sizeof(test_data));
  313. printf("ATT MTU = %u\n", att_mtu);
  314. break;
  315. case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
  316. att_mtu = att_event_mtu_exchange_complete_get_MTU(packet);
  317. le_test_data_len = btstack_min(att_mtu - 3, sizeof(test_data));
  318. printf("ATT MTU = %u\n", att_mtu);
  319. break;
  320. case ATT_EVENT_CAN_SEND_NOW:
  321. le_streamer();
  322. break;
  323. case ATT_EVENT_DISCONNECTED:
  324. le_notification_enabled = 0;
  325. le_connection_handle = HCI_CON_HANDLE_INVALID;
  326. break;
  327. }
  328. }
  329. }
  330. // ATT Client Read Callback for Dynamic Data
  331. // - if buffer == NULL, don't copy data, just return size of value
  332. // - if buffer != NULL, copy data and return number bytes copied
  333. // @param offset defines start of attribute value
  334. static uint16_t att_read_callback(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
  335. UNUSED(con_handle);
  336. UNUSED(att_handle);
  337. UNUSED(offset);
  338. UNUSED(buffer);
  339. UNUSED(buffer_size);
  340. return 0;
  341. }
  342. // write requests
  343. static int att_write_callback(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size){
  344. UNUSED(con_handle);
  345. UNUSED(offset);
  346. UNUSED(buffer_size);
  347. // printf("att_write_callback att_handle %04x, transaction mode %u\n", att_handle, transaction_mode);
  348. if (transaction_mode != ATT_TRANSACTION_MODE_NONE) return 0;
  349. switch(att_handle){
  350. case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
  351. le_notification_enabled = little_endian_read_16(buffer, 0) == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION;
  352. printf("Notifications enabled %u\n", le_notification_enabled);
  353. if (le_notification_enabled){
  354. att_server_request_can_send_now_event(le_connection_handle);
  355. }
  356. // disable page/inquiry scan to get max performance
  357. gap_discoverable_control(0);
  358. gap_connectable_control(0);
  359. test_reset();
  360. break;
  361. default:
  362. break;
  363. }
  364. return 0;
  365. }
  366. /*
  367. * @section Main Application Setup
  368. *
  369. * @text As with the packet and the heartbeat handlers, the combined app setup contains the code from the individual example setups.
  370. */
  371. /* LISTING_START(MainConfiguration): Init L2CAP RFCOMM SDO SM ATT Server and start heartbeat timer */
  372. int btstack_main(int argc, const char * argv[])
  373. {
  374. UNUSED(argc);
  375. (void)argv;
  376. l2cap_init();
  377. rfcomm_init();
  378. rfcomm_register_service(rfcomm_packet_handler, RFCOMM_SERVER_CHANNEL, 0xffff);
  379. // init SDP, create record for SPP and register with SDP
  380. sdp_init();
  381. memset(spp_service_buffer, 0, sizeof(spp_service_buffer));
  382. spp_create_sdp_record(spp_service_buffer, 0x10001, RFCOMM_SERVER_CHANNEL, "SPP Streamer");
  383. sdp_register_service(spp_service_buffer);
  384. #ifdef ENABLE_GATT_OVER_CLASSIC
  385. // init SDP, create record for GATT and register with SDP
  386. memset(gatt_service_buffer, 0, sizeof(gatt_service_buffer));
  387. gatt_create_sdp_record(gatt_service_buffer, 0x10001, ATT_SERVICE_GATT_SERVICE_START_HANDLE, ATT_SERVICE_GATT_SERVICE_END_HANDLE);
  388. sdp_register_service(gatt_service_buffer);
  389. #endif
  390. gap_set_local_name("SPP and LE Streamer 00:00:00:00:00:00");
  391. gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
  392. // short-cut to find other SPP Streamer
  393. gap_set_class_of_device(TEST_COD);
  394. gap_discoverable_control(1);
  395. // setup le device db
  396. le_device_db_init();
  397. // setup SM: Display only
  398. sm_init();
  399. // setup ATT server
  400. att_server_init(profile_data, att_read_callback, att_write_callback);
  401. // register for HCI events
  402. hci_event_callback_registration.callback = &hci_packet_handler;
  403. hci_add_event_handler(&hci_event_callback_registration);
  404. // register for ATT events
  405. att_server_register_packet_handler(att_packet_handler);
  406. // setup advertisements
  407. uint16_t adv_int_min = 0x0030;
  408. uint16_t adv_int_max = 0x0030;
  409. uint8_t adv_type = 0;
  410. bd_addr_t null_addr;
  411. memset(null_addr, 0, 6);
  412. gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
  413. gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
  414. gap_advertisements_enable(1);
  415. spp_create_test_data();
  416. // turn on!
  417. hci_power_control(HCI_POWER_ON);
  418. return 0;
  419. }
  420. /* LISTING_END */
  421. /* EXAMPLE_END */