xref: /btstack/example/gap_le_advertisements.c (revision bcf00d8fa453bd3a5c441c3b99e6e4b685f0d8f0)
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 /* EXAMPLE_START(gap_le_advertisements): GAP LE Advertisements Dumper
41  *
42  * @text This example shows how to scan and parse advertisements.
43  *
44  */
45  // *****************************************************************************
46 
47 
48 #include <stdint.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 
53 #include "hci_cmd.h"
54 
55 #include "btstack_memory.h"
56 #include "hci.h"
57 #include "ble/ad_parser.h"
58 
59 static btstack_packet_callback_registration_t hci_event_callback_registration;
60 
61 /* @section GAP LE setup for receiving advertisements
62  *
63  * @text GAP LE advertisements are received as custom HCI events of the
64  * GAP_LE_EVENT_ADVERTISING_REPORT type. To receive them, you'll need to register
65  * the HCI packet handler, as shown in Listing GAPLEAdvSetup.
66  */
67 
68 /* LISTING_START(GAPLEAdvSetup): Setting up GAP LE client for receiving advertisements */
69 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
70 
71 static void gap_le_advertisements_setup(void){
72     hci_event_callback_registration.callback = &packet_handler;
73     hci_add_event_handler(&hci_event_callback_registration);
74 }
75 
76 /* LISTING_END */
77 
78 /* @section GAP LE Advertising Data Dumper
79  *
80  * @text Here, we use the definition of advertising data types and flags as specified in
81  * [Assigned Numbers GAP](https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile)
82  * and [Supplement to the Bluetooth Core Specification, v4](https://www.bluetooth.org/DocMan/handlers/DownloadDoc.ashx?doc_id=282152).
83  */
84 
85 /* LISTING_START(GAPLEAdvDataTypesAndFlags): Advertising data types and flags */
86 static char * ad_types[] = {
87     "",
88     "Flags",
89     "Incomplete List of 16-bit Service Class UUIDs",
90     "Complete List of 16-bit Service Class UUIDs",
91     "Incomplete List of 32-bit Service Class UUIDs",
92     "Complete List of 32-bit Service Class UUIDs",
93     "Incomplete List of 128-bit Service Class UUIDs",
94     "Complete List of 128-bit Service Class UUIDs",
95     "Shortened Local Name",
96     "Complete Local Name",
97     "Tx Power Level",
98     "",
99     "",
100     "Class of Device",
101     "Simple Pairing Hash C",
102     "Simple Pairing Randomizer R",
103     "Device ID",
104     "Security Manager TK Value",
105     "Slave Connection Interval Range",
106     "",
107     "List of 16-bit Service Solicitation UUIDs",
108     "List of 128-bit Service Solicitation UUIDs",
109     "Service Data",
110     "Public Target Address",
111     "Random Target Address",
112     "Appearance",
113     "Advertising Interval"
114 };
115 
116 static char * flags[] = {
117     "LE Limited Discoverable Mode",
118     "LE General Discoverable Mode",
119     "BR/EDR Not Supported",
120     "Simultaneous LE and BR/EDR to Same Device Capable (Controller)",
121     "Simultaneous LE and BR/EDR to Same Device Capable (Host)",
122     "Reserved",
123     "Reserved",
124     "Reserved"
125 };
126 /* LISTING_END */
127 
128 /* @text BTstack offers an iterator for parsing sequence of advertising data (AD) structures,
129  * see [BLE advertisements parser API](../appendix/apis/#ble-advertisements-parser-api).
130  * After initializing the iterator, each AD structure is dumped according to its type.
131  */
132 
133 /* LISTING_START(GAPLEAdvDataParsing): Parsing advertising data */
134 static void dump_advertisement_data(uint8_t * adv_data, uint8_t adv_size){
135     ad_context_t context;
136     bd_addr_t address;
137     uint8_t uuid_128[16];
138     for (ad_iterator_init(&context, adv_size, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
139         uint8_t data_type = ad_iterator_get_data_type(&context);
140         uint8_t size      = ad_iterator_get_data_len(&context);
141         uint8_t * data    = ad_iterator_get_data(&context);
142 
143         if (data_type > 0 && data_type < 0x1B){
144             printf("    %s: ", ad_types[data_type]);
145         }
146         int i;
147         // Assigned Numbers GAP
148 
149         switch (data_type){
150             case 0x01: // Flags
151                 // show only first octet, ignore rest
152                 for (i=0; i<8;i++){
153                     if (data[0] & (1<<i)){
154                         printf("%s; ", flags[i]);
155                     }
156 
157                 }
158                 break;
159             case 0x02: // Incomplete List of 16-bit Service Class UUIDs
160             case 0x03: // Complete List of 16-bit Service Class UUIDs
161             case 0x14: // List of 16-bit Service Solicitation UUIDs
162                 for (i=0; i<size;i+=2){
163                     printf("%02X ", little_endian_read_16(data, i));
164                 }
165                 break;
166             case 0x04: // Incomplete List of 32-bit Service Class UUIDs
167             case 0x05: // Complete List of 32-bit Service Class UUIDs
168                 for (i=0; i<size;i+=4){
169                     printf("%04X ", little_endian_read_32(data, i));
170                 }
171                 break;
172             case 0x06: // Incomplete List of 128-bit Service Class UUIDs
173             case 0x07: // Complete List of 128-bit Service Class UUIDs
174             case 0x15: // List of 128-bit Service Solicitation UUIDs
175                 reverse_128(data, uuid_128);
176                 printf("%s", uuid128_to_str(uuid_128));
177                 break;
178             case 0x08: // Shortened Local Name
179             case 0x09: // Complete Local Name
180                 for (i=0; i<size;i++){
181                     printf("%c", (char)(data[i]));
182                 }
183                 break;
184             case 0x0A: // Tx Power Level
185                 printf("%d dBm", *(int8_t*)data);
186                 break;
187             case 0x12: // Slave Connection Interval Range
188                 printf("Connection Interval Min = %u ms, Max = %u ms", little_endian_read_16(data, 0) * 5/4, little_endian_read_16(data, 2) * 5/4);
189                 break;
190             case 0x16: // Service Data
191                 printf_hexdump(data, size);
192                 break;
193             case 0x17: // Public Target Address
194             case 0x18: // Random Target Address
195                 reverse_bd_addr(data, address);
196                 printf("%s", bd_addr_to_str(address));
197                 break;
198             case 0x19: // Appearance
199                 // https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml
200                 printf("%02X", little_endian_read_16(data, 0) );
201                 break;
202             case 0x1A: // Advertising Interval
203                 printf("%u ms", little_endian_read_16(data, 0) * 5/8 );
204                 break;
205             case 0x3D: // 3D Information Data
206                 printf_hexdump(data, size);
207                 break;
208             case 0xFF: // Manufacturer Specific Data
209                 break;
210             case 0x0D: // Class of Device (3B)
211             case 0x0E: // Simple Pairing Hash C (16B)
212             case 0x0F: // Simple Pairing Randomizer R (16B)
213             case 0x10: // Device ID
214             case 0x11: // Security Manager TK Value (16B)
215             default:
216                 printf("Unknown Advertising Data Type");
217                 break;
218         }
219         printf("\n");
220     }
221     printf("\n");
222 }
223 /* LISTING_END */
224 
225 /* @section HCI packet handler
226  *
227  * @text The HCI packet handler has to start the scanning,
228  * and to handle received advertisements. Advertisements are received
229  * as HCI event packets of the GAP_LE_EVENT_ADVERTISING_REPORT type,
230  * see Listing GAPLEAdvPacketHandler.
231  */
232 
233 /* LISTING_START(GAPLEAdvPacketHandler): Scanning and receiving advertisements */
234 
235 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
236     if (packet_type != HCI_EVENT_PACKET) return;
237 
238     switch (packet[0]) {
239         case BTSTACK_EVENT_STATE:
240             // BTstack activated, get started
241             if (packet[2] == HCI_STATE_WORKING) {
242                 printf("BTstack activated, start scaning!\n");
243                 gap_set_scan_parameters(0,0x0030, 0x0030);
244                 gap_start_scan();
245             }
246             break;
247         case GAP_LE_EVENT_ADVERTISING_REPORT:{
248             int pos = 2;
249             uint8_t event_type = packet[pos++];
250             uint8_t address_type = packet[pos++];
251             bd_addr_t address;
252             reverse_bd_addr(&packet[pos], address);
253             pos += 6;
254             uint8_t rssi = packet[pos++];
255             uint8_t length = packet[pos++];
256             uint8_t * data = &packet[pos];
257 
258             printf("Advertisement event: evt-type %u, addr-type %u, addr %s, rssi %u, data[%u] ", event_type,
259                address_type, bd_addr_to_str(address), rssi, length);
260             printf_hexdump(data, length);
261             dump_advertisement_data(data, length);
262             break;
263         }
264         default:
265             break;
266     }
267 }
268 /* LISTING_END */
269 
270 int btstack_main(void);
271 int btstack_main(void)
272 {
273     gap_le_advertisements_setup();
274 
275     // turn on!
276     hci_power_control(HCI_POWER_ON);
277 
278     return 0;
279 }
280 
281 /* EXAMPLE_END */