xref: /btstack/platform/daemon/example/inquiry.c (revision b3fcedb9c9ccbcc9680da165cd86f394be5d84a8)
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  *  inquiry.c
40  *
41  *  basic inquiry scan with remote name lookup
42  */
43 
44 #include <unistd.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 
49 #include "btstack_client.h"
50 #include "btstack_run_loop_posix.h"
51 
52 #define MAX_DEVICES 10
53 struct device {
54 	bd_addr_t  address;
55 	uint16_t   clockOffset;
56 	uint32_t   classOfDevice;
57 	uint8_t	   pageScanRepetitionMode;
58 	uint8_t    rssi;
59 	uint8_t    state; // 0 empty, 1 found, 2 remote name tried, 3 remote name found
60 };
61 
62 #define INQUIRY_INTERVAL 5
63 struct device devices[MAX_DEVICES];
64 int deviceCount = 0;
65 
66 enum STATE {INIT, W4_INQUIRY_MODE_COMPLETE, ACTIVE, DEVICE_NAME, REMOTE_NAME_REQUEST, REMOTE_NAME_INQUIRED, REMOTE_NAME_FETCHED} ;
67 enum STATE state = INIT;
68 
69 int getDeviceIndexForAddress( bd_addr_t addr){
70 	int j;
71 	for (j=0; j< deviceCount; j++){
72 		if (bd_addr_cmp(addr, devices[j].address) == 0){
73 			return j;
74 		}
75 	}
76 	return -1;
77 }
78 
79 void start_scan(void){
80 	printf("Starting inquiry scan..\n");
81 	bt_send_cmd(&hci_inquiry, HCI_INQUIRY_LAP, INQUIRY_INTERVAL, 0);
82 }
83 
84 int has_more_remote_name_requests(void){
85 	int i;
86 	for (i=0;i<deviceCount;i++) {
87 		if (devices[i].state == REMOTE_NAME_REQUEST) return 1;
88 	}
89 	return 0;
90 }
91 
92 void do_next_remote_name_request(void){
93 	int i;
94 	for (i=0;i<deviceCount;i++) {
95 		// remote name request
96 		if (devices[i].state == REMOTE_NAME_REQUEST){
97 			devices[i].state = REMOTE_NAME_INQUIRED;
98 			printf("Get remote name of %s...\n", bd_addr_to_str(devices[i].address));
99 			bt_send_cmd(&hci_remote_name_request, devices[i].address,
100 								devices[i].pageScanRepetitionMode, 0, devices[i].clockOffset | 0x8000);
101 			return;
102 		}
103 	}
104 }
105 
106 
107 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
108 //static void packet_handler (uint8_t packet_type, uint8_t *packet, uint16_t size){
109 	bd_addr_t addr;
110 	int i;
111 	int index;
112 	int numResponses;
113 
114 	// printf("packet_handler: pt: 0x%02x, packet[0]: 0x%02x\n", packet_type, packet[0]);
115 	if (packet_type != HCI_EVENT_PACKET) return;
116 
117 	uint8_t event = hci_event_packet_get_type(packet);
118 
119 	switch(state){
120 
121 		case INIT:
122 			if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
123 				bt_send_cmd(&hci_write_inquiry_mode, 0x01); // with RSSI
124 				state = W4_INQUIRY_MODE_COMPLETE;
125 			}
126 			break;
127 
128 		case W4_INQUIRY_MODE_COMPLETE:
129 			switch(event){
130 				case HCI_EVENT_COMMAND_COMPLETE:
131 					if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_inquiry_mode)) {
132 						start_scan();
133 						state = ACTIVE;
134 					}
135 					break;
136 				case HCI_EVENT_COMMAND_STATUS:
137 					if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_write_inquiry_mode)) {
138 						printf("Ignoring error (0x%x) from hci_write_inquiry_mode.\n", packet[2]);
139 						start_scan();
140 						state = ACTIVE;
141 					}
142 					break;
143 				default:
144 					break;
145 			}
146 
147 			break;
148 
149 		case ACTIVE:
150 			switch(event){
151 				case HCI_EVENT_INQUIRY_RESULT:
152 				case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
153                     numResponses = hci_event_inquiry_result_get_num_responses(packet);
154                     int offset = 3;
155                     for (i=0; i<numResponses && deviceCount < MAX_DEVICES;i++){
156                         reverse_bd_addr(&packet[offset], addr);
157                         offset += 6;
158                         index = getDeviceIndexForAddress(addr);
159                         if (index >= 0) continue;   // already in our list
160                         memcpy(devices[deviceCount].address, addr, 6);
161 
162                         devices[deviceCount].pageScanRepetitionMode = packet[offset];
163                         offset += 1;
164 
165                         if (event == HCI_EVENT_INQUIRY_RESULT){
166                             offset += 2; // Reserved + Reserved
167                             devices[deviceCount].classOfDevice = little_endian_read_24(packet, offset);
168                             offset += 3;
169                             devices[deviceCount].clockOffset =   little_endian_read_16(packet, offset) & 0x7fff;
170                             offset += 2;
171                             devices[deviceCount].rssi  = 0;
172                         } else {
173                             offset += 1; // Reserved
174                             devices[deviceCount].classOfDevice = little_endian_read_24(packet, offset);
175                             offset += 3;
176                             devices[deviceCount].clockOffset =   little_endian_read_16(packet, offset) & 0x7fff;
177                             offset += 2;
178                             devices[deviceCount].rssi  = packet[offset];
179                             offset += 1;
180                         }
181                         devices[deviceCount].state = REMOTE_NAME_REQUEST;
182                         printf("Device found: %s with COD: 0x%06x, pageScan %d, clock offset 0x%04x, rssi 0x%02x\n", bd_addr_to_str(addr),
183                                 devices[deviceCount].classOfDevice, devices[deviceCount].pageScanRepetitionMode,
184                                 devices[deviceCount].clockOffset, devices[deviceCount].rssi);
185                         deviceCount++;
186                     }
187 
188                     break;
189                 }
190 
191 				case HCI_EVENT_INQUIRY_COMPLETE:
192 					for (i=0;i<deviceCount;i++) {
193 						// retry remote name request
194 						if (devices[i].state == REMOTE_NAME_INQUIRED)
195 							devices[i].state = REMOTE_NAME_REQUEST;
196 					}
197 					if (has_more_remote_name_requests()){
198 						do_next_remote_name_request();
199 						break;
200 					}
201 					start_scan();
202 					break;
203 
204 				case DAEMON_EVENT_REMOTE_NAME_CACHED:
205 					reverse_bd_addr(&packet[3], addr);
206 					printf("Cached remote name for %s: '%s'\n", bd_addr_to_str(addr), &packet[9]);
207 					break;
208 
209 				case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
210 					reverse_bd_addr(&packet[3], addr);
211 					index = getDeviceIndexForAddress(addr);
212 					if (index >= 0) {
213 						if (packet[2] == 0) {
214 							printf("Name: '%s'\n", &packet[9]);
215 							devices[index].state = REMOTE_NAME_FETCHED;
216 						} else {
217 							printf("Failed to get name: page timeout\n");
218 						}
219 					}
220 					if (has_more_remote_name_requests()){
221 						do_next_remote_name_request();
222 						break;
223 					}
224 					start_scan();
225 					break;
226 
227 				default:
228 					break;
229 			}
230 			break;
231 
232 		default:
233 			break;
234 	}
235 }
236 
237 int main (int argc, const char * argv[]){
238 	// start stack
239 	btstack_run_loop_init(btstack_run_loop_posix_get_instance());
240 	int err = bt_open();
241 	if (err) {
242 		printf("Failed to open connection to BTdaemon\n");
243 		return err;
244 	}
245 	// init table
246 	int i; for (i=0;i<MAX_DEVICES;i++) devices[i].state = 0;
247 
248 	bt_register_packet_handler(packet_handler);
249 	bt_send_cmd(&btstack_set_power_mode, HCI_POWER_ON );
250 	btstack_run_loop_execute();
251 	bt_close();
252 	return 0;
253 }
254