xref: /btstack/example/gatt_battery_query.c (revision a4fe6467953bdb173fdf96a604f6527ed88f81c3)
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  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "gatt_battery_query.c"
39 
40 // *****************************************************************************
41 //
42 // BLE Client
43 //
44 // *****************************************************************************
45 
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #include "btstack.h"
52 #include "gatt_battery_query.h"
53 
54 typedef struct advertising_report {
55     uint8_t   type;
56     uint8_t   event_type;
57     uint8_t   address_type;
58     bd_addr_t address;
59     uint8_t   rssi;
60     uint8_t   length;
61     const uint8_t * data;
62 } advertising_report_t;
63 
64 
65 typedef enum {
66     TC_IDLE,
67     TC_W4_SCAN_RESULT,
68     TC_W4_CONNECT,
69     TC_W4_SERVICE_RESULT,
70     TC_W4_CHARACTERISTIC_RESULT,
71     TC_W4_BATTERY_DATA
72 } gc_state_t;
73 
74 static int blacklist_index = 0;
75 static bd_addr_t blacklist[20];
76 static advertising_report_t report;
77 
78 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
79 
80 static bd_addr_t cmdline_addr;
81 static int cmdline_addr_found = 0;
82 
83 static hci_con_handle_t connection_handle;
84 static uint16_t battery_service_uuid = 0x180F;
85 static uint16_t battery_level_characteristic_uuid = 0x2a19;
86 static gatt_client_service_t battery_service;
87 static gatt_client_characteristic_t config_characteristic;
88 
89 static gc_state_t state = TC_IDLE;
90 static btstack_packet_callback_registration_t hci_event_callback_registration;
91 
92 static void printUUID(uint8_t * uuid128, uint16_t uuid16){
93     if (uuid16){
94         printf("%04x",uuid16);
95     } else {
96         printf("%s", uuid128_to_str(uuid128));
97     }
98 }
99 
100 static int blacklist_size(void){
101     return sizeof(blacklist) / sizeof(bd_addr_t);
102 }
103 
104 static int blacklist_contains(bd_addr_t addr){
105     int i;
106     for (i=0; i<blacklist_size(); i++){
107         if (bd_addr_cmp(addr, blacklist[i]) == 0) return 1;
108     }
109     return 0;
110 }
111 
112 static void add_to_blacklist(bd_addr_t addr){
113     printf("%s added to blacklist (no battery service found\n", bd_addr_to_str(addr));
114     bd_addr_copy(blacklist[blacklist_index], addr);
115     blacklist_index = (blacklist_index + 1) % blacklist_size();
116 }
117 
118 static void dump_advertising_report(advertising_report_t * e){
119     printf("    * adv. event: evt-type %u, addr-type %u, addr %s, rssi %u, length adv %u, data: ", e->event_type,
120            e->address_type, bd_addr_to_str(e->address), e->rssi, e->length);
121     printf_hexdump(e->data, e->length);
122 
123 }
124 
125 static void dump_characteristic_value(uint8_t * blob, uint16_t blob_length){
126     printf("    * characteristic value of length %d *** ", blob_length );
127     printf_hexdump(blob , blob_length);
128     printf("\n");
129 }
130 
131 static void dump_characteristic(gatt_client_characteristic_t * characteristic){
132     printf("    * characteristic: [0x%04x-0x%04x-0x%04x], properties 0x%02x, uuid ",
133                             characteristic->start_handle, characteristic->value_handle, characteristic->end_handle, characteristic->properties);
134     printUUID(characteristic->uuid128, characteristic->uuid16);
135     printf("\n");
136 }
137 
138 static void dump_service(gatt_client_service_t * service){
139     printf("    * service: [0x%04x-0x%04x], uuid ", service->start_group_handle, service->end_group_handle);
140     printUUID(service->uuid128, service->uuid16);
141     printf("\n");
142 }
143 
144 
145 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
146     UNUSED(packet_type);
147     UNUSED(channel);
148     UNUSED(size);
149 
150     int status;
151     uint8_t battery_level;
152 
153     switch(state){
154         case TC_W4_SERVICE_RESULT:
155             switch(hci_event_packet_get_type(packet)){
156                 case GATT_EVENT_SERVICE_QUERY_RESULT:
157                     gatt_event_service_query_result_get_service(packet, &battery_service);
158                     dump_service(&battery_service);
159                     break;
160                 case GATT_EVENT_QUERY_COMPLETE:
161                     if (packet[4] != 0){
162                         printf("SERVICE_QUERY_RESULT - Error status %x.\n", packet[4]);
163                         add_to_blacklist(report.address);
164                         gap_disconnect(connection_handle);
165                         break;
166                     }
167                     state = TC_W4_CHARACTERISTIC_RESULT;
168                     printf("\nSearch for battery level characteristic.\n");
169                     gatt_client_discover_characteristics_for_service_by_uuid16(handle_gatt_client_event, connection_handle, &battery_service, battery_level_characteristic_uuid);
170                     break;
171                 default:
172                     break;
173             }
174             break;
175 
176         case TC_W4_CHARACTERISTIC_RESULT:
177             switch(hci_event_packet_get_type(packet)){
178                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
179                     gatt_event_characteristic_query_result_get_characteristic(packet, &config_characteristic);
180                     dump_characteristic(&config_characteristic);
181                     break;
182                 case GATT_EVENT_QUERY_COMPLETE:
183                     if (packet[4] != 0){
184                         printf("CHARACTERISTIC_QUERY_RESULT - Error status %x.\n", packet[4]);
185                         add_to_blacklist(report.address);
186                         gap_disconnect(connection_handle);
187                         break;
188                     }
189                     state = TC_W4_BATTERY_DATA;
190                     printf("\nConfigure battery level characteristic for notify.\n");
191                     status = gatt_client_write_client_characteristic_configuration(handle_gatt_client_event, connection_handle, &config_characteristic, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
192                     if (status != 0){
193                         printf("\nNotification not supported. Query value of characteristic.\n");
194                         gatt_client_read_value_of_characteristic(handle_gatt_client_event, connection_handle, &config_characteristic);
195                     }
196 
197                     break;
198                 default:
199                     break;
200             }
201             break;
202         case TC_W4_BATTERY_DATA:
203             switch(hci_event_packet_get_type(packet)){
204                 case GATT_EVENT_NOTIFICATION:
205                     printf("\nBattery Data:\n");
206                     dump_characteristic_value(&packet[8], little_endian_read_16(packet, 6));
207                     break;
208                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
209 
210                         if (gatt_event_characteristic_value_query_result_get_value_length(packet) < 1) break;
211                         battery_level = gatt_event_characteristic_value_query_result_get_value(packet)[0];
212                         printf("Battery level %d \n", battery_level);
213                     break;
214 
215                 case GATT_EVENT_QUERY_COMPLETE:
216                     if (packet[4] != 0){
217                         printf("CHARACTERISTIC_VALUE_QUERY_RESULT - Error status %x.\n", packet[4]);
218                         break;
219                     }
220                     break;
221                 default:
222                     printf("Unknown packet type %x\n", hci_event_packet_get_type(packet));
223                     break;
224             }
225             break;
226 
227         default:
228             printf("error\n");
229             break;
230     }
231 
232 }
233 
234 static void fill_advertising_report_from_packet(advertising_report_t * adv_report, uint8_t *packet){
235     gap_event_advertising_report_get_address(packet, adv_report->address);
236     adv_report->event_type = gap_event_advertising_report_get_advertising_event_type(packet);
237     adv_report->address_type = gap_event_advertising_report_get_address_type(packet);
238     adv_report->rssi = gap_event_advertising_report_get_rssi(packet);
239     adv_report->length = gap_event_advertising_report_get_data_length(packet);
240     adv_report->data = gap_event_advertising_report_get_data(packet);
241 }
242 
243 static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
244     UNUSED(channel);
245     UNUSED(size);
246 
247     if (packet_type != HCI_EVENT_PACKET) return;
248 
249     uint8_t event = hci_event_packet_get_type(packet);
250     switch (event) {
251         case BTSTACK_EVENT_STATE:
252             // BTstack activated, get started
253             if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
254             if (cmdline_addr_found){
255                 printf("Connect to %s\n", bd_addr_to_str(cmdline_addr));
256                 state = TC_W4_CONNECT;
257                 gap_connect(cmdline_addr, 0);
258                 break;
259             }
260             printf("Start scanning!\n");
261             state = TC_W4_SCAN_RESULT;
262             gap_set_scan_parameters(0,0x0030, 0x0030);
263             gap_start_scan();
264             break;
265         case GAP_EVENT_ADVERTISING_REPORT:
266             if (state != TC_W4_SCAN_RESULT) return;
267             fill_advertising_report_from_packet(&report, packet);
268 
269             if (blacklist_contains(report.address)) {
270                 break;
271             }
272             dump_advertising_report(&report);
273             // stop scanning, and connect to the device
274             state = TC_W4_CONNECT;
275             gap_stop_scan();
276             printf("Stop scan. Connect to device with addr %s.\n", bd_addr_to_str(report.address));
277             gap_connect(report.address,report.address_type);
278 
279             break;
280         case HCI_EVENT_LE_META:
281             // wait for connection complete
282             if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
283             if (state != TC_W4_CONNECT) return;
284             connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
285             // initialize gatt client context with handle, and add it to the list of active clients
286             // query primary services
287             printf("\nSearch for battery service.\n");
288             state = TC_W4_SERVICE_RESULT;
289             gatt_client_discover_primary_services_by_uuid16(handle_gatt_client_event, connection_handle, battery_service_uuid);
290             break;
291         case HCI_EVENT_DISCONNECTION_COMPLETE:
292 
293             if (cmdline_addr_found){
294                 printf("\nDisconnected %s\n", bd_addr_to_str(cmdline_addr));
295                 return;
296             }
297 
298             printf("\nDisconnected %s\n", bd_addr_to_str(report.address));
299             printf("Restart scan.\n");
300             state = TC_W4_SCAN_RESULT;
301             gap_start_scan();
302             break;
303         default:
304             break;
305     }
306 }
307 
308 #ifdef HAVE_BTSTACK_STDIN
309 static void usage(const char *name){
310     fprintf(stderr, "\nUsage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", name);
311     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");
312 }
313 #endif
314 
315 int btstack_main(int argc, const char * argv[]);
316 int btstack_main(int argc, const char * argv[]){
317 
318 #ifdef HAVE_BTSTACK_STDIN
319     int arg = 1;
320     cmdline_addr_found = 0;
321 
322     while (arg < argc) {
323         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
324             arg++;
325             cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
326             arg++;
327             if (!cmdline_addr_found) exit(1);
328             continue;
329         }
330         usage(argv[0]);
331         return 0;
332     }
333 #else
334     (void)argc;
335     (void)argv;
336 #endif
337     l2cap_init();
338 
339     // setup ATT server - only needed if LE Peripheral does ATT queries on its own, e.g. Android phones
340     att_server_init(profile_data, NULL, NULL);
341 
342     // GATT Client setup
343     gatt_client_init();
344 
345     sm_init();
346     sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
347 
348     hci_event_callback_registration.callback = &hci_event_handler;
349     hci_add_event_handler(&hci_event_callback_registration);
350 
351 
352     // turn on!
353     hci_power_control(HCI_POWER_ON);
354 
355     return 0;
356 }
357 
358 
359 
360 
361