public class BTClient implements Runnable, DiscoveryListener {
static ServiceRecord record = null;
private static final UUID thisServerUUID = new UUID("F0E0D0C0B0A000918273645546372819", false);
private LocalDevice localDevice;
private DiscoveryAgent agent;
boolean result = false;
boolean master = true;
private int serviceSearchCount;
private int transactionID[];
private int maxServiceSearches = 0;
private int discType;
int iterator = 0;
Vector service = new Vector();
ServiceRecord[] recordTab = new ServiceRecord[10];
RemoteDevice[] devList;
static int selected = -1;
String url = null;
static DataOutputStream op = null;
static StreamConnection conn = null;
boolean ok = true;
HelloMIDlet hello;
private long timeSendSingnalOnline = 5000;
private long tmpTimeSendSignal = System.currentTimeMillis();
/**
*
* @param list
*/
public BTClient(MIDlet midlet) {
//this.server = BTInit.server;
this.hello = (HelloMIDlet) midlet;
//this.state = true;
synchronized (this) {
try {
localDevice = LocalDevice.getLocalDevice();
} catch (BluetoothStateException ex) {
ex.printStackTrace();
}
agent = localDevice.getDiscoveryAgent();
try {
maxServiceSearches = Integer.parseInt(LocalDevice.getProperty("bluetooth.sd.trans.max"));
} catch (NumberFormatException e) {
System.out.println("General Application Error");
System.out.println("\tNumberFormatException: " + e.getMessage());
}
}
}
public void destroy() {
if (transactionID != null) {
for (int i = 0; i < transactionID.length; i++) {
//if (transactionID[i] != -1) {
agent.cancelServiceSearch(transactionID[i]);
//}
}
}
}
/**
*
*/
public void run() {
hello.getList().deleteAll();
for (int j = 0; j < iterator; j++) {
recordTab[j] = null;
}
iterator = 0;
service.removeAllElements();
destroy();
try {
this.findService();
select();
destroy();
agent.cancelInquiry(this);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (Throwable e) {
System.out.println("Unable to find devices to search" + e.getMessage());
}
}
/**
*
* @param btDevice
* @param cod
*/
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
service.addElement(btDevice);
this.findService();
}
/**
*
* @param discType
*/
public void inquiryCompleted(int discType) {
this.discType = discType;
}
/**
*
* @param transID
* @param respCode
*/
public void serviceSearchCompleted(int transID, int respCode) {
removeFromTransactionTable(transID);
serviceSearchCount--;
synchronized (this) {
this.notifyAll();
}
}
/**
*
* @param transID
* @param servRecord
*/
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
System.out.println("Found a service " + transID);
// System.out.println("Length of array = " + servRecord.length);
if (servRecord[0] == null) {
System.out.println("The service record is null");
}
System.out.println("servRecord " + servRecord.toString());
if (iterator < 10) {
for (int j = 0; j < iterator; j++) {
if (recordTab[j].getHostDevice() == servRecord[0].getHostDevice()) {
return;
}
}
hello.getList().append(servRecord[0].getHostDevice().getBluetoothAddress().toString(), null);
recordTab[iterator] = servRecord[0];
System.out.println("iterator " + iterator);
//service.addElement(servRecord[0]);
iterator++;
} else {
return;
}
// System.out.println("After this");
if (record == null) {
// System.out.println("THe Seocnd try was null");
}
if (transactionID != null) {
for (int i = 0; i < transactionID.length; i++) {
if (transactionID[i] != -1) {
//agent.cancelServiceSearch(transactionID[i]);
//System.out.println(agent.cancelServiceSearch(transactionID[i]));
//System.out.println(transactionID[i]);
}
}
}
// }
}
/**
*
* @param attrSet
* @param uuidSet
* @param btDev
* @param discListener
* @return
* @throws BluetoothStateException
*/
public int searchServices(int[] attrSet, UUID[] uuidSet, RemoteDevice btDev, DiscoveryListener discListener) throws BluetoothStateException {
System.out.println("uuidSet " + uuidSet);
return agent.searchServices(attrSet, uuidSet, btDev, discListener);
}
/**
*
* @param uuid
* @param security
* @param master
* @return
* @throws BluetoothStateException
*/
public String selectService(UUID uuid, int security, boolean master) throws BluetoothStateException {
return agent.selectService(uuid, security, master);
}
private void addToTransactionTable(int trans) {
transactionID = new int[maxServiceSearches];
for (int i = 0; i < transactionID.length; i++) {
if (transactionID[i] == -1) {
transactionID[i] = trans;
return;
}
}
}
private boolean searchServices() {
UUID[] searchList = new UUID[2];
searchList[0] = new UUID(0x1101);
searchList[1] = thisServerUUID;
System.out.println("service.size() " + service.size());
// for (int i = 0; i < devList.length; i++) {
for (int i = 0; i < service.size(); i++) {
RemoteDevice rd = (RemoteDevice) service.elementAt(i);
try {
// System.out.println("Starting Service Search on " + devList[i].getBluetoothAddress());
System.out.println("agent " + null + " 123 " + searchList + " 123 " + rd + " 123 " + this + " 123 " + agent);
//int trans = agent.searchServices(null, searchList, devList[i], this);
int trans = agent.searchServices(null, searchList, rd, this);
// System.out.println("Starting Service Search " + trans);
addToTransactionTable(trans);
//servicesDiscovered(trans, recordTab);
} catch (BluetoothStateException e) {
System.out.println("BluetoothStateException: " + e.getMessage());
/*
* Failed to start the search on this device, try another
* device.
*/
} catch (NullPointerException e) {
//e.printStackTrace();
System.err.println("NullPointerException: " + e.getMessage());
} catch (Error e) {
System.out.println("Unable to find devices to search" + e.getMessage());
} catch (Exception e) {
System.out.println("Unable to find devices to search" + e.getMessage());
} catch (Throwable e) {
System.out.println("Unable to find devices to search" + e.getMessage());
}
/*
* Determine if another search can be started. If not, wait for
* a service search to end.
*/
synchronized (this) {
serviceSearchCount++;
// System.out.println("maxServiceSearches = " + maxServiceSearches);
// System.out.println("serviceSearchCount = " + serviceSearchCount);
if (serviceSearchCount == maxServiceSearches) {
// System.out.println("Waiting");
try {
this.wait();
} catch (Exception e) {
}
}
// System.out.println("Done Waiting " + serviceSearchCount);
}
}
/*
* Wait until all the service searches have completed.
*/
while (serviceSearchCount > 0) {
synchronized (this) {
try {
this.wait();
} catch (Exception e) {
}
}
}
if (record != null) {
// System.out.println("Record is not null");
return true;
} else {
// System.out.println("Record is null");
return false;
}
}
/**
*
* @return
*/
public ServiceRecord findService() {
// ServiceRecord record = this.record;
searchServices();
try {
agent.startInquiry(DiscoveryAgent.LIAC, this);
} catch (BluetoothStateException e) {
System.out.println("Unable to find devices to search");
} catch (Error e) {
System.out.println("Unable to find devices to search" + e.getMessage());
} catch (Exception e) {
System.out.println("Unable to find devices to search" + e.getMessage());
} catch (Throwable e) {
System.out.println("Unable to find devices to search" + e.getMessage());
}
switch (discType) {
case INQUIRY_ERROR:
System.err.println("Device discovering error...");
try {
//master = !master;
//url = LocalDevice.getLocalDevice().getRecord(null).getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, true);
//conn = (StreamConnection) Connector.open(url);
session = (SessionNotifierImpl) conn;
LocalDevice.getLocalDevice().getRecord(conn);
localDevice.updateRecord(record);
} catch (IOException ex) {
ex.printStackTrace();
}
BTClient.record = null;
System.err.println("bluetooth.master.switch " + LocalDevice.getProperty("bluetooth.master.switch"));
BTServer.other = null;
BTTaskManager.auto = -1;
BTInit.taskMan.delate();
BTInit.taskMan.abordConn();
agent.cancelInquiry(this);
exit();
//destroy();
// fall through
case INQUIRY_TERMINATED:
// make sure no garbage in found devices list
service.removeAllElements();
// nothing to report - go to next request
break;
case INQUIRY_COMPLETED:
if (service.size() == 0) {
System.err.println("system error:" + " service.size() == 0 ");
}
// go to service search now
break;
default:
// what kind of system you are?... :(
System.err.println("system error:" + " unexpected device discovery code: ");
destroy();
return null;
}
return null;
}
private void removeFromTransactionTable(int trans) {
for (int i = 0; i < transactionID.length; i++) {
// if (transactionID[i] == trans) {
transactionID[i] = -1;
//return;
// }
}
}
private void select() {
tmpTimeSendSignal = System.currentTimeMillis();
while (selected == -1 || record == null) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
if (selected > -1) {
System.out.println(record + " " + recordTab[selected]);
System.out.println(selected);
System.out.println("records " + recordTab[0] + " " + recordTab[1] + " " + iterator);
System.out.println("records " + recordTab[2] + " " + recordTab[3] + " " + iterator);
System.out.println("records " + recordTab[4] + " " + recordTab[5] + " " + iterator);
System.out.println("records " + recordTab[6] + " " + recordTab[7] + " " + iterator);
System.out.println("records " + recordTab[8] + " " + recordTab[9] + " " + iterator);
}
if (BTServer.other != null) {
for (int j = 0; j < iterator; j++) {
System.out.println(this.recordTab[j].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false) + " " + "btspp://" + BTServer.other + ":1;master=false;encrypt=false;authenticate=false" + " " + selected);
if ((this.recordTab[j].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false)).equals("btspp://" + BTServer.other + ":1;master=false;encrypt=false;authenticate=false")) {
//System.out.println(3);
BTClient.record = this.recordTab[j];
try {
while (record == null) {
}
// System.out.println(4);
url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, !master);
conn = (StreamConnection) Connector.open(url);
op = conn.openDataOutputStream();
//BTTaskManager.auto=true;
destroy();
selected = -1;
return;
//ok = false;
} catch (ClassCastException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Throwable e) {
System.out.println("Unable to find devices to search" + e.getMessage());
}
}
}
return;
}
if (selected == -2) {
break;
}
if (selected <= iterator && selected >= 0) {
BTClient.record = this.recordTab[selected];
//System.out.println(record + " " + recordTab[selected]);
try {
while (record == null) {
}
url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, master);
conn = (StreamConnection) Connector.open(url);
op = conn.openDataOutputStream();
//System.out.println("???? " + " " + hello);
//BTTaskManager.auto=true;
BTInit.taskMan.sendInit(3, localDevice.getBluetoothAddress());
BTInit.taskMan.answer();
//hello.taskManager.sendInit(1, localDevice.getBluetoothAddress());
//BTTaskManager.auto=true;
//ok = false;
} catch (ClassCastException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Throwable e) {
System.out.println("Unable to find devices to search" + e.getMessage());
}
/*{ else if (selected == -2) {
selected = -1;
BTClient.record=null;
System.out.println("abord");
break;*/
} else {
selected = -1;
}
/* if (iterator == 0) {
return;
}*/
if (System.currentTimeMillis() - tmpTimeSendSignal > timeSendSingnalOnline && selected == -1) {
selected = -2;
System.gc();
}
}
System.out.println("record " + record);
destroy();
agent.cancelInquiry(this);
selected = -1;
}