le_streamer_client.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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__ "le_streamer_client.c"
  38. /*
  39. * le_streamer_client.c
  40. */
  41. // *****************************************************************************
  42. /* EXAMPLE_START(le_streamer_client): Connects to 'LE Streamer' and subscribes to test characteristic
  43. */
  44. // *****************************************************************************
  45. #include <inttypes.h>
  46. #include <stdint.h>
  47. #include <stdio.h>
  48. #include <stdlib.h>
  49. #include <string.h>
  50. #include "btstack.h"
  51. // prototypes
  52. static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
  53. typedef enum {
  54. TC_OFF,
  55. TC_IDLE,
  56. TC_W4_SCAN_RESULT,
  57. TC_W4_CONNECT,
  58. TC_W4_SERVICE_RESULT,
  59. TC_W4_CHARACTERISTIC_RX_RESULT,
  60. TC_W4_CHARACTERISTIC_TX_RESULT,
  61. TC_W4_ENABLE_NOTIFICATIONS_COMPLETE,
  62. TC_W4_TEST_DATA
  63. } gc_state_t;
  64. static bd_addr_t cmdline_addr;
  65. static int cmdline_addr_found = 0;
  66. // addr and type of device with correct name
  67. static bd_addr_t le_streamer_addr;
  68. static bd_addr_type_t le_streamer_addr_type;
  69. static hci_con_handle_t connection_handle;
  70. // On the GATT Server, RX Characteristic is used for receive data via Write, and TX Characteristic is used to send data via Notifications
  71. static uint8_t le_streamer_service_uuid[16] = { 0x00, 0x00, 0xFF, 0x10, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
  72. static uint8_t le_streamer_characteristic_rx_uuid[16] = { 0x00, 0x00, 0xFF, 0x11, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
  73. static uint8_t le_streamer_characteristic_tx_uuid[16] = { 0x00, 0x00, 0xFF, 0x12, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
  74. static gatt_client_service_t le_streamer_service;
  75. static gatt_client_characteristic_t le_streamer_characteristic_rx;
  76. static gatt_client_characteristic_t le_streamer_characteristic_tx;
  77. static gatt_client_notification_t notification_listener;
  78. static int listener_registered;
  79. static gc_state_t state = TC_OFF;
  80. static btstack_packet_callback_registration_t hci_event_callback_registration;
  81. /*
  82. * @section Track throughput
  83. * @text We calculate the throughput by setting a start time and measuring the amount of
  84. * data sent. After a configurable REPORT_INTERVAL_MS, we print the throughput in kB/s
  85. * and reset the counter and start time.
  86. */
  87. /* LISTING_START(tracking): Tracking throughput */
  88. #define TEST_MODE_WRITE_WITHOUT_RESPONSE 1
  89. #define TEST_MODE_ENABLE_NOTIFICATIONS 2
  90. #define TEST_MODE_DUPLEX 3
  91. // configure test mode: send only, receive only, full duplex
  92. #define TEST_MODE TEST_MODE_DUPLEX
  93. #define REPORT_INTERVAL_MS 3000
  94. // support for multiple clients
  95. typedef struct {
  96. char name;
  97. int le_notification_enabled;
  98. int counter;
  99. char test_data[200];
  100. int test_data_len;
  101. uint32_t test_data_sent;
  102. uint32_t test_data_start;
  103. } le_streamer_connection_t;
  104. static le_streamer_connection_t le_streamer_connection;
  105. static void test_reset(le_streamer_connection_t * context){
  106. context->test_data_start = btstack_run_loop_get_time_ms();
  107. context->test_data_sent = 0;
  108. }
  109. static void test_track_data(le_streamer_connection_t * context, int bytes_sent){
  110. context->test_data_sent += bytes_sent;
  111. // evaluate
  112. uint32_t now = btstack_run_loop_get_time_ms();
  113. uint32_t time_passed = now - context->test_data_start;
  114. if (time_passed < REPORT_INTERVAL_MS) return;
  115. // print speed
  116. int bytes_per_second = context->test_data_sent * 1000 / time_passed;
  117. printf("%c: %"PRIu32" bytes -> %u.%03u kB/s\n", context->name, context->test_data_sent, bytes_per_second / 1000, bytes_per_second % 1000);
  118. // restart
  119. context->test_data_start = now;
  120. context->test_data_sent = 0;
  121. }
  122. /* LISTING_END(tracking): Tracking throughput */
  123. // stramer
  124. static void streamer(le_streamer_connection_t * context){
  125. if (connection_handle == HCI_CON_HANDLE_INVALID) return;
  126. // create test data
  127. context->counter++;
  128. if (context->counter > 'Z') context->counter = 'A';
  129. memset(context->test_data, context->counter, context->test_data_len);
  130. // send
  131. uint8_t status = gatt_client_write_value_of_characteristic_without_response(connection_handle, le_streamer_characteristic_rx.value_handle, context->test_data_len, (uint8_t*) context->test_data);
  132. if (status){
  133. printf("error %02x for write without response!\n", status);
  134. return;
  135. } else {
  136. test_track_data(&le_streamer_connection, context->test_data_len);
  137. }
  138. // request again
  139. gatt_client_request_can_write_without_response_event(handle_gatt_client_event, connection_handle);
  140. }
  141. // returns 1 if name is found in advertisement
  142. static int advertisement_report_contains_name(const char * name, uint8_t * advertisement_report){
  143. // get advertisement from report event
  144. const uint8_t * adv_data = gap_event_advertising_report_get_data(advertisement_report);
  145. uint16_t adv_len = gap_event_advertising_report_get_data_length(advertisement_report);
  146. int name_len = strlen(name);
  147. // iterate over advertisement data
  148. ad_context_t context;
  149. for (ad_iterator_init(&context, adv_len, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
  150. uint8_t data_type = ad_iterator_get_data_type(&context);
  151. uint8_t data_size = ad_iterator_get_data_len(&context);
  152. const uint8_t * data = ad_iterator_get_data(&context);
  153. int i;
  154. switch (data_type){
  155. case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
  156. case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
  157. // compare common prefix
  158. for (i=0; i<data_size && i<name_len;i++){
  159. if (data[i] != name[i]) break;
  160. }
  161. // prefix match
  162. return 1;
  163. default:
  164. break;
  165. }
  166. }
  167. return 0;
  168. }
  169. static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  170. UNUSED(packet_type);
  171. UNUSED(channel);
  172. UNUSED(size);
  173. uint16_t mtu;
  174. switch(state){
  175. case TC_W4_SERVICE_RESULT:
  176. switch(hci_event_packet_get_type(packet)){
  177. case GATT_EVENT_SERVICE_QUERY_RESULT:
  178. // store service (we expect only one)
  179. gatt_event_service_query_result_get_service(packet, &le_streamer_service);
  180. break;
  181. case GATT_EVENT_QUERY_COMPLETE:
  182. if (packet[4] != 0){
  183. printf("SERVICE_QUERY_RESULT - Error status %x.\n", packet[4]);
  184. gap_disconnect(connection_handle);
  185. break;
  186. }
  187. // service query complete, look for characteristic
  188. state = TC_W4_CHARACTERISTIC_RX_RESULT;
  189. printf("Search for LE Streamer RX characteristic.\n");
  190. gatt_client_discover_characteristics_for_service_by_uuid128(handle_gatt_client_event, connection_handle, &le_streamer_service, le_streamer_characteristic_rx_uuid);
  191. break;
  192. default:
  193. break;
  194. }
  195. break;
  196. case TC_W4_CHARACTERISTIC_RX_RESULT:
  197. switch(hci_event_packet_get_type(packet)){
  198. case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
  199. gatt_event_characteristic_query_result_get_characteristic(packet, &le_streamer_characteristic_rx);
  200. break;
  201. case GATT_EVENT_QUERY_COMPLETE:
  202. if (packet[4] != 0){
  203. printf("CHARACTERISTIC_QUERY_RESULT - Error status %x.\n", packet[4]);
  204. gap_disconnect(connection_handle);
  205. break;
  206. }
  207. // rx characteristiic found, look for tx characteristic
  208. state = TC_W4_CHARACTERISTIC_TX_RESULT;
  209. printf("Search for LE Streamer TX characteristic.\n");
  210. gatt_client_discover_characteristics_for_service_by_uuid128(handle_gatt_client_event, connection_handle, &le_streamer_service, le_streamer_characteristic_tx_uuid);
  211. break;
  212. default:
  213. break;
  214. }
  215. break;
  216. case TC_W4_CHARACTERISTIC_TX_RESULT:
  217. switch(hci_event_packet_get_type(packet)){
  218. case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
  219. gatt_event_characteristic_query_result_get_characteristic(packet, &le_streamer_characteristic_tx);
  220. break;
  221. case GATT_EVENT_QUERY_COMPLETE:
  222. if (packet[4] != 0){
  223. printf("CHARACTERISTIC_QUERY_RESULT - Error status %x.\n", packet[4]);
  224. gap_disconnect(connection_handle);
  225. break;
  226. }
  227. // register handler for notifications
  228. listener_registered = 1;
  229. gatt_client_listen_for_characteristic_value_updates(&notification_listener, handle_gatt_client_event, connection_handle, &le_streamer_characteristic_tx);
  230. // setup tracking
  231. le_streamer_connection.name = 'A';
  232. le_streamer_connection.test_data_len = ATT_DEFAULT_MTU - 3;
  233. test_reset(&le_streamer_connection);
  234. gatt_client_get_mtu(connection_handle, &mtu);
  235. le_streamer_connection.test_data_len = btstack_min(mtu - 3, sizeof(le_streamer_connection.test_data));
  236. printf("%c: ATT MTU = %u => use test data of len %u\n", le_streamer_connection.name, mtu, le_streamer_connection.test_data_len);
  237. // enable notifications
  238. #if (TEST_MODE & TEST_MODE_ENABLE_NOTIFICATIONS)
  239. printf("Start streaming - enable notify on test characteristic.\n");
  240. state = TC_W4_ENABLE_NOTIFICATIONS_COMPLETE;
  241. gatt_client_write_client_characteristic_configuration(handle_gatt_client_event, connection_handle,
  242. &le_streamer_characteristic_tx, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
  243. break;
  244. #endif
  245. state = TC_W4_TEST_DATA;
  246. #if (TEST_MODE & TEST_MODE_WRITE_WITHOUT_RESPONSE)
  247. printf("Start streaming - request can send now.\n");
  248. gatt_client_request_can_write_without_response_event(handle_gatt_client_event, connection_handle);
  249. #endif
  250. break;
  251. default:
  252. break;
  253. }
  254. break;
  255. case TC_W4_ENABLE_NOTIFICATIONS_COMPLETE:
  256. switch(hci_event_packet_get_type(packet)){
  257. case GATT_EVENT_QUERY_COMPLETE:
  258. printf("Notifications enabled, ATT status %02x\n", gatt_event_query_complete_get_att_status(packet));
  259. if (gatt_event_query_complete_get_att_status(packet) != ATT_ERROR_SUCCESS) break;
  260. state = TC_W4_TEST_DATA;
  261. #if (TEST_MODE & TEST_MODE_WRITE_WITHOUT_RESPONSE)
  262. printf("Start streaming - request can send now.\n");
  263. gatt_client_request_can_write_without_response_event(handle_gatt_client_event, connection_handle);
  264. #endif
  265. break;
  266. default:
  267. break;
  268. }
  269. break;
  270. case TC_W4_TEST_DATA:
  271. switch(hci_event_packet_get_type(packet)){
  272. case GATT_EVENT_NOTIFICATION:
  273. test_track_data(&le_streamer_connection, gatt_event_notification_get_value_length(packet));
  274. break;
  275. case GATT_EVENT_QUERY_COMPLETE:
  276. break;
  277. case GATT_EVENT_CAN_WRITE_WITHOUT_RESPONSE:
  278. streamer(&le_streamer_connection);
  279. break;
  280. default:
  281. printf("Unknown packet type %x\n", hci_event_packet_get_type(packet));
  282. break;
  283. }
  284. break;
  285. default:
  286. printf("error\n");
  287. break;
  288. }
  289. }
  290. // Either connect to remote specified on command line or start scan for device with "LE Streamer" in advertisement
  291. static void le_streamer_client_start(void){
  292. if (cmdline_addr_found){
  293. printf("Connect to %s\n", bd_addr_to_str(cmdline_addr));
  294. state = TC_W4_CONNECT;
  295. gap_connect(cmdline_addr, 0);
  296. } else {
  297. printf("Start scanning!\n");
  298. state = TC_W4_SCAN_RESULT;
  299. gap_set_scan_parameters(0,0x0030, 0x0030);
  300. gap_start_scan();
  301. }
  302. }
  303. static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  304. UNUSED(channel);
  305. UNUSED(size);
  306. if (packet_type != HCI_EVENT_PACKET) return;
  307. uint16_t conn_interval;
  308. uint8_t event = hci_event_packet_get_type(packet);
  309. switch (event) {
  310. case BTSTACK_EVENT_STATE:
  311. // BTstack activated, get started
  312. if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING) {
  313. le_streamer_client_start();
  314. } else {
  315. state = TC_OFF;
  316. }
  317. break;
  318. case GAP_EVENT_ADVERTISING_REPORT:
  319. if (state != TC_W4_SCAN_RESULT) return;
  320. // check name in advertisement
  321. if (!advertisement_report_contains_name("LE Streamer", packet)) return;
  322. // store address and type
  323. gap_event_advertising_report_get_address(packet, le_streamer_addr);
  324. le_streamer_addr_type = gap_event_advertising_report_get_address_type(packet);
  325. // stop scanning, and connect to the device
  326. state = TC_W4_CONNECT;
  327. gap_stop_scan();
  328. printf("Stop scan. Connect to device with addr %s.\n", bd_addr_to_str(le_streamer_addr));
  329. gap_connect(le_streamer_addr,le_streamer_addr_type);
  330. break;
  331. case HCI_EVENT_LE_META:
  332. // wait for connection complete
  333. if (hci_event_le_meta_get_subevent_code(packet) != HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
  334. if (state != TC_W4_CONNECT) return;
  335. connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
  336. // print connection parameters (without using float operations)
  337. conn_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
  338. printf("Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
  339. printf("Connection Latency: %u\n", hci_subevent_le_connection_complete_get_conn_latency(packet));
  340. // initialize gatt client context with handle, and add it to the list of active clients
  341. // query primary services
  342. printf("Search for LE Streamer service.\n");
  343. state = TC_W4_SERVICE_RESULT;
  344. gatt_client_discover_primary_services_by_uuid128(handle_gatt_client_event, connection_handle, le_streamer_service_uuid);
  345. break;
  346. case HCI_EVENT_DISCONNECTION_COMPLETE:
  347. // unregister listener
  348. connection_handle = HCI_CON_HANDLE_INVALID;
  349. if (listener_registered){
  350. listener_registered = 0;
  351. gatt_client_stop_listening_for_characteristic_value_updates(&notification_listener);
  352. }
  353. if (cmdline_addr_found){
  354. printf("Disconnected %s\n", bd_addr_to_str(cmdline_addr));
  355. return;
  356. }
  357. printf("Disconnected %s\n", bd_addr_to_str(le_streamer_addr));
  358. if (state == TC_OFF) break;
  359. le_streamer_client_start();
  360. break;
  361. default:
  362. break;
  363. }
  364. }
  365. #ifdef HAVE_BTSTACK_STDIN
  366. static void usage(const char *name){
  367. fprintf(stderr, "Usage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", name);
  368. fprintf(stderr, "If no argument is provided, LE Streamer Client will start scanning and connect to the first device named 'LE Streamer'.\n");
  369. fprintf(stderr, "To connect to a specific device use argument [-a].\n\n");
  370. }
  371. #endif
  372. int btstack_main(int argc, const char * argv[]);
  373. int btstack_main(int argc, const char * argv[]){
  374. #ifdef HAVE_BTSTACK_STDIN
  375. int arg = 1;
  376. cmdline_addr_found = 0;
  377. while (arg < argc) {
  378. if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
  379. arg++;
  380. cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
  381. arg++;
  382. if (!cmdline_addr_found) exit(1);
  383. continue;
  384. }
  385. usage(argv[0]);
  386. return 0;
  387. }
  388. #else
  389. (void)argc;
  390. (void)argv;
  391. #endif
  392. l2cap_init();
  393. sm_init();
  394. sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
  395. // sm_init needed before gatt_client_init
  396. gatt_client_init();
  397. hci_event_callback_registration.callback = &hci_event_handler;
  398. hci_add_event_handler(&hci_event_callback_registration);
  399. // use different connection parameters: conn interval min/max (* 1.25 ms), slave latency, supervision timeout, CE len min/max (* 0.6125 ms)
  400. // gap_set_connection_parameters(0x06, 0x06, 4, 1000, 0x01, 0x06 * 2);
  401. // turn on!
  402. hci_power_control(HCI_POWER_ON);
  403. return 0;
  404. }
  405. /* EXAMPLE_END */