1 package com.bluekitchen; 2 3 import com.bluekitchen.btstack.BD_ADDR; 4 import com.bluekitchen.btstack.BTstack; 5 import com.bluekitchen.btstack.Packet; 6 import com.bluekitchen.btstack.PacketHandler; 7 import com.bluekitchen.btstack.Util; 8 import com.bluekitchen.btstack.event.BTstackEventState; 9 import com.bluekitchen.btstack.event.GAPEventInquiryResult; 10 import com.bluekitchen.btstack.event.GAPEventInquiryComplete; 11 12 import java.nio.charset.StandardCharsets; 13 14 public class GAPInquiry implements PacketHandler { 15 16 private enum STATE { 17 w4_btstack_working, w4_query_result, 18 }; 19 20 private BTstack btstack; 21 private STATE state; 22 23 private void startInquiry(){ 24 state = STATE.w4_query_result; 25 int duration_in_1_28s = 5; 26 btstack.GAPInquiryStart(duration_in_1_28s); 27 } 28 29 public void handlePacket(Packet packet){ 30 switch (state){ 31 case w4_btstack_working: 32 if (packet instanceof BTstackEventState){ 33 BTstackEventState event = (BTstackEventState) packet; 34 if (event.getState() == 2) { 35 System.out.println("BTstack working. Start Inquiry"); 36 startInquiry(); 37 } 38 } 39 break; 40 41 case w4_query_result: 42 if (packet instanceof GAPEventInquiryResult){ 43 GAPEventInquiryResult result = (GAPEventInquiryResult) packet; 44 String name = ""; 45 if (result.getNameAvailable() != 0){ 46 name = Util.getText(result.getName(), 0, result.getNameLen()); 47 System.out.println( "Device found " + result.getBdAddr() + ", name: '" + name + "'"); 48 } else { 49 System.out.println( "Device found " + result.getBdAddr()); 50 } 51 } 52 if (packet instanceof GAPEventInquiryComplete){ 53 // TODO: for devices without name, do a gap_remote_name_request 54 System.out.println("Inquiry done, restart"); 55 startInquiry(); 56 } 57 break; 58 default: 59 break; 60 } 61 } 62 63 void test(){ 64 System.out.println("Inquiry Test Application"); 65 66 // connect to BTstack Daemon via default port on localhost 67 // start: src/BTdaemon --tcp 68 69 btstack = new BTstack(); 70 btstack.setTcpPort(BTstack.DEFAULT_TCP_PORT); 71 btstack.registerPacketHandler(this); 72 boolean ok = btstack.connect(); 73 if (!ok) { 74 System.out.println("Failed to connect to BTstack Server"); 75 return; 76 } 77 78 System.out.println("BTstackSetPowerMode(1)"); 79 80 state = STATE.w4_btstack_working; 81 btstack.BTstackSetPowerMode(1); 82 } 83 84 public static void main(String args[]){ 85 new GAPInquiry().test(); 86 } 87 } 88