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