xref: /btstack/example/gatt_battery_query.c (revision 6897da5c53aac5b1f90f41b5b15d0bd43d61dfff)
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 BLUEKITCHEN
24  * GMBH 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 
175     if (packet_type != HCI_EVENT_PACKET){
176         return;
177     }
178 
179     switch (hci_event_packet_get_type(packet)) {
180         /* LISTING_PAUSE */
181 
182         case BTSTACK_EVENT_STATE:
183             // BTstack activated, get started
184             if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
185             if (cmdline_addr_found){
186                 printf("Connect to %s\n", bd_addr_to_str(cmdline_addr));
187                 app_state = APP_STATE_W4_CONNECT;
188                 gap_connect(cmdline_addr, 0);
189                 break;
190             }
191             printf("Start scanning!\n");
192             app_state = APP_STATE_W4_SCAN_RESULT;
193             gap_set_scan_parameters(0,0x0030, 0x0030);
194             gap_start_scan();
195             break;
196 
197         case GAP_EVENT_ADVERTISING_REPORT:
198             if (app_state != APP_STATE_W4_SCAN_RESULT) return;
199 
200             gap_event_advertising_report_get_address(packet, report.address);
201             report.address_type = gap_event_advertising_report_get_address_type(packet);
202             if (blacklist_contains(report.address)) {
203                 break;
204             }
205             dump_advertising_report(packet);
206 
207             // stop scanning, and connect to the device
208             app_state = APP_STATE_W4_CONNECT;
209             gap_stop_scan();
210             printf("Stop scan. Connect to device with addr %s.\n", bd_addr_to_str(report.address));
211             gap_connect(report.address,report.address_type);
212             break;
213 
214         /* LISTING_RESUME */
215         case HCI_EVENT_META_GAP:
216             // Wait for connection complete
217             if (hci_event_gap_meta_get_subevent_code(packet) !=  GAP_SUBEVENT_LE_CONNECTION_COMPLETE) break;
218 
219             /* LISTING_PAUSE */
220             if (app_state != APP_STATE_W4_CONNECT) return;
221 
222             /* LISTING_RESUME */
223             // Get connection handle from event
224             connection_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
225 
226             // Connect to remote Battery Service.
227             // On succesful connection, the client tries to register for notifications. If notifications
228             // are not supported by remote Battery Service, the client will automatically poll the battery level - here every 2 seconds.
229             // If poll_interval_ms is 0, polling is disabled, and only notifications will be received (for manual polling,
230             // see battery_service_client.h).
231             // All GATT Battery Service events are handled by the gatt_client_event_handler.
232             (void) battery_service_client_connect(connection_handle, gatt_client_event_handler, 2000, &battery_service_cid);
233 
234             app_state = APP_STATE_CONNECTED;
235             printf("Battery service connected.\n");
236             break;
237 
238         case HCI_EVENT_DISCONNECTION_COMPLETE:
239             connection_handle = HCI_CON_HANDLE_INVALID;
240             // Disconnect battery service
241             battery_service_client_disconnect(battery_service_cid);
242 
243             /* LISTING_PAUSE */
244             if (cmdline_addr_found){
245                 printf("Disconnected %s\n", bd_addr_to_str(cmdline_addr));
246                 return;
247             }
248 
249             /* LISTING_RESUME */
250             printf("Disconnected %s\n", bd_addr_to_str(report.address));
251             printf("Restart scan.\n");
252             app_state = APP_STATE_W4_SCAN_RESULT;
253             gap_start_scan();
254             break;
255         default:
256             break;
257     }
258 }
259 /* LISTING_END */
260 
261 /* LISTING_START(gatt_client_event_handler): GATT Client Event Handler */
262 // The gatt_client_event_handler receives following events from remote device:
263 //  - GATTSERVICE_SUBEVENT_BATTERY_SERVICE_CONNECTED
264 //  - GATTSERVICE_SUBEVENT_BATTERY_SERVICE_LEVEL
265 //
266 static void gatt_client_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
267     /* LISTING_PAUSE */
268     UNUSED(packet_type);
269     UNUSED(channel);
270     UNUSED(size);
271 
272     /* LISTING_RESUME */
273     uint8_t status;
274     uint8_t att_status;
275 
276     if (hci_event_packet_get_type(packet) != HCI_EVENT_GATTSERVICE_META){
277         return;
278     }
279 
280     switch (hci_event_gattservice_meta_get_subevent_code(packet)){
281         case GATTSERVICE_SUBEVENT_BATTERY_SERVICE_CONNECTED:
282             status = gattservice_subevent_battery_service_connected_get_status(packet);
283             switch (status){
284                 case ERROR_CODE_SUCCESS:
285                     printf("Battery service client connected, found %d services, poll bitmap 0x%02x\n",
286                         gattservice_subevent_battery_service_connected_get_num_instances(packet),
287                         gattservice_subevent_battery_service_connected_get_poll_bitmap(packet));
288                         battery_service_client_read_battery_level(battery_service_cid, 0);
289                     break;
290                 default:
291                     printf("Battery service client connection failed, status 0x%02x.\n", status);
292                     add_to_blacklist(report.address);
293                     gap_disconnect(connection_handle);
294                     break;
295             }
296             break;
297 
298         case GATTSERVICE_SUBEVENT_BATTERY_SERVICE_LEVEL:
299             att_status = gattservice_subevent_battery_service_level_get_att_status(packet);
300             if (att_status != ATT_ERROR_SUCCESS){
301                 printf("Battery level read failed, ATT Error 0x%02x\n", att_status);
302             } else {
303                 printf("Service index: %d, Battery level: %d\n",
304                     gattservice_subevent_battery_service_level_get_sevice_index(packet),
305                     gattservice_subevent_battery_service_level_get_level(packet));
306 
307             }
308             break;
309 
310         default:
311             break;
312     }
313 }
314  /* LISTING_END */
315 
316 int btstack_main(int argc, const char * argv[]);
317 int btstack_main(int argc, const char * argv[]){
318 
319     // parse address if command line arguments are provided
320     int arg;
321     cmdline_addr_found = 0;
322 
323     for (arg = 1; arg < argc; arg++) {
324         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
325             if (arg + 1 < argc) {
326                 arg++;
327                 cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
328             }
329             if (!cmdline_addr_found) {
330                 fprintf(stderr, "\nUsage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", argv[0]);
331                 fprintf(stderr, "If no argument is provided, %s will start scanning and connect to the first found device.\n"
332                                 "To connect to a specific device use argument [-a].\n\n", argv[0]);
333                 return 1;
334             }
335         }
336     }
337     if (!cmdline_addr_found) {
338         fprintf(stderr, "No specific address specified or found; start scanning for any advertiser.\n");
339     }
340 
341     battery_service_client_setup();
342 
343     app_state = APP_STATE_IDLE;
344 
345     // turn on!
346     hci_power_control(HCI_POWER_ON);
347 
348     return 0;
349 }
350 
351 /* EXAMPLE_END */
352 
353 
354