gatt_streamer_server.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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__ "gatt_streamer.c"
  38. // *****************************************************************************
  39. /* EXAMPLE_START(le_streamer): LE Streamer - Stream data over GATT.
  40. *
  41. * @text All newer operating systems provide GATT Client functionality.
  42. * This example shows how to get a maximal throughput via BLE:
  43. * - send whenever possible,
  44. * - use the max ATT MTU.
  45. *
  46. * @text In theory, we should also update the connection parameters, but we already get
  47. * a connection interval of 30 ms and there's no public way to use a shorter
  48. * interval with iOS (if we're not implementing an HID device).
  49. *
  50. * @text Note: To start the streaming, run the example.
  51. * On remote device use some GATT Explorer, e.g. LightBlue, BLExplr to enable notifications.
  52. */
  53. // *****************************************************************************
  54. #include <inttypes.h>
  55. #include <stdint.h>
  56. #include <stdio.h>
  57. #include <stdlib.h>
  58. #include <string.h>
  59. #include "btstack.h"
  60. // le_streamer.gatt contains the declaration of the provided GATT Services + Characteristics
  61. // le_streamer.h contains the binary representation of le_streamer.gatt
  62. // it is generated by the build system by calling: $BTSTACK_ROOT/tool/compile_gatt.py le_streamer.gatt le_streamer.h
  63. // it needs to be regenerated when the GATT Database declared in le_streamer.gatt file is modified
  64. #include "gatt_streamer_server.h"
  65. #define REPORT_INTERVAL_MS 3000
  66. #define MAX_NR_CONNECTIONS 3
  67. static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
  68. static void att_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
  69. 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);
  70. static void streamer(void);
  71. const uint8_t adv_data[] = {
  72. // Flags general discoverable, BR/EDR not supported
  73. 0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
  74. // Name
  75. 0x0c, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'L', 'E', ' ', 'S', 't', 'r', 'e', 'a', 'm', 'e', 'r',
  76. // Incomplete List of 16-bit Service Class UUIDs -- FF10 - only valid for testing!
  77. 0x03, BLUETOOTH_DATA_TYPE_INCOMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, 0x10, 0xff,
  78. };
  79. const uint8_t adv_data_len = sizeof(adv_data);
  80. static btstack_packet_callback_registration_t hci_event_callback_registration;
  81. // support for multiple clients
  82. typedef struct {
  83. char name;
  84. int le_notification_enabled;
  85. uint16_t value_handle;
  86. hci_con_handle_t connection_handle;
  87. int counter;
  88. char test_data[200];
  89. int test_data_len;
  90. uint32_t test_data_sent;
  91. uint32_t test_data_start;
  92. } le_streamer_connection_t;
  93. static le_streamer_connection_t le_streamer_connections[MAX_NR_CONNECTIONS];
  94. // round robin sending
  95. static int connection_index;
  96. #ifdef ENABLE_GATT_OVER_CLASSIC
  97. static uint8_t gatt_service_buffer[70];
  98. #endif
  99. static void init_connections(void){
  100. // track connections
  101. int i;
  102. for (i=0;i<MAX_NR_CONNECTIONS;i++){
  103. le_streamer_connections[i].connection_handle = HCI_CON_HANDLE_INVALID;
  104. le_streamer_connections[i].name = 'A' + i;
  105. }
  106. }
  107. static le_streamer_connection_t * connection_for_conn_handle(hci_con_handle_t conn_handle){
  108. int i;
  109. for (i=0;i<MAX_NR_CONNECTIONS;i++){
  110. if (le_streamer_connections[i].connection_handle == conn_handle) return &le_streamer_connections[i];
  111. }
  112. return NULL;
  113. }
  114. static void next_connection_index(void){
  115. connection_index++;
  116. if (connection_index == MAX_NR_CONNECTIONS){
  117. connection_index = 0;
  118. }
  119. }
  120. /* @section Main Application Setup
  121. *
  122. * @text Listing MainConfiguration shows main application code.
  123. * It initializes L2CAP, the Security Manager, and configures the ATT Server with the pre-compiled
  124. * ATT Database generated from $le_streamer.gatt$. Finally, it configures the advertisements
  125. * and boots the Bluetooth stack.
  126. */
  127. /* LISTING_START(MainConfiguration): Init L2CAP, SM, ATT Server, and enable advertisements */
  128. static void le_streamer_setup(void){
  129. l2cap_init();
  130. // setup le device db
  131. le_device_db_init();
  132. // setup SM: Display only
  133. sm_init();
  134. #ifdef ENABLE_GATT_OVER_CLASSIC
  135. // init SDP, create record for GATT and register with SDP
  136. sdp_init();
  137. memset(gatt_service_buffer, 0, sizeof(gatt_service_buffer));
  138. gatt_create_sdp_record(gatt_service_buffer, 0x10001, ATT_SERVICE_GATT_SERVICE_START_HANDLE, ATT_SERVICE_GATT_SERVICE_END_HANDLE);
  139. sdp_register_service(gatt_service_buffer);
  140. printf("SDP service record size: %u\n", de_get_len(gatt_service_buffer));
  141. // configure Classic GAP
  142. gap_set_local_name("GATT Streamer BR/EDR 00:00:00:00:00:00");
  143. gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
  144. gap_discoverable_control(1);
  145. #endif
  146. // setup ATT server
  147. att_server_init(profile_data, NULL, att_write_callback);
  148. // register for HCI events
  149. hci_event_callback_registration.callback = &hci_packet_handler;
  150. hci_add_event_handler(&hci_event_callback_registration);
  151. // register for ATT events
  152. att_server_register_packet_handler(att_packet_handler);
  153. // setup advertisements
  154. uint16_t adv_int_min = 0x0030;
  155. uint16_t adv_int_max = 0x0030;
  156. uint8_t adv_type = 0;
  157. bd_addr_t null_addr;
  158. memset(null_addr, 0, 6);
  159. gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
  160. gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
  161. gap_advertisements_enable(1);
  162. // init client state
  163. init_connections();
  164. }
  165. /* LISTING_END */
  166. /*
  167. * @section Track throughput
  168. * @text We calculate the throughput by setting a start time and measuring the amount of
  169. * data sent. After a configurable REPORT_INTERVAL_MS, we print the throughput in kB/s
  170. * and reset the counter and start time.
  171. */
  172. /* LISTING_START(tracking): Tracking throughput */
  173. static void test_reset(le_streamer_connection_t * context){
  174. context->test_data_start = btstack_run_loop_get_time_ms();
  175. context->test_data_sent = 0;
  176. }
  177. static void test_track_sent(le_streamer_connection_t * context, int bytes_sent){
  178. context->test_data_sent += bytes_sent;
  179. // evaluate
  180. uint32_t now = btstack_run_loop_get_time_ms();
  181. uint32_t time_passed = now - context->test_data_start;
  182. if (time_passed < REPORT_INTERVAL_MS) return;
  183. // print speed
  184. int bytes_per_second = context->test_data_sent * 1000 / time_passed;
  185. printf("%c: %"PRIu32" bytes sent-> %u.%03u kB/s\n", context->name, context->test_data_sent, bytes_per_second / 1000, bytes_per_second % 1000);
  186. // restart
  187. context->test_data_start = now;
  188. context->test_data_sent = 0;
  189. }
  190. /* LISTING_END(tracking): Tracking throughput */
  191. /*
  192. * @section HCI Packet Handler
  193. *
  194. * @text The packet handler is used track incoming connections and to stop notifications on disconnect
  195. * It is also a good place to request the connection parameter update as indicated
  196. * in the commented code block.
  197. */
  198. /* LISTING_START(hciPacketHandler): Packet Handler */
  199. static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  200. UNUSED(channel);
  201. UNUSED(size);
  202. uint16_t conn_interval;
  203. hci_con_handle_t con_handle;
  204. switch (packet_type) {
  205. case HCI_EVENT_PACKET:
  206. switch (hci_event_packet_get_type(packet)) {
  207. case BTSTACK_EVENT_STATE:
  208. // BTstack activated, get started
  209. if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING) {
  210. printf("To start the streaming, please run the le_streamer_client example on other device, or use some GATT Explorer, e.g. LightBlue, BLExplr.\n");
  211. }
  212. break;
  213. case HCI_EVENT_DISCONNECTION_COMPLETE:
  214. con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
  215. printf("- LE Connection %04x: disconnect, reason %02x\n", con_handle, hci_event_disconnection_complete_get_reason(packet));
  216. break;
  217. case HCI_EVENT_LE_META:
  218. switch (hci_event_le_meta_get_subevent_code(packet)) {
  219. case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
  220. // print connection parameters (without using float operations)
  221. con_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
  222. conn_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
  223. printf("- LE Connection %04x: connected - connection interval %u.%02u ms, latency %u\n", con_handle, conn_interval * 125 / 100,
  224. 25 * (conn_interval & 3), hci_subevent_le_connection_complete_get_conn_latency(packet));
  225. // request min con interval 15 ms for iOS 11+
  226. printf("- LE Connection %04x: request 15 ms connection interval\n", con_handle);
  227. gap_request_connection_parameter_update(con_handle, 12, 12, 0, 0x0048);
  228. break;
  229. case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
  230. // print connection parameters (without using float operations)
  231. con_handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
  232. conn_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
  233. printf("- LE Connection %04x: connection update - connection interval %u.%02u ms, latency %u\n", con_handle, conn_interval * 125 / 100,
  234. 25 * (conn_interval & 3), hci_subevent_le_connection_update_complete_get_conn_latency(packet));
  235. break;
  236. default:
  237. break;
  238. }
  239. break;
  240. default:
  241. break;
  242. }
  243. }
  244. }
  245. /* LISTING_END */
  246. /*
  247. * @section ATT Packet Handler
  248. *
  249. * @text The packet handler is used to track the ATT MTU Exchange and trigger ATT send
  250. */
  251. /* LISTING_START(attPacketHandler): Packet Handler */
  252. static void att_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  253. UNUSED(channel);
  254. UNUSED(size);
  255. int mtu;
  256. le_streamer_connection_t * context;
  257. switch (packet_type) {
  258. case HCI_EVENT_PACKET:
  259. switch (hci_event_packet_get_type(packet)) {
  260. case ATT_EVENT_CONNECTED:
  261. // setup new
  262. context = connection_for_conn_handle(HCI_CON_HANDLE_INVALID);
  263. if (!context) break;
  264. context->counter = 'A';
  265. context->connection_handle = att_event_connected_get_handle(packet);
  266. context->test_data_len = btstack_min(att_server_get_mtu(context->connection_handle) - 3, sizeof(context->test_data));
  267. printf("%c: ATT connected, handle %04x, test data len %u\n", context->name, context->connection_handle, context->test_data_len);
  268. break;
  269. case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
  270. mtu = att_event_mtu_exchange_complete_get_MTU(packet) - 3;
  271. context = connection_for_conn_handle(att_event_mtu_exchange_complete_get_handle(packet));
  272. if (!context) break;
  273. context->test_data_len = btstack_min(mtu - 3, sizeof(context->test_data));
  274. printf("%c: ATT MTU = %u => use test data of len %u\n", context->name, mtu, context->test_data_len);
  275. break;
  276. case ATT_EVENT_CAN_SEND_NOW:
  277. streamer();
  278. break;
  279. case ATT_EVENT_DISCONNECTED:
  280. context = connection_for_conn_handle(att_event_disconnected_get_handle(packet));
  281. if (!context) break;
  282. // free connection
  283. printf("%c: ATT disconnected, handle %04x\n", context->name, context->connection_handle);
  284. context->le_notification_enabled = 0;
  285. context->connection_handle = HCI_CON_HANDLE_INVALID;
  286. break;
  287. default:
  288. break;
  289. }
  290. break;
  291. default:
  292. break;
  293. }
  294. }
  295. /* LISTING_END */
  296. /*
  297. * @section Streamer
  298. *
  299. * @text The streamer function checks if notifications are enabled and if a notification can be sent now.
  300. * It creates some test data - a single letter that gets increased every time - and tracks the data sent.
  301. */
  302. /* LISTING_START(streamer): Streaming code */
  303. static void streamer(void){
  304. // find next active streaming connection
  305. int old_connection_index = connection_index;
  306. while (1){
  307. // active found?
  308. if ((le_streamer_connections[connection_index].connection_handle != HCI_CON_HANDLE_INVALID) &&
  309. (le_streamer_connections[connection_index].le_notification_enabled)) break;
  310. // check next
  311. next_connection_index();
  312. // none found
  313. if (connection_index == old_connection_index) return;
  314. }
  315. le_streamer_connection_t * context = &le_streamer_connections[connection_index];
  316. // create test data
  317. context->counter++;
  318. if (context->counter > 'Z') context->counter = 'A';
  319. memset(context->test_data, context->counter, context->test_data_len);
  320. // send
  321. att_server_notify(context->connection_handle, context->value_handle, (uint8_t*) context->test_data, context->test_data_len);
  322. // track
  323. test_track_sent(context, context->test_data_len);
  324. // request next send event
  325. att_server_request_can_send_now_event(context->connection_handle);
  326. // check next
  327. next_connection_index();
  328. }
  329. /* LISTING_END */
  330. /*
  331. * @section ATT Write
  332. *
  333. * @text The only valid ATT write in this example is to the Client Characteristic Configuration, which configures notification
  334. * and indication. If the ATT handle matches the client configuration handle, the new configuration value is stored.
  335. * If notifications get enabled, an ATT_EVENT_CAN_SEND_NOW is requested. See Listing attWrite.
  336. */
  337. /* LISTING_START(attWrite): ATT Write */
  338. 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){
  339. UNUSED(offset);
  340. // printf("att_write_callback att_handle %04x, transaction mode %u\n", att_handle, transaction_mode);
  341. if (transaction_mode != ATT_TRANSACTION_MODE_NONE) return 0;
  342. le_streamer_connection_t * context = connection_for_conn_handle(con_handle);
  343. switch(att_handle){
  344. case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
  345. case ATT_CHARACTERISTIC_0000FF12_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
  346. context->le_notification_enabled = little_endian_read_16(buffer, 0) == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION;
  347. printf("%c: Notifications enabled %u\n", context->name, context->le_notification_enabled);
  348. if (context->le_notification_enabled){
  349. switch (att_handle){
  350. case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
  351. context->value_handle = ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE;
  352. break;
  353. case ATT_CHARACTERISTIC_0000FF12_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
  354. context->value_handle = ATT_CHARACTERISTIC_0000FF12_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE;
  355. break;
  356. default:
  357. break;
  358. }
  359. att_server_request_can_send_now_event(context->connection_handle);
  360. }
  361. test_reset(context);
  362. break;
  363. case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE:
  364. case ATT_CHARACTERISTIC_0000FF12_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE:
  365. test_track_sent(context, buffer_size);
  366. break;
  367. default:
  368. printf("Write to 0x%04x, len %u\n", att_handle, buffer_size);
  369. }
  370. return 0;
  371. }
  372. /* LISTING_END */
  373. int btstack_main(void);
  374. int btstack_main(void)
  375. {
  376. le_streamer_setup();
  377. // turn on!
  378. hci_power_control(HCI_POWER_ON);
  379. return 0;
  380. }
  381. /* EXAMPLE_END */