xref: /btstack/example/gatt_battery_query.c (revision 842264f18f03b8dc69bae06bfa4f0ff58277db3f)
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 /* EXAMPLE_START(gatt_battery_query): GATT Battery Service Client
42  *
43  * @text This example demonstrates how to use the GATT Battery Service client to
44  * receive battery level information. The client supports querying of multiple
45  * battery services instances of on the remote device.
46  * The example scans for remote devices and connects to the first found device
47  * and starts the battery service client.
48  */
49 // *****************************************************************************
50 
51 #include <stdint.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 
56 #include "btstack.h"
57 
58 // gatt_battery_query.gatt contains the declaration of the provided GATT Services + Characteristics
59 // gatt_battery_query.h    contains the binary representation of gatt_battery_query.gatt
60 // it is generated by the build system by calling: $BTSTACK_ROOT/tool/compile_gatt.py gatt_battery_query.gatt gatt_battery_query.h
61 // it needs to be regenerated when the GATT Database declared in gatt_battery_query.gatt file is modified
62 #include "gatt_battery_query.h"
63 
64 typedef struct advertising_report {
65     uint8_t   type;
66     uint8_t   event_type;
67     uint8_t   address_type;
68     bd_addr_t address;
69     uint8_t   rssi;
70     uint8_t   length;
71     const uint8_t * data;
72 } advertising_report_t;
73 
74 static enum {
75     APP_STATE_IDLE,
76     APP_STATE_W4_SCAN_RESULT,
77     APP_STATE_W4_CONNECT,
78     APP_STATE_CONNECTED
79 } app_state;
80 
81 static int blacklist_index = 0;
82 static bd_addr_t blacklist[20];
83 static advertising_report_t report;
84 
85 static hci_con_handle_t connection_handle;
86 static uint16_t battery_service_cid;
87 
88 static bd_addr_t cmdline_addr;
89 static int cmdline_addr_found = 0;
90 
91 static btstack_packet_callback_registration_t hci_event_callback_registration;
92 
93 /* @section Main Application Setup
94  *
95  * @text The Listing MainConfiguration shows how to setup Battery Service client.
96  * Besides calling init() method for each service, you'll also need to register HCI packet handler
97  * to handle advertisements, as well as connect and disconect events.
98  *
99  * @text Handling of GATT Battery Service events will be later delegated to a sepparate packet
100  * handler, i.e. gatt_client_event_handler.
101  *
102  * @note There are two additional files associated with this client to allow a remote device to query out GATT database:
103  * - gatt_battary_query.gatt - contains the declaration of the provided GATT Services and Characteristics.
104  * - gatt_battary_query.h    - contains the binary representation of gatt_battary_query.gatt.
105  *
106  * gatt_battary_query.h is generated by the build system by calling:
107  * $BTSTACK_ROOT/tool/compile_gatt.py gatt_battary_query.gatt gatt_battary_query.h
108  * This file needs to be regenerated when the GATT Database declared in gatt_battary_query.gatt file is modified.
109  */
110 
111 /* LISTING_START(MainConfiguration): Setup Device Battery Client service */
112 static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
113 static void gatt_client_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
114 
115 static void battery_service_client_setup(void){
116     // Init L2CAP
117     l2cap_init();
118 
119     // Setup ATT server - only needed if LE Peripheral does ATT queries on its own, e.g. Android phones
120     att_server_init(profile_data, NULL, NULL);
121 
122     // GATT Client setup
123     gatt_client_init();
124     // Device Information Service Client setup
125     battery_service_client_init();
126 
127     sm_init();
128     sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
129 
130     hci_event_callback_registration.callback = &hci_event_handler;
131     hci_add_event_handler(&hci_event_callback_registration);
132 }
133 /* LISTING_END */
134 
135 static int blacklist_size(void){
136     return sizeof(blacklist) / sizeof(bd_addr_t);
137 }
138 
139 static int blacklist_contains(bd_addr_t addr){
140     int i;
141     for (i=0; i<blacklist_size(); i++){
142         if (bd_addr_cmp(addr, blacklist[i]) == 0) return 1;
143     }
144     return 0;
145 }
146 
147 static void add_to_blacklist(bd_addr_t addr){
148     printf("%s added to blacklist (no battery service found).\n", bd_addr_to_str(addr));
149     bd_addr_copy(blacklist[blacklist_index], addr);
150     blacklist_index = (blacklist_index + 1) % blacklist_size();
151 }
152 
153 static void dump_advertising_report(uint8_t *packet){
154     bd_addr_t address;
155     gap_event_advertising_report_get_address(packet, address);
156 
157     printf("    * adv. event: evt-type %u, addr-type %u, addr %s, rssi %u, length adv %u, data: ",
158         gap_event_advertising_report_get_advertising_event_type(packet),
159         gap_event_advertising_report_get_address_type(packet),
160         bd_addr_to_str(address),
161         gap_event_advertising_report_get_rssi(packet),
162         gap_event_advertising_report_get_data_length(packet));
163     printf_hexdump(gap_event_advertising_report_get_data(packet), gap_event_advertising_report_get_data_length(packet));
164 
165 }
166 
167 /* LISTING_START(packetHandler): Packet Handler */
168 static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
169     /* LISTING_PAUSE */
170     UNUSED(channel);
171     UNUSED(size);
172 
173     /* LISTING_RESUME */
174     uint8_t status;
175     bd_addr_t address;
176 
177     if (packet_type != HCI_EVENT_PACKET){
178         return;
179     }
180 
181     switch (hci_event_packet_get_type(packet)) {
182         /* LISTING_PAUSE */
183 
184         case BTSTACK_EVENT_STATE:
185             // BTstack activated, get started
186             if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
187             if (cmdline_addr_found){
188                 printf("Connect to %s\n", bd_addr_to_str(cmdline_addr));
189                 app_state = APP_STATE_W4_CONNECT;
190                 gap_connect(cmdline_addr, 0);
191                 break;
192             }
193             printf("Start scanning!\n");
194             app_state = APP_STATE_W4_SCAN_RESULT;
195             gap_set_scan_parameters(0,0x0030, 0x0030);
196             gap_start_scan();
197             break;
198 
199         case GAP_EVENT_ADVERTISING_REPORT:
200             if (app_state != APP_STATE_W4_SCAN_RESULT) return;
201 
202             gap_event_advertising_report_get_address(packet, address);
203             if (blacklist_contains(address)) {
204                 break;
205             }
206             dump_advertising_report(packet);
207 
208             // stop scanning, and connect to the device
209             app_state = APP_STATE_W4_CONNECT;
210             gap_stop_scan();
211             printf("Stop scan. Connect to device with addr %s.\n", bd_addr_to_str(report.address));
212             gap_connect(report.address,report.address_type);
213             break;
214 
215         /* LISTING_RESUME */
216         case HCI_EVENT_LE_META:
217             // Wait for connection complete
218             if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
219 
220             /* LISTING_PAUSE */
221             if (app_state != APP_STATE_W4_CONNECT) return;
222 
223             /* LISTING_RESUME */
224             // Get connection handle from event
225             connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
226 
227             // Connect to remote Battery Service.
228             // On succesful connection, the client tries to register for notifications. If notifications
229             // are not supported by remote Battery Service, the client will automatically poll the battery level - here every 2 seconds.
230             // If poll_interval_ms is 0, polling is disabled, and only notifications will be received (for manual polling,
231             // see battery_service_client.h).
232             // All GATT Battery Service events are handled by the gatt_client_event_handler.
233             status = battery_service_client_connect(connection_handle, gatt_client_event_handler, 2000, &battery_service_cid);
234             btstack_assert(status == ERROR_CODE_SUCCESS);
235 
236             app_state = APP_STATE_CONNECTED;
237             printf("Battery service connected.\n");
238             break;
239 
240         case HCI_EVENT_DISCONNECTION_COMPLETE:
241             connection_handle = HCI_CON_HANDLE_INVALID;
242             // Disconnect battery service
243             battery_service_client_disconnect(battery_service_cid);
244 
245             /* LISTING_PAUSE */
246             if (cmdline_addr_found){
247                 printf("Disconnected %s\n", bd_addr_to_str(cmdline_addr));
248                 return;
249             }
250 
251             /* LISTING_RESUME */
252             printf("Disconnected %s\n", bd_addr_to_str(report.address));
253             printf("Restart scan.\n");
254             app_state = APP_STATE_W4_SCAN_RESULT;
255             gap_start_scan();
256             break;
257         default:
258             break;
259     }
260 }
261 /* LISTING_END */
262 
263 /* LISTING_START(gatt_client_event_handler): GATT Client Event Handler */
264 // The gatt_client_event_handler receives following events from remote device:
265 //  - GATTSERVICE_SUBEVENT_BATTERY_SERVICE_CONNECTED
266 //  - GATTSERVICE_SUBEVENT_BATTERY_SERVICE_LEVEL
267 //
268 static void gatt_client_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
269     /* LISTING_PAUSE */
270     UNUSED(packet_type);
271     UNUSED(channel);
272     UNUSED(size);
273 
274     /* LISTING_RESUME */
275     uint8_t status;
276     uint8_t att_status;
277 
278     if (hci_event_packet_get_type(packet) != HCI_EVENT_GATTSERVICE_META){
279         return;
280     }
281 
282     switch (hci_event_gattservice_meta_get_subevent_code(packet)){
283         case GATTSERVICE_SUBEVENT_BATTERY_SERVICE_CONNECTED:
284             status = gattservice_subevent_battery_service_connected_get_status(packet);
285             switch (status){
286                 case ERROR_CODE_SUCCESS:
287                     printf("Battery service client connected, found %d services, poll bitmap 0x%02x\n",
288                         gattservice_subevent_battery_service_connected_get_num_instances(packet),
289                         gattservice_subevent_battery_service_connected_get_poll_bitmap(packet));
290                     break;
291                 default:
292                     printf("Battery service client connection failed, err 0x%02x.\n", status);
293                     add_to_blacklist(report.address);
294                     gap_disconnect(connection_handle);
295                     break;
296             }
297             break;
298 
299         case GATTSERVICE_SUBEVENT_BATTERY_SERVICE_LEVEL:
300             att_status = gattservice_subevent_battery_service_level_get_att_status(packet);
301             if (att_status != ATT_ERROR_SUCCESS){
302                 printf("Battery level read failed, ATT Error 0x%02x\n", att_status);
303             } else {
304                 printf("Service index: %d, Battery level: %d\n",
305                     gattservice_subevent_battery_service_level_get_sevice_index(packet),
306                     gattservice_subevent_battery_service_level_get_level(packet));
307 
308             }
309             break;
310 
311         default:
312             break;
313     }
314 }
315  /* LISTING_END */
316 
317 int btstack_main(int argc, const char * argv[]);
318 int btstack_main(int argc, const char * argv[]){
319 
320     // parse address if command line arguments are provided
321     int arg = 1;
322     cmdline_addr_found = 0;
323 
324     while (arg < argc) {
325         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
326             arg++;
327             cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
328             arg++;
329             if (!cmdline_addr_found) exit(1);
330             continue;
331         }
332         fprintf(stderr, "\nUsage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", argv[0]);
333         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");
334         return 0;
335     }
336     (void)argv;
337 
338     battery_service_client_setup();
339 
340     app_state = APP_STATE_IDLE;
341 
342     // turn on!
343     hci_power_control(HCI_POWER_ON);
344 
345     return 0;
346 }
347 
348 /* EXAMPLE_END */
349 
350 
351