xref: /btstack/example/gatt_battery_query.c (revision cd5f23a3250874824c01a2b3326a9522fea3f99f)
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     uint8_t status;
125     uint8_t att_status;
126 
127     if (hci_event_packet_get_type(packet) != HCI_EVENT_GATTSERVICE_META){
128         return;
129     }
130 
131     switch (hci_event_gattservice_meta_get_subevent_code(packet)){
132         case GATTSERVICE_SUBEVENT_BATTERY_SERVICE_CONNECTED:
133             status = gattservice_subevent_battery_service_connected_get_status(packet);
134             switch (status){
135                 case ERROR_CODE_SUCCESS:
136                     printf("Battery service client connected, found %d services, poll bitmap 0x%02x\n",
137                         gattservice_subevent_battery_service_connected_get_num_instances(packet),
138                         gattservice_subevent_battery_service_connected_get_poll_bitmap(packet));
139                     break;
140                 default:
141                     printf("Battery service client connection failed, err 0x%02x.\n", status);
142                     add_to_blacklist(report.address);
143                     gap_disconnect(connection_handle);
144                     break;
145             }
146             break;
147 
148         case GATTSERVICE_SUBEVENT_BATTERY_SERVICE_LEVEL:
149             att_status = gattservice_subevent_battery_service_level_get_att_status(packet);
150             if (att_status != ATT_ERROR_SUCCESS){
151                 printf("Battery level read failed, ATT Error 0x%02x\n", att_status);
152             } else {
153                 printf("Service index: %d, Battery level: %d\n",
154                     gattservice_subevent_battery_service_level_get_sevice_index(packet),
155                     gattservice_subevent_battery_service_level_get_level(packet));
156 
157             }
158             break;
159 
160         default:
161             break;
162     }
163 }
164 
165 static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
166     UNUSED(channel);
167     UNUSED(size);
168 
169     uint8_t status;
170     bd_addr_t address;
171 
172     if (packet_type != HCI_EVENT_PACKET){
173         return;
174     }
175 
176     switch (hci_event_packet_get_type(packet)) {
177         case BTSTACK_EVENT_STATE:
178             // BTstack activated, get started
179             if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
180             if (cmdline_addr_found){
181                 printf("Connect to %s\n", bd_addr_to_str(cmdline_addr));
182                 app_state = APP_STATE_W4_CONNECT;
183                 gap_connect(cmdline_addr, 0);
184                 break;
185             }
186             printf("Start scanning!\n");
187             app_state = APP_STATE_W4_SCAN_RESULT;
188             gap_set_scan_parameters(0,0x0030, 0x0030);
189             gap_start_scan();
190             break;
191 
192         case GAP_EVENT_ADVERTISING_REPORT:
193             if (app_state != APP_STATE_W4_SCAN_RESULT) return;
194 
195             gap_event_advertising_report_get_address(packet, address);
196             if (blacklist_contains(address)) {
197                 break;
198             }
199             dump_advertising_report(packet);
200 
201             // stop scanning, and connect to the device
202             app_state = APP_STATE_W4_CONNECT;
203             gap_stop_scan();
204             printf("Stop scan. Connect to device with addr %s.\n", bd_addr_to_str(report.address));
205             gap_connect(report.address,report.address_type);
206             break;
207 
208         case HCI_EVENT_LE_META:
209             // wait for connection complete
210             if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
211             if (app_state != APP_STATE_W4_CONNECT) return;
212             connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
213 
214             status = battery_service_client_connect(connection_handle, handle_gatt_client_event, 2000, &battery_service_cid);
215             btstack_assert(status == ERROR_CODE_SUCCESS);
216 
217             app_state = APP_STATE_CONNECTED;
218             printf("Battery service connected.\n");
219             break;
220 
221         case HCI_EVENT_DISCONNECTION_COMPLETE:
222             connection_handle = HCI_CON_HANDLE_INVALID;
223             // Disconnect battery service
224             battery_service_client_disconnect(battery_service_cid);
225 
226             if (cmdline_addr_found){
227                 printf("Disconnected %s\n", bd_addr_to_str(cmdline_addr));
228                 return;
229             }
230 
231             printf("Disconnected %s\n", bd_addr_to_str(report.address));
232             printf("Restart scan.\n");
233             app_state = APP_STATE_W4_SCAN_RESULT;
234             gap_start_scan();
235             break;
236         default:
237             break;
238     }
239 }
240 
241 int btstack_main(int argc, const char * argv[]);
242 int btstack_main(int argc, const char * argv[]){
243 
244     // parse address if command line arguments are provided
245     int arg = 1;
246     cmdline_addr_found = 0;
247 
248     while (arg < argc) {
249         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
250             arg++;
251             cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
252             arg++;
253             if (!cmdline_addr_found) exit(1);
254             continue;
255         }
256         fprintf(stderr, "\nUsage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", argv[0]);
257         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");
258         return 0;
259     }
260     (void)argv;
261 
262     l2cap_init();
263 
264     // setup ATT server - only needed if LE Peripheral does ATT queries on its own, e.g. Android phones
265     att_server_init(profile_data, NULL, NULL);
266 
267     // GATT Client setup
268     gatt_client_init();
269     battery_service_client_init();
270 
271     sm_init();
272     sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
273 
274     hci_event_callback_registration.callback = &hci_event_handler;
275     hci_add_event_handler(&hci_event_callback_registration);
276 
277     app_state = APP_STATE_IDLE;
278 
279     // turn on!
280     hci_power_control(HCI_POWER_ON);
281 
282     return 0;
283 }
284 
285 /* EXAMPLE_END */
286 
287 
288