1

I ve been using a wired Smart Card Reader SDK where the calls where synchronous. Lately been trying on the Bluetooth Interface but the APDU Command is asynchronous due to which we are not able to interpret the response of the calls sent for forming the next APDU Command.

Any help will be much appreciated.

Request

byte[] var1 = {(byte)0, (byte)-92, (byte)4, (byte)0, (byte)12, (byte)-96, (byte)0, (byte)0, (byte)2, (byte)67, (byte)0, (byte)19, (byte)0, (byte)0, (byte)0, (byte)1, (byte)1};

        String apduString = QPOSUtil.byteArray2Hex(var1);
        pos.sendApdu(apduString);

Result:

@Override public void onReturnApduResult(boolean arg0, String arg1, int arg2) { }

Munavar
  • 11
  • 1
  • Possible duplicate of [Wrapping an asynchronous computation into a synchronous (blocking) computation](https://stackoverflow.com/questions/2180419/wrapping-an-asynchronous-computation-into-a-synchronous-blocking-computation) – Michael Roland Jun 13 '17 at 17:14

1 Answers1

0

You can capsule you asynchronous call to a synchronous one. The main idea is to block the current thread while you are waiting for a result. I like to work with locks so I used java.util.concurrent.locks.ReentrantLock. But there are many ways to implement this behavior like java.util.concurrent.Future<T> or Busy Waiting.

// Lock that is used for waiting
private final ReentrantLock waitLock = new ReentrantLock();

private APDUResult result = null;

// synchronous wrapper 
// synchronized keyword is used to serialize requests
public synchronized APDUResult sendAPDUSynchronous(byte[] apdu) {
    // calles asynchronous function
    sendAPDUAsynchronous(apdu);
    // waits until .unlock() is called
    waitLock.lock();
    // returns the result
    return result;
}

// this function sould not be called outside - so its private
private void sendAPDUAsynchronous(byte[] apdu) {
    String apduString = QPOSUtil.byteArray2Hex(var1);
    pos.sendApdu(apduString);
}

@Override
public void onReturnApduResult(boolean arg0, String arg1, int arg2) {
    // stores the result
    result = new APDUResult(arg0, arg1, arg2);
    // notifys the waiting thread in synchronous call
    waitLock.unlock();
}

APDUResult just wraps the three parameters to one object that can passted as by the synchronous function. Dont forget to call waitLock.unlock() on error-callbacks, too. Otherwise there will be a deadlock.

There are other posts on this topic too should you need more inspiration.

Myon
  • 937
  • 13
  • 23