xref: /btstack/example/gatt_battery_query.c (revision 83b6788cc176b84e4053592dc57941e20a8b19d5)
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 Client
42  *
43  */
44 
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 
50 #include "btstack.h"
51 
52 // gatt_battery_query.gatt contains the declaration of the provided GATT Services + Characteristics
53 // gatt_battery_query.h    contains the binary representation of gatt_battery_query.gatt
54 // it is generated by the build system by calling: $BTSTACK_ROOT/tool/compile_gatt.py gatt_battery_query.gatt gatt_battery_query.h
55 // it needs to be regenerated when the GATT Database declared in gatt_battery_query.gatt file is modified
56 #include "gatt_battery_query.h"
57 
58 typedef struct advertising_report {
59     uint8_t   type;
60     uint8_t   event_type;
61     uint8_t   address_type;
62     bd_addr_t address;
63     uint8_t   rssi;
64     uint8_t   length;
65     const uint8_t * data;
66 } advertising_report_t;
67 
68 static enum {
69     APP_STATE_IDLE,
70     APP_STATE_W4_SCAN_RESULT,
71     APP_STATE_W4_CONNECT,
72     APP_STATE_CONNECTED
73 } app_state;
74 
75 static int blacklist_index = 0;
76 static bd_addr_t blacklist[20];
77 static advertising_report_t report;
78 
79 static hci_con_handle_t connection_handle;
80 static uint16_t battery_service_cid;
81 
82 static bd_addr_t cmdline_addr;
83 static int cmdline_addr_found = 0;
84 
85 static btstack_packet_callback_registration_t hci_event_callback_registration;
86 
87 static int blacklist_size(void){
88     return sizeof(blacklist) / sizeof(bd_addr_t);
89 }
90 
91 static int blacklist_contains(bd_addr_t addr){
92     int i;
93     for (i=0; i<blacklist_size(); i++){
94         if (bd_addr_cmp(addr, blacklist[i]) == 0) return 1;
95     }
96     return 0;
97 }
98 
99 static void add_to_blacklist(bd_addr_t addr){
100     printf("%s added to blacklist (no battery service found\n", bd_addr_to_str(addr));
101     bd_addr_copy(blacklist[blacklist_index], addr);
102     blacklist_index = (blacklist_index + 1) % blacklist_size();
103 }
104 
105 static void dump_advertising_report(uint8_t *packet){
106     bd_addr_t address;
107     gap_event_advertising_report_get_address(packet, address);
108 
109     printf("    * adv. event: evt-type %u, addr-type %u, addr %s, rssi %u, length adv %u, data: ",
110         gap_event_advertising_report_get_advertising_event_type(packet),
111         gap_event_advertising_report_get_address_type(packet),
112         bd_addr_to_str(address),
113         gap_event_advertising_report_get_rssi(packet),
114         gap_event_advertising_report_get_data_length(packet));
115     printf_hexdump(gap_event_advertising_report_get_data(packet), gap_event_advertising_report_get_data_length(packet));
116 
117 }
118 
119 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
120     UNUSED(packet_type);
121     UNUSED(channel);
122     UNUSED(size);
123 
124     int status;
125 
126     if (hci_event_packet_get_type(packet) != HCI_EVENT_GATTSERVICE_META){
127         return;
128     }
129 
130     switch (hci_event_gattservice_meta_get_subevent_code(packet)){
131         case GATTSERVICE_SUBEVENT_BATTERY_SERVICE_CONNECTED:
132             status = gattservice_subevent_battery_service_connected_get_status(packet);
133             switch (status){
134                 case ERROR_CODE_SUCCESS:
135                     printf("Battery service client connected - found %d services",
136                         gattservice_subevent_battery_service_connected_get_num_instances(packet));
137                     break;
138                 default:
139                     printf("Battery service client connection failed - Error status 0x%02x.\n", status);
140                     add_to_blacklist(report.address);
141                     gap_disconnect(connection_handle);
142                     break;
143             }
144             break;
145 
146         case GATTSERVICE_SUBEVENT_BATTERY_SERVICE_LEVEL:
147             printf("Service index: %d, Battery level %d \n",
148                 gattservice_subevent_battery_service_level_get_sevice_index(packet),
149                 gattservice_subevent_battery_service_level_get_level(packet));
150             break;
151 
152         default:
153             break;
154     }
155 }
156 
157 static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
158     UNUSED(channel);
159     UNUSED(size);
160 
161     uint8_t status;
162     bd_addr_t address;
163 
164     if (packet_type != HCI_EVENT_PACKET){
165         return;
166     }
167 
168     switch (hci_event_packet_get_type(packet)) {
169         case BTSTACK_EVENT_STATE:
170             // BTstack activated, get started
171             if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
172             if (cmdline_addr_found){
173                 printf("Connect to %s\n", bd_addr_to_str(cmdline_addr));
174                 app_state = APP_STATE_W4_CONNECT;
175                 gap_connect(cmdline_addr, 0);
176                 break;
177             }
178             printf("Start scanning!\n");
179             app_state = APP_STATE_W4_SCAN_RESULT;
180             gap_set_scan_parameters(0,0x0030, 0x0030);
181             gap_start_scan();
182             break;
183 
184         case GAP_EVENT_ADVERTISING_REPORT:
185             if (app_state != APP_STATE_W4_SCAN_RESULT) return;
186 
187             gap_event_advertising_report_get_address(packet, address);
188             if (blacklist_contains(address)) {
189                 break;
190             }
191             dump_advertising_report(packet);
192 
193             // stop scanning, and connect to the device
194             app_state = APP_STATE_W4_CONNECT;
195             gap_stop_scan();
196             printf("Stop scan. Connect to device with addr %s.\n", bd_addr_to_str(report.address));
197             gap_connect(report.address,report.address_type);
198             break;
199 
200         case HCI_EVENT_LE_META:
201             // wait for connection complete
202             if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
203             if (app_state != APP_STATE_W4_CONNECT) return;
204             connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
205 
206             status = battery_service_client_connect(connection_handle, handle_gatt_client_event, &battery_service_cid);
207             btstack_assert(status == ERROR_CODE_SUCCESS);
208 
209             app_state = APP_STATE_CONNECTED;
210             printf("Battery service connected.\n");
211             break;
212 
213         case HCI_EVENT_DISCONNECTION_COMPLETE:
214             connection_handle = HCI_CON_HANDLE_INVALID;
215             // Disconnect battery service
216             battery_service_client_disconnect(battery_service_cid);
217 
218             if (cmdline_addr_found){
219                 printf("Disconnected %s\n", bd_addr_to_str(cmdline_addr));
220                 return;
221             }
222 
223             printf("Disconnected %s\n", bd_addr_to_str(report.address));
224             printf("Restart scan.\n");
225             app_state = APP_STATE_W4_SCAN_RESULT;
226             gap_start_scan();
227             break;
228         default:
229             break;
230     }
231 }
232 
233 int btstack_main(int argc, const char * argv[]);
234 int btstack_main(int argc, const char * argv[]){
235 
236     // parse address if command line arguments are provided
237     int arg = 1;
238     cmdline_addr_found = 0;
239 
240     while (arg < argc) {
241         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
242             arg++;
243             cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
244             arg++;
245             if (!cmdline_addr_found) exit(1);
246             continue;
247         }
248         fprintf(stderr, "\nUsage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", argv[0]);
249         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");
250         return 0;
251     }
252     (void)argv;
253 
254     l2cap_init();
255 
256     // setup ATT server - only needed if LE Peripheral does ATT queries on its own, e.g. Android phones
257     att_server_init(profile_data, NULL, NULL);
258 
259     // GATT Client setup
260     gatt_client_init();
261     battery_service_client_init();
262 
263     sm_init();
264     sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
265 
266     hci_event_callback_registration.callback = &hci_event_handler;
267     hci_add_event_handler(&hci_event_callback_registration);
268 
269     app_state = APP_STATE_IDLE;
270 
271     // turn on!
272     hci_power_control(HCI_POWER_ON);
273 
274     return 0;
275 }
276 
277 /* EXAMPLE_END */
278 
279 
280