xref: /btstack/example/gatt_battery_query.c (revision ed2540d4a98d3580c4414caf25307c965fdf3f9c)
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 // *****************************************************************************
39 //
40 // BLE Client
41 //
42 // *****************************************************************************
43 
44 #include <stdint.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 
49 #include "btstack.h"
50 
51 typedef struct advertising_report {
52     uint8_t   type;
53     uint8_t   event_type;
54     uint8_t   address_type;
55     bd_addr_t address;
56     uint8_t   rssi;
57     uint8_t   length;
58     uint8_t * data;
59 } advertising_report_t;
60 
61 
62 typedef enum {
63     TC_IDLE,
64     TC_W4_SCAN_RESULT,
65     TC_W4_CONNECT,
66     TC_W4_SERVICE_RESULT,
67     TC_W4_CHARACTERISTIC_RESULT,
68     TC_W4_BATTERY_DATA
69 } gc_state_t;
70 
71 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
72 
73 static bd_addr_t cmdline_addr = { };
74 static int cmdline_addr_found = 0;
75 
76 static hci_con_handle_t connection_handle;
77 static uint16_t battery_service_uuid = 0x180F;
78 static uint16_t battery_level_characteristic_uuid = 0x2a19;
79 static gatt_client_service_t battery_service;
80 static gatt_client_characteristic_t config_characteristic;
81 
82 static gc_state_t state = TC_IDLE;
83 static btstack_packet_callback_registration_t hci_event_callback_registration;
84 
85 static void printUUID(uint8_t * uuid128, uint16_t uuid16){
86     if (uuid16){
87         printf("%04x",uuid16);
88     } else {
89         printf("%s", uuid128_to_str(uuid128));
90     }
91 }
92 
93 static void dump_advertising_report(advertising_report_t * e){
94     printf("    * adv. event: evt-type %u, addr-type %u, addr %s, rssi %u, length adv %u, data: ", e->event_type,
95            e->address_type, bd_addr_to_str(e->address), e->rssi, e->length);
96     printf_hexdump(e->data, e->length);
97 
98 }
99 
100 static void dump_characteristic_value(uint8_t * blob, uint16_t blob_length){
101     printf("    * characteristic value of length %d *** ", blob_length );
102     printf_hexdump(blob , blob_length);
103     printf("\n");
104 }
105 
106 static void dump_characteristic(gatt_client_characteristic_t * characteristic){
107     printf("    * characteristic: [0x%04x-0x%04x-0x%04x], properties 0x%02x, uuid ",
108                             characteristic->start_handle, characteristic->value_handle, characteristic->end_handle, characteristic->properties);
109     printUUID(characteristic->uuid128, characteristic->uuid16);
110     printf("\n");
111 }
112 
113 static void dump_service(gatt_client_service_t * service){
114     printf("    * service: [0x%04x-0x%04x], uuid ", service->start_group_handle, service->end_group_handle);
115     printUUID(service->uuid128, service->uuid16);
116     printf("\n");
117 }
118 
119 static void error_code(int status){
120     switch(status){
121         case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
122             printf("ATT_ERROR_INSUFFICIENT_AUTHENTICATION. TODO: security manager is not complete yet.\n");
123             break;
124         default:
125             printf(" status 0x%02x\n", status);
126             break;
127     }
128 }
129 
130 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
131 
132     switch(state){
133         case TC_W4_SERVICE_RESULT:
134             switch(hci_event_packet_get_type(packet)){
135                 case GATT_EVENT_SERVICE_QUERY_RESULT:
136                     gatt_event_service_query_result_get_service(packet, &battery_service);
137                     printf("Battery service found:\n");
138                     dump_service(&battery_service);
139                     break;
140                 case GATT_EVENT_QUERY_COMPLETE:
141                     if (!packet[4]){
142                         printf("Battery service not found. Restart scan.\n");
143                         state = TC_W4_SCAN_RESULT;
144                         gap_start_scan();
145                         break;
146                     }
147                     state = TC_W4_CHARACTERISTIC_RESULT;
148                     printf("\nSearch for battery level characteristic in battery service. ");
149                     gatt_client_discover_characteristics_for_service_by_uuid16(handle_gatt_client_event, connection_handle, &battery_service, battery_level_characteristic_uuid);
150                     break;
151                 default:
152                     break;
153             }
154             break;
155 
156         case TC_W4_CHARACTERISTIC_RESULT:
157             switch(hci_event_packet_get_type(packet)){
158                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
159                     printf("Battery level characteristic found:\n");
160                     gatt_event_characteristic_query_result_get_characteristic(packet, &config_characteristic);
161                     dump_characteristic(&config_characteristic);
162                     break;
163                 case GATT_EVENT_QUERY_COMPLETE:
164                     state = TC_W4_BATTERY_DATA;
165                     printf("\nConfigure battery level characteristic for notify.");
166                     gatt_client_write_client_characteristic_configuration(handle_gatt_client_event, connection_handle, &config_characteristic, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
167                     break;
168                 default:
169                     break;
170             }
171             break;
172         case TC_W4_BATTERY_DATA:
173             if (hci_event_packet_get_type(packet) == GATT_EVENT_QUERY_COMPLETE){
174                 if (packet[4] != 0){
175                     printf("\nNotification is not possible: ");
176                     error_code(packet[4]);
177                 }
178                 break;
179             }
180             if (hci_event_packet_get_type(packet) != GATT_EVENT_NOTIFICATION) break;
181             printf("\nBattery Data:\n");
182             dump_characteristic_value(&packet[8], little_endian_read_16(packet, 6));
183             break;
184 
185         default:
186             printf("error\n");
187             break;
188     }
189 
190 }
191 
192 static void fill_advertising_report_from_packet(advertising_report_t * report, uint8_t *packet){
193     int pos = 2;
194     report->event_type = packet[pos++];
195     report->address_type = packet[pos++];
196     reverse_bd_addr(&packet[pos], report->address);
197     pos += 6;
198     report->rssi = packet[pos++];
199     report->length = packet[pos++];
200     report->data = &packet[pos];
201     pos += report->length;
202     dump_advertising_report(report);
203 }
204 
205 static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
206     if (packet_type != HCI_EVENT_PACKET) return;
207     advertising_report_t report;
208     uint8_t event = hci_event_packet_get_type(packet);
209     switch (event) {
210         case BTSTACK_EVENT_STATE:
211             // BTstack activated, get started
212             if (packet[2] != HCI_STATE_WORKING) break;
213             if (cmdline_addr_found){
214                 printf("Start connect to %s\n", bd_addr_to_str(cmdline_addr));
215                 state = TC_W4_CONNECT;
216                 gap_connect(cmdline_addr, 0);
217                 break;
218             }
219             printf("BTstack activated, start scanning!\n");
220             state = TC_W4_SCAN_RESULT;
221             gap_set_scan_parameters(0,0x0030, 0x0030);
222             gap_start_scan();
223             break;
224         case GAP_LE_EVENT_ADVERTISING_REPORT:
225             if (state != TC_W4_SCAN_RESULT) return;
226             fill_advertising_report_from_packet(&report, packet);
227             // stop scanning, and connect to the device
228             state = TC_W4_CONNECT;
229             gap_stop_scan();
230             printf("Stop scan. Start connect to device with addr %s.\n", bd_addr_to_str(report.address));
231             gap_connect(report.address,report.address_type);
232             break;
233         case HCI_EVENT_LE_META:
234             // wait for connection complete
235             if (packet[2] !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
236             if (state != TC_W4_CONNECT) return;
237             connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
238             // initialize gatt client context with handle, and add it to the list of active clients
239             // query primary services
240             printf("\nSearch for battery service.\n");
241             state = TC_W4_SERVICE_RESULT;
242             gatt_client_discover_primary_services_by_uuid16(handle_gatt_client_event, connection_handle, battery_service_uuid);
243             break;
244         case HCI_EVENT_DISCONNECTION_COMPLETE:
245             printf("\nDISCONNECTED\n");
246             exit(0);
247             break;
248         default:
249             break;
250     }
251 }
252 
253 static void usage(const char *name){
254 	fprintf(stderr, "\nUsage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", name);
255 	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");
256 }
257 
258 int btstack_main(int argc, const char * argv[]);
259 int btstack_main(int argc, const char * argv[]){
260 
261     int arg = 1;
262     cmdline_addr_found = 0;
263 
264     while (arg < argc) {
265 		if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
266 			arg++;
267 			cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
268             arg++;
269             continue;
270         }
271         usage(argv[0]);
272         return 0;
273 	}
274 
275     hci_event_callback_registration.callback = &hci_event_handler;
276     hci_add_event_handler(&hci_event_callback_registration);
277 
278     l2cap_init();
279 
280     gatt_client_init();
281 
282     sm_init();
283     sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
284 
285     // turn on!
286     hci_power_control(HCI_POWER_ON);
287 
288     return 0;
289 }
290 
291 
292 
293 
294