BitcoinJ wallet shows wrong balance - java

I'm getting familiar with BitcoinJ. So now there is a function for user that registers for the first time and there should be created address for him. But it doesn't work. It says there is already some money.
// USER HAS NEVER USED COIN_ATLAS ( IT IS THE FIRST TIME )
public void addUser()
{
DBObject dbUser;
WalletAppKit kit = new WalletAppKit(TestNet3Params.get(), new File("."), "forwarding-service-testnet");
params = TestNet3Params.get();
Debug.Log("Wait a bit...");
kit.startAsync();
kit.awaitRunning();
BlockChain chain = null;
my_wallet = kit.wallet(); // Wallet created for that user
try {
chain = new BlockChain(params, my_wallet,
new MemoryBlockStore(params));
} catch (BlockStoreException e) {
e.printStackTrace();
}
PeerGroup peerGroup = new PeerGroup(params, chain);
peerGroup.addPeerDiscovery(new DnsDiscovery(params));
peerGroup.addWallet(my_wallet);
peerGroup.startAsync();
Debug.Log("WALLET: " + my_wallet.currentReceiveAddress());
Debug.Log("WALLET BALANCE: " + my_wallet.getBalance().toFriendlyString());
my_wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
#Override
public void onCoinsReceived(Wallet wallet, Transaction transaction, Coin coin, Coin coin1) {
send("NEW TRANSACTION:");
sendWithMarkdown("FROM: " + wallet.currentReceiveAddress() + " : " + bold(coin1.toFriendlyString()));
Coin value = transaction.getValueSentToMe(wallet);
System.out.println("Received tx for " + value.toFriendlyString() + ": " + transaction);
Futures.addCallback(transaction.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
#Override
public void onSuccess(#Nullable TransactionConfidence transactionConfidence) {
send(bold("Transaction confirmed!"));
send(bold(value.toFriendlyString() + " is deposited!"));
}
#Override
public void onFailure(Throwable throwable) {
}
});
}
});
peerGroup.downloadBlockChain();
peerGroup.stopAsync();
dbUser = new BasicDBObject("_id", bot_user.getId())
.append("firstName", bot_user.getFirstName())
.append("password", bot_user.getPassword())
.append("address", my_wallet.currentReceiveAddress().toString())
.append("BTC", (double)my_wallet.getBalance().getValue());
collection.insert(dbUser);
}
There is what I get in output:
WALLET: mtrjbnpq5wDzoywrKqod63tpB7ZUFrr7q5
WALLET BALANCE: 1.21503904 BTC
But if I check this address in blockchain, it shows 0.
So how to create wallet the right way?

Related

Interactive Brokers API - Executing multiple trades

