NFC HCE - Reader two way communincation android

92 Views Asked by At

We can send data from HCE device to NFC reader device . But How to send same data or other data from NFC Reader to that HCE device? Is there any other way to do build this solution around NFC?

HostApduService:

  override fun processCommandApdu(commandApdu: ByteArray, extras: Bundle?): ByteArray {
        if (Arrays.equals(SELECT_APPLICATION, commandApdu)) {
            mAppSelected = true
            mCcSelected = false
            mNdefSelected = false
            return SUCCESS_SW
        } else if (mAppSelected && Arrays.equals(SELECT_CAPABILITY_CONTAINER, commandApdu)) {
            mCcSelected = true
            mNdefSelected = false
            return SUCCESS_SW
        } else if (mAppSelected && Arrays.equals(SELECT_NDEF_FILE, commandApdu)) {
            // NDEF
            mCcSelected = false
            mNdefSelected = true
            return SUCCESS_SW
        } else if (commandApdu[0] == 0x00.toByte() && commandApdu[1] == 0xb0.toByte()) {
            // READ_BINARY
            // get the offset an le (length) data
            //System.out.println("** " + Utils.bytesToHex(commandApdu) + " in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {");
                    return responseApdu
                }
            }
        }
        return FAILURE_SW
    }

Reader

@Override
    public void onTagDiscovered(Tag tag) {
        System.out.println("NFC tag discovered");
        this.runOnUiThread(() -> {
            readResult.setText("");
        });

        Ndef mNdef = Ndef.get(tag);
        if (mNdef != null) {
           //read tag
        } else {
            this.runOnUiThread(() -> {
                readResult.setText("There was an error in NDEF data");
            });
        }
        if (mNdef!= null) {
            NdefRecord mRecord = NdefRecord.createTextRecord("en","kamal");
            NdefMessage mMsg = new NdefMessage(mRecord);
            try {
                mNdef.connect();
                mNdef.writeNdefMessage(mMsg);
            } catch(Exception e){}
        }
1

There are 1 best solutions below

4
Andrew On

So logically sending data from HCE to reader is the reader "reading" the emulated Tag, to send data in the opposite direction the reader has to "write" to the emulated Tag.

So the HCE device needs to process suitable reading and writing ADPU's

Update

As shown in your updated code your HostApduService responds to CLA = 00h and INS = B0h for a read operation and returns the correct ADPU containing the Ndef Data.

As seen in the Type 4 NFC Spec section 5.4.7 NDEF Update Procedure (Write) your HostApduService also needs to respond to CLA = 00h and INS = D6h and then extract the NDef data from the ADPU and then store it somewhere.