gatt_browser.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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_browser.c"
  38. // *****************************************************************************
  39. /* EXAMPLE_START(gatt_browser): GATT Client - Discovering primary services and their characteristics
  40. *
  41. * @text This example shows how to use the GATT Client
  42. * API to discover primary services and their characteristics of the first found
  43. * device that is advertising its services.
  44. *
  45. * The logic is divided between the HCI and GATT client packet handlers.
  46. * The HCI packet handler is responsible for finding a remote device,
  47. * connecting to it, and for starting the first GATT client query.
  48. * Then, the GATT client packet handler receives all primary services and
  49. * requests the characteristics of the last one to keep the example short.
  50. *
  51. */
  52. // *****************************************************************************
  53. #include <stdint.h>
  54. #include <stdio.h>
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include "btstack.h"
  58. // gatt_browser.gatt contains the declaration of the provided GATT Services + Characteristics
  59. // gatt_browser.h contains the binary representation of gatt_browser.gatt
  60. // it is generated by the build system by calling: $BTSTACK_ROOT/tool/compile_gatt.py gatt_browser.gatt gatt_browser.h
  61. // it needs to be regenerated when the GATT Database declared in gatt_browser.gatt file is modified
  62. #include "gatt_browser.h"
  63. typedef struct advertising_report {
  64. uint8_t type;
  65. uint8_t event_type;
  66. uint8_t address_type;
  67. bd_addr_t address;
  68. uint8_t rssi;
  69. uint8_t length;
  70. const uint8_t * data;
  71. } advertising_report_t;
  72. static bd_addr_t cmdline_addr;
  73. static int cmdline_addr_found = 0;
  74. static hci_con_handle_t connection_handler;
  75. static gatt_client_service_t services[40];
  76. static int service_count = 0;
  77. static int service_index = 0;
  78. static btstack_packet_callback_registration_t hci_event_callback_registration;
  79. /* @section GATT client setup
  80. *
  81. * @text In the setup phase, a GATT client must register the HCI and GATT client
  82. * packet handlers, as shown in Listing GATTClientSetup.
  83. * Additionally, the security manager can be setup, if signed writes, or
  84. * encrypted, or authenticated connection are required, to access the
  85. * characteristics, as explained in Section on [SMP](../protocols/#sec:smpProtocols).
  86. */
  87. /* LISTING_START(GATTClientSetup): Setting up GATT client */
  88. // Handles connect, disconnect, and advertising report events,
  89. // starts the GATT client, and sends the first query.
  90. static void handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
  91. // Handles GATT client query results, sends queries and the
  92. // GAP disconnect command when the querying is done.
  93. static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
  94. static void gatt_client_setup(void){
  95. // Initialize L2CAP and register HCI event handler
  96. l2cap_init();
  97. // Initialize GATT client
  98. gatt_client_init();
  99. // Optinoally, Setup security manager
  100. sm_init();
  101. sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
  102. // register for HCI events
  103. hci_event_callback_registration.callback = &handle_hci_event;
  104. hci_add_event_handler(&hci_event_callback_registration);
  105. }
  106. /* LISTING_END */
  107. static void printUUID(uint8_t * uuid128, uint16_t uuid16){
  108. if (uuid16){
  109. printf("%04x",uuid16);
  110. } else {
  111. printf("%s", uuid128_to_str(uuid128));
  112. }
  113. }
  114. static void dump_advertising_report(advertising_report_t * e){
  115. printf(" * adv. event: evt-type %u, addr-type %u, addr %s, rssi %u, length adv %u, data: ", e->event_type,
  116. e->address_type, bd_addr_to_str(e->address), e->rssi, e->length);
  117. printf_hexdump(e->data, e->length);
  118. }
  119. static void dump_characteristic(gatt_client_characteristic_t * characteristic){
  120. printf(" * characteristic: [0x%04x-0x%04x-0x%04x], properties 0x%02x, uuid ",
  121. characteristic->start_handle, characteristic->value_handle, characteristic->end_handle, characteristic->properties);
  122. printUUID(characteristic->uuid128, characteristic->uuid16);
  123. printf("\n");
  124. }
  125. static void dump_service(gatt_client_service_t * service){
  126. printf(" * service: [0x%04x-0x%04x], uuid ", service->start_group_handle, service->end_group_handle);
  127. printUUID(service->uuid128, service->uuid16);
  128. printf("\n");
  129. }
  130. static void fill_advertising_report_from_packet(advertising_report_t * report, uint8_t *packet){
  131. gap_event_advertising_report_get_address(packet, report->address);
  132. report->event_type = gap_event_advertising_report_get_advertising_event_type(packet);
  133. report->address_type = gap_event_advertising_report_get_address_type(packet);
  134. report->rssi = gap_event_advertising_report_get_rssi(packet);
  135. report->length = gap_event_advertising_report_get_data_length(packet);
  136. report->data = gap_event_advertising_report_get_data(packet);
  137. }
  138. /* @section HCI packet handler
  139. *
  140. * @text The HCI packet handler has to start the scanning,
  141. * to find the first advertising device, to stop scanning, to connect
  142. * to and later to disconnect from it, to start the GATT client upon
  143. * the connection is completed, and to send the first query - in this
  144. * case the gatt_client_discover_primary_services() is called, see
  145. * Listing GATTBrowserHCIPacketHandler.
  146. */
  147. /* LISTING_START(GATTBrowserHCIPacketHandler): Connecting and disconnecting from the GATT client */
  148. static void handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  149. UNUSED(channel);
  150. UNUSED(size);
  151. if (packet_type != HCI_EVENT_PACKET) return;
  152. advertising_report_t report;
  153. uint8_t event = hci_event_packet_get_type(packet);
  154. switch (event) {
  155. case BTSTACK_EVENT_STATE:
  156. // BTstack activated, get started
  157. if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
  158. if (cmdline_addr_found){
  159. printf("Trying to connect to %s\n", bd_addr_to_str(cmdline_addr));
  160. gap_connect(cmdline_addr, 0);
  161. break;
  162. }
  163. printf("BTstack activated, start scanning!\n");
  164. gap_set_scan_parameters(0,0x0030, 0x0030);
  165. gap_start_scan();
  166. break;
  167. case GAP_EVENT_ADVERTISING_REPORT:
  168. fill_advertising_report_from_packet(&report, packet);
  169. dump_advertising_report(&report);
  170. // stop scanning, and connect to the device
  171. gap_stop_scan();
  172. gap_connect(report.address,report.address_type);
  173. break;
  174. case HCI_EVENT_LE_META:
  175. // wait for connection complete
  176. if (hci_event_le_meta_get_subevent_code(packet) != HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
  177. connection_handler = hci_subevent_le_connection_complete_get_connection_handle(packet);
  178. // query primary services
  179. gatt_client_discover_primary_services(handle_gatt_client_event, connection_handler);
  180. break;
  181. case HCI_EVENT_DISCONNECTION_COMPLETE:
  182. printf("\nGATT browser - DISCONNECTED\n");
  183. break;
  184. default:
  185. break;
  186. }
  187. }
  188. /* LISTING_END */
  189. /* @section GATT Client event handler
  190. *
  191. * @text Query results and further queries are handled by the GATT client packet
  192. * handler, as shown in Listing GATTBrowserQueryHandler. Here, upon
  193. * receiving the primary services, the
  194. * gatt_client_discover_characteristics_for_service() query for the last
  195. * received service is sent. After receiving the characteristics for the service,
  196. * gap_disconnect is called to terminate the connection. Upon
  197. * disconnect, the HCI packet handler receives the disconnect complete event.
  198. */
  199. /* LISTING_START(GATTBrowserQueryHandler): Handling of the GATT client queries */
  200. static int search_services = 1;
  201. static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  202. UNUSED(packet_type);
  203. UNUSED(channel);
  204. UNUSED(size);
  205. gatt_client_service_t service;
  206. gatt_client_characteristic_t characteristic;
  207. switch(hci_event_packet_get_type(packet)){
  208. case GATT_EVENT_SERVICE_QUERY_RESULT:\
  209. gatt_event_service_query_result_get_service(packet, &service);
  210. dump_service(&service);
  211. services[service_count++] = service;
  212. break;
  213. case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
  214. gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
  215. dump_characteristic(&characteristic);
  216. break;
  217. case GATT_EVENT_QUERY_COMPLETE:
  218. if (search_services){
  219. // GATT_EVENT_QUERY_COMPLETE of search services
  220. service_index = 0;
  221. printf("\nGATT browser - CHARACTERISTIC for SERVICE %s\n", uuid128_to_str(service.uuid128));
  222. search_services = 0;
  223. gatt_client_discover_characteristics_for_service(handle_gatt_client_event, connection_handler, &services[service_index]);
  224. } else {
  225. // GATT_EVENT_QUERY_COMPLETE of search characteristics
  226. if (service_index < service_count) {
  227. service = services[service_index++];
  228. printf("\nGATT browser - CHARACTERISTIC for SERVICE %s, [0x%04x-0x%04x]\n",
  229. uuid128_to_str(service.uuid128), service.start_group_handle, service.end_group_handle);
  230. gatt_client_discover_characteristics_for_service(handle_gatt_client_event, connection_handler, &service);
  231. break;
  232. }
  233. service_index = 0;
  234. gap_disconnect(connection_handler);
  235. }
  236. break;
  237. default:
  238. break;
  239. }
  240. }
  241. /* LISTING_END */
  242. #ifdef HAVE_BTSTACK_STDIN
  243. static void usage(const char *name){
  244. fprintf(stderr, "\nUsage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", name);
  245. fprintf(stderr, "If no argument is provided, GATT browser will start scanning and connect to the first found device.\nTo connect to a specific device use argument [-a].\n\n");
  246. }
  247. #endif
  248. int btstack_main(int argc, const char * argv[]);
  249. int btstack_main(int argc, const char * argv[]){
  250. #ifdef HAVE_BTSTACK_STDIN
  251. int arg = 1;
  252. cmdline_addr_found = 0;
  253. while (arg < argc) {
  254. if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
  255. arg++;
  256. cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
  257. arg++;
  258. continue;
  259. }
  260. usage(argv[0]);
  261. return 0;
  262. }
  263. #else
  264. (void)argc;
  265. (void)argv;
  266. #endif
  267. // setup GATT client
  268. gatt_client_setup();
  269. // setup ATT server - only needed if LE Peripheral does ATT queries on its own, e.g. Android and iOS
  270. att_server_init(profile_data, NULL, NULL);
  271. // turn on!
  272. hci_power_control(HCI_POWER_ON);
  273. return 0;
  274. }
  275. /* EXAMPLE_END */