I'm trying to create a program for an API to place multiple trades at once, and then get prices for the stocks, and then rebalance every so often. I used a tutorial from online to get some of this code, and made a few tweaks.
However, when I run the code, it often connects and will place an order if I restart IB TWS. But if I go to run the code again it does not work, or show any indication that it will connect. Can anyone help me figure out how to keep the connection going, so that I can run the main.java file, and it will execute multiple trades and then end the connection? Do I need to change the client id number in either the code, or the settings of TWS?
There are three files:
Ordermanagement.java:
package SendMarketOrder;
//import statements//
class OrderManagement extends Thread implements EWrapper{
private EClientSocket client = null; //IB API client Socket Object
private Stock stock = new Stock();
private Order order = new Order();
private int orderId;
private double limitprice;
private String Ticker;
//method to create connection class. It's the constructor
public OrderManagement() throws InterruptedException, ClassNotFoundException, SQLException {
// Create a new EClientSocket object
System.out.println("////////////// Creating a Connection ////////////");
client = new EClientSocket(this); //Creation of a socket to connect
//connect to the TWS Demo
client.eConnect(null,7497,1);
try {
Thread.sleep(3000); //waits 3 seconds for user to accept
while (!(client.isConnected()));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("///////// Connected /////////");
}
public void sendMarketOrder(String cusip, String buyorSell, int shares) throws SQLException, ClassNotFoundException{
//New Order ID
orderId++;
order.m_action = buyorSell;
order.m_orderId = orderId;
order.m_orderType = "MKT";
order.m_totalQuantity = shares;
order.m_account = "DU33xxxxx"; //write own account
order.m_clientId = 1;
//Create a new contract
stock.createContract(cusip);
client.placeOrder(orderId, stock.contract, order);
//Show order in console
SimpleDateFormat time_formatter = new SimpleDateFormat("HH:mm:ss");
String current_time_str = time_formatter.format(System.currentTimeMillis());
System.out.println("////////////////////////////////////////////////\n" +
"#Limit Price: " + order.m_lmtPrice + "///////////////////////////\n" +
"#Client number: " + order.m_clientId + "///////////////////////////\n" +
"#OrderType: " + order.m_orderType + "///////////////////////////\n" +
"#Order Quantity: " + order.m_totalQuantity + "///////////////////////////\n" +
"#Account number: " + order.m_account + "///////////////////////////\n" +
"#Symbol: " + stock.contract.m_secId + "///////////////////////////\n" +
"///////////////////////////////////////"
);
}
Stock.java
public class Stock{
private int StockId; //we can identify the stock
private String Symbol; //Ticker
public Stock() { //default constructor
}
public Stock(int StockId, String Symbol) { //constructor
this.StockId = StockId;
this.Symbol = Symbol;
}
//getter and setters
public int getStockId() {
return StockId;
}
public String getSymbol() {
return Symbol;
}
Contract contract = new Contract ();
public void createContract(String cusip){
contract.m_secId = cusip;
contract.m_secIdType = "CUSIP";
contract.m_exchange = "SMART";
contract.m_secType = "STK";
contract.m_currency = "USD";
}
}
Main.java:
package SendMarketOrder;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws InterruptedException, ClassNotFoundException, SQLException {
OrderManagement order = new OrderManagement();
order.sendMarketOrder("922908363","BUY", 100);
order.sendMarketOrder("92204A504","BUY", 50);
order.sendMarketOrder("92204A702","BUY", 100);
System.exit(0);
}
}
These are my current settings TWS settings if that helps:
Thanks in advance for the help!
I changed a few things around in the code and added comments.
package sendmarketorder;//usually lower case pkg names
public class Main {
//you throw a bunch of exceptions that are never encountered
public static void main(String[] args) {
//since there's a Thread.sleep in this class
//it will block until ready
OrderManagement order = new OrderManagement();
//obviously you need some logic to buy/sell
//you can use command line args here if you want
order.sendMarketOrder("922908363", "BUY", 100);
order.sendMarketOrder("92204A504", "BUY", 50);
order.sendMarketOrder("92204A702", "BUY", 100);
//the socket creates a reader thread so this will stop it.
//if you didn't have this line the non-daemon thread would keep a
//connection to TWS and that's why you couldn't reconnect
//System.exit(0);//use better exit logic
}
}
.
package sendmarketorder;
import com.ib.client.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
//doesn't extend thread and if you implement EWrapper you have to implement all methods
//in API 9.72 you can extend DefaultWrapper and just override the methods you need
public class OrderManagement implements EWrapper{
private EClientSocket client = null; //IB API client Socket Object
private int orderId = -1;//use as flag to send orders
//private double limitprice;
//private String Ticker;
//keep track of all working orders
private Map<Integer, Order> workingOrders = new HashMap<>();
//method to create connection class. It's the constructor
public OrderManagement(){
// Create a new EClientSocket object
System.out.println("////////////// Creating a Connection ////////////");
client = new EClientSocket(this); //Creation of a socket to connect
//connect to the TWS Demo
client.eConnect(null, 7497, 123);//starts reader thread
try {
while (orderId < 0){ //not best practice but it works
System.out.println("waiting for orderId");
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("///////// Connected /////////");
}
public void sendMarketOrder(String cusip, String buyorSell, int shares) {
//make new stock and order for each stock
Stock stock = new Stock();
Order order = new Order();
//New Order ID, but get from API as you have to increment on every run for life
orderId++;
order.m_action = buyorSell;
order.m_orderId = orderId;
order.m_orderType = "MKT";
order.m_totalQuantity = shares;
//I don't think you're supposed to use these fields
//order.m_account = "DU33xxxxx"; //write own account
//order.m_clientId = 1;
//Create a new contract
stock.createContract(cusip);
//remember which orders are working
workingOrders.put(orderId, order);
client.placeOrder(orderId, stock.contract, order);
//Show order in console
SimpleDateFormat time_formatter = new SimpleDateFormat("HH:mm:ss");
String current_time_str = time_formatter.format(System.currentTimeMillis());
System.out.println("////////////////////////////////////////////////\n"
+ "#Limit Price: " + order.m_lmtPrice + "///////////////////////////\n"
+ "#Client number: " + order.m_clientId + "///////////////////////////\n"
+ "#OrderType: " + order.m_orderType + "///////////////////////////\n"
+ "#Order Quantity: " + order.m_totalQuantity + "///////////////////////////\n"
+ "#Account number: " + order.m_account + "///////////////////////////\n"
+ "#Symbol: " + stock.contract.m_secId + "///////////////////////////\n"
+ "///////////////////////////////////////"
);
}
//always impl the error callback so you know what's happening
#Override
public void error(int id, int errorCode, String errorMsg) {
System.out.println(id + " " + errorCode + " " + errorMsg);
}
#Override
public void nextValidId(int orderId) {
System.out.println("next order id "+orderId);
this.orderId = orderId;
}
#Override
public void orderStatus(int orderId, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, String whyHeld) {
//so you know it's been filled
System.out.println(EWrapperMsgGenerator.orderStatus(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld));
//completely filled when remaining == 0, or possible to cancel order from TWS
if (remaining == 0 || status.equals("Cancelled")){
//remove from map, should always be there
if (workingOrders.remove(orderId) == null) System.out.println("not my order!");
}
//if map is empty then exit program as all orders have been filled
if (workingOrders.isEmpty()){
System.out.println("all done");
client.eDisconnect();//will stop reader thread
//now is when you stop the program, but since all
//non-daemon threads have finished, the jvm will close.
//System.exit(0);
}
}
//impl rest of interface...
}

QuickBooks NULL CallbackHandler

I'm trying to perform a batch operation in QuickBook but getting null callbackhandler.
private static void AddBulkCustomer(DataService ds) throws FMSException{
BatchOperation bo = new BatchOperation();
Customer c1 = new Customer();
c1.setGivenName("Customer 3");
c1.setDisplayName("Disp Customer 3");
EmailAddress email = new EmailAddress();
email.setAddress("customer1#zzz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b3");
c1= null;
c1 = new Customer();
c1.setGivenName("Customer 4");
c1.setDisplayName("Disp Customer 4");
email = null;
email = new EmailAddress();
email.setAddress("customer2#z2zz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b4");
// String strQuery = " select * from customer where givenname ='"+c1.getGivenName()+"'";
// bo.addQuery(strQuery, "b3Query");
ds.executeBatchAsync(bo, new AsyncCallBackBatch());
}
For AsyncCallback operation
public class AsyncCallBackBatch implements CallbackHandler {
#Override
public void execute(CallbackMessage callbackMsg) {
System.out.println("asyncCallbackBatch is executing... ");
try {
System.out.println("QR = "+callbackMsg.getFMSException().toString());
BatchOperation BO = callbackMsg.getBatchOperation();
if (BO != null) {
List<String> bId = BO.getBIds();
for (String strBId : bId) {
if (BO.isFault(strBId)) {
Fault fault = BO.getFault(strBId);
System.out.println("asyncCallBackBatch Error Code : "+ fault.getError().get(0).getCode() + " "+ "Error : "
+ fault.getError().get(0).getDetail()+ ", Message : "+ fault.getError().get(0).getMessage());
} else if (BO.isEntity(strBId)) {
System.out.println("Batch having entity message.. ");
Customer cust = (Customer) BO.getEntity(strBId);
System.out.println("cust id : " + cust.getId()+ " CustName = " + cust.getGivenName());
} else if (BO.isQuery(strBId)) {
System.out.println("Batch having Query ... Parsing... ");
QueryResult qR = BO.getQueryResponse(strBId);
System.out.println("Query : " + qR.getTotalCount());
} else if (BO.isReport(strBId)) {
System.out.println("Batch having Report... ");
Report report = BO.getReport(strBId);
System.out.println(" " + report.getClass().getName());
} else {
System.out.println("Something went wrong... ");
}
}
}else{
System.out.println("Batch Operation terminated, reason: NULL callbackMsg ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
OAuthAuthorizer oAuth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken, accessTokenSecret);
//403352746
try {
Context context = new Context(oAuth, ServiceType.QBO, "403352746");
System.out.println("RealmID : "+context.getRealmID());
context.setCustomerRequestTimeout(99999);
System.out.println("TimeOut Set to = "+context.getCustomerRequestTimeout());
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
DataService ds = new DataService(context);
AddBulkCustomer(ds);
System.out.println("Operation Complete..");
} catch (Exception e) {
e.printStackTrace();
}
}
When I debug, in execute method, I'm getting Null BatchOperation in return. I'm not sure performing Batch operation is allowed in sandbox environment.
I found the solution after so much of testing and communication with Quickbooks Devs thought would be helpful for others.
In sandbox environment even if you set the config properties to sandbox URL it still picks as PROD URL in Callbackhandler.
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
In this case they called this as a bug, currently all you can do is to make a trial account in PROD and then test this.

Queues and Stacks Hiring and Firing

I finished this program and demo for my TA. I completely forgot one thing. So, the program is about hiring and firing people using stack and queues. I figured everything out except for one thing. I have to hire at least 3 people and whoever the first applicant is, I will hire them first so on. Here's the problem:
When I fire someone (The last person hired), that person should be the next person to get hired. Example:
Fired Name: b SS: 2
next person hired should be
Hired Name: b SS: 2.
I can't figure out how to get the last person fired to be the next person hired. Here's my program:
class Person {
public String name;
public String SS;
public Person(String N, String S) {
this.name = N;
this.SS = S;
}
}
class Manager {
Scanner keyboard = new Scanner(System.in);
private Queue<Person> app = new Queue<Person>();
public Stack<Person> hire = new Stack<Person>();
public Stack<Person> fire = new Stack<Person>();
public void Apply() throws QueueException {
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
app.enqueue(apply);
}
public void hire() throws QueueException {
if (!app.isEmpty()) {
Person newHire = hire.push(app.dequeue());
System.out.println("Hired \nName: " + newHire.name + " SS: " + newHire.SS);
//hire.push(app.dequeue());
} else if (!fire.isEmpty()) {
Person newFire = app.dequeue();
System.out.println("Hired \nName: " + newFire.name + " SS: " + newFire.SS);
} else {
System.out.println("Nobody to hire.");
}
}
public void fire() throws StackException {
if (!hire.isEmpty()) {
Person newFire = fire.push(hire.pop());
System.out.println("Fired \nName: " + newFire.name + " SS: " + newFire.SS);
fire.push(hire.pop());
} else {
System.out.println("Nobody to fire");
}
}
}
public class Management {
public static void main(String[] args) throws QueueException, StackException {
Scanner keyboard = new Scanner(System.in);
Manager user = new Manager();
boolean test = true;
while (test) {
System.out.print("Press \n\t1 ACCEPT APPLICANT");
System.out.print("\n\t2 Hire \n\t3 Fire \n\t4 Quit:");
System.out.print("\nAnswer: \n");
int action = keyboard.nextInt();
String space = keyboard.nextLine();
if (action == 1) {
user.Apply();
} else if (action == 2) {
user.hire();
} else if (action == 3) {
user.fire();
} else if (action == 4) {
System.exit(0);
} else {
System.out.println("Please try again.");
}
}
you have this error on the hire() method.
Person newFire = app.dequeue();
you see that you are executing this line even tho app queue is Empty. just use fire stack instead of app queue.
public void hire() throws QueueException {
if (!app.isEmpty()) {
Person newHire = hire.push(app.dequeue());
System.out.println("Hired \nName: " + newHire.name + " SS: " + newHire.SS);
//hire.push(app.dequeue());
} else if (!fire.isEmpty()) {
Person newFire = fire.pop();
hire.push(newFire);
System.out.println("Hired \nName: " + newFire.name + " SS: " + newFire.SS);
} else {
System.out.println("Nobody to hire.");
}
}

asynccallback failures

In my app I need to add string vallues to the file(.property file, if it is important). and user enter this values in gwt GUI. Here is it's important part:
final Button submit = new Button("Submit");
addButton(submit);
submit.addSelectionListener(new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
keyWord.selectAll();
regexp.selectAll();
if (keyWord.getValue() != null){
setKeyWord(customerId, keyWord.getValue());
keyWord.setValue("");
}
if (regexp.getValue() != null){
setRegExp(customerId, regexp.getValue());
regexp.setValue("");
}
}
});
}
private void setKeyWord(final String customerId, final String keyword){
final AsyncCallback<String> callbackItems = new AsyncCallback<String>() {
public void onFailure(final Throwable caught) {
Window.alert("unable to add " + caught.toString());
}
public void onSuccess(final String x) {
Window.alert(x);
}
};
serverManagementSvc.setKeyWords(customerId, keyword, callbackItems);
}
private void setRegExp(final String customerId, final String regexp){
final AsyncCallback<String> calbackItems = new AsyncCallback<String>() {
#Override
public void onFailure(Throwable throwable) {
Window.alert("unable to add " + throwable.toString());
}
#Override
public void onSuccess(String s) {
Window.alert(s);
}
};
serverManagementSvc.setRegExp(customerId, regexp, calbackItems);
}
So I need to use Asunccallback to call methods which are in the "server part".
here are these methods:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords" + "," + word));
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps" + "," + regexp));
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
all interfaces are present.
when I run my code And press "submit" button in gui I see that both asynccallback failured(Window.alert, as you can see, shows "null pointer exception" despite of the fact that values which I send to methods are not null). why can it be? can you suggest me something?
UPD here is error which is shown by firebug:
uncaught exception: java.lang.ClassCastException
function W8(){try{null.a()}catch(a){return a}}
the problem is solved: there were a simple mistake in the code. I've closed brackets at the wrong place:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords") + "," + word);
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps") + "," + regexp);
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
I recommend that you recompile the GWT code using
-style PRETTY
and then check that firebug output again; it may give you a better clue, compared to your updated uncaught exception.
Next, I suggest you run it in the eclipse debugger, and set breakpoints in both the client and server code, and then you can inspect the variables and step through the code.

Bluecove: SERVICE_SEARCH_DEVICE_NOT_REACHABLE issue

I try to connect to a custom Bluetooth device using BlueCove. I can pair the device, but when I try to search for services I always get SERVICE_SEARCH_DEVICE_NOT_REACHABLE in serviceSearchCompleted() and no services are discovered. If I try the same thing outside Java (in Windows), the PC bluetooth device discovers and can connect (using COM21, COM22, ...) to the SPP service on my device.
What am I doing wrong?
I also tried to do the service search after the device discovery is ended. Same issue.
Please find below my code.
Many thanks in advance for any idea on how to solve this,
Adrian.
public class Test {
private static Logger LOG = Logger.getLogger(Test.class.getName());
private static final String NAME = "XXXX";
private static final String PIN = "1234";
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003), new UUID(0x1101)};
private LocalDevice localDevice;
private DiscoveryAgent discoveryAgent;
private DiscoveryListener discoveryListener = new GDiscoveryListener();
private Map<Integer, RemoteDevice> searchForServices = new HashMap<Integer, RemoteDevice>();
private Collection<ServiceRecord> servicesDiscovered = new HashSet<ServiceRecord>();
private Object lock = new Object();
private CountDownLatch waitForDevices;
protected void connect() {
try {
localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
LOG.info("Local Device: " + localDevice.getFriendlyName()
+ "(" + localDevice.getBluetoothAddress() + ")");
discoveryAgent = localDevice.getDiscoveryAgent();
LOG.finest("Start discovering devices");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, discoveryListener);
try {
synchronized(lock) {
lock.wait();
}
if (searchForServices.size() > 0) {
waitForDevices = new CountDownLatch(searchForServices.size());
waitForDevices.await();
}
}
catch (InterruptedException e) {
LOG.log(Level.WARNING, "Error waiting to terminate discovery", e);
}
LOG.finest(servicesDiscovered.size() + " services discovered");
LOG.finest("Device discovery completed");
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Error initializing Bluetooth", e);
}
}
private class GDiscoveryListener implements DiscoveryListener {
public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
try {
String name = rd.getFriendlyName(false);
boolean isMine = NAME.equals(name);
LOG.info("Discovered: " + name + "(" + rd.getBluetoothAddress() + ")"
+ (isMine ? "" : " - ignoring"));
if (!isMine)
return;
if (!rd.isAuthenticated()) {
LOG.finest("Try to pair with " + name
+ " PIN: " + PIN);
boolean paired = RemoteDeviceHelper.authenticate(rd, PIN);
LOG.info("Pair with " + name + (paired ? " succesfull" : " failed"));
}
int transID = discoveryAgent.searchServices(null, UUIDS, rd, discoveryListener);
searchForServices.put(transID, rd);
LOG.finest("Searching for services for " + name + " with transaction " + transID);
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), e);
} catch (IOException e) {
LOG.log(Level.WARNING, "Error connecting ", e);
} catch (Throwable t) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), t);
}
}
public void inquiryCompleted(int respCode) {
synchronized(lock) {
lock.notify();
}
switch (respCode) {
case DiscoveryListener.INQUIRY_COMPLETED :
LOG.fine("INQUIRY_COMPLETED");
break;
case DiscoveryListener.INQUIRY_TERMINATED :
LOG.fine("INQUIRY_TERMINATED");
break;
case DiscoveryListener.INQUIRY_ERROR :
LOG.fine("INQUIRY_ERROR");
break;
default :
LOG.fine("Unknown Response Code - " + respCode);
break;
}
}
public void serviceSearchCompleted(int transID, int respCode) {
String rd = searchForServices.get(transID).getBluetoothAddress();
//searchForServices.remove(transID);
switch (respCode) {
case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
LOG.fine(rd + ": The service search completed normally");
break;
case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
LOG.fine(rd + ": The service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch(int)");
break;
case DiscoveryListener.SERVICE_SEARCH_ERROR:
LOG.warning(rd + ": An error occurred while processing the request");
break;
case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
LOG.info(rd + ": No records were found during the service search");
break;
case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
LOG.warning(rd + ": The device specified in the search request could not be reached or the local device could not establish a connection to the remote device");
break;
default:
LOG.warning(rd + ": Unknown Response Code - " + respCode);
break;
}
if (waitForDevices != null)
waitForDevices.countDown();
}
public void servicesDiscovered(int transID, ServiceRecord[] srs) {
LOG.info("Services discovered in transaction " + transID + " : " + srs.length);
for (ServiceRecord sr : srs) {
LOG.info(sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false));
servicesDiscovered.add(sr);
}
}
}
public static void main(String[] args) {
new Test().connect();
}
}
I had the same problem while connecting to a Bluetooth earpiece. Like you I was also searching for more than one service at a time and It always returned SERVICE_SEARCH_DEVICE_NOT_REACHABLE. So, I tried searching for only one service and it worked. So, try modifying your code as:
...
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003)}

Categories

Resources