我正在尝试使用SECTOR_SELECT对指定扇区进行读写,但在通过TagLostException
发送命令的第二部分时获得MifareUltralight.transceive()
。我如何选择和操纵扇区?
我正在使用Android Nexus 6(6.0.1)向NXP NTAG(NT3H1201)发送命令并从中获取数据。我可以使用GET_VERSION命令(60h)进行收发(通过NfcA
和MifareUltralight
)。
我用来选择某个扇区的方法:
public void selectSector(byte sector, MifareUltralight mifareUltralight) throws IOException {
if (mifareUltralight.isConnected()) {
mifareUltralight.close();
}
// SECTOR_SELECT command (see nxp p. 46)
byte[] sectorSelectCmdPacket1 = new byte[2];
byte[] sectorSelectCmdPacket2 = new byte[4];
sectorSelectCmdPacket1[0] = (byte) 0xc2; // Sector select command
sectorSelectCmdPacket1[1] = (byte) 0xff;
sectorSelectCmdPacket2[0] = sector; // Memory sector to be selected; 1 for I2C 2k version
sectorSelectCmdPacket2[1] = (byte) 0x00;
sectorSelectCmdPacket2[2] = (byte) 0x00;
sectorSelectCmdPacket2[3] = (byte) 0x00;
mifareUltralight.connect();
try {
// ACK = 0A
byte[] sectorSelectResp1 = mifareUltralight.transceive(sectorSelectCmdPacket1);
Log.w(TAG, bytesToHex(sectorSelectResp1));
} catch (IOException e) {
Log.w(TAG, "selectSector: there was an exception while sending first sector select command");
e.printStackTrace();
}
try {
mifareUltralight.transceive(sectorSelectCmdPacket2);
Log.w(TAG, "Second sector select command sent");
} catch (IOException e) {
Log.w(TAG, "selectSector: there was an exception while sending second sector select command");
e.printStackTrace();
}
mifareUltralight.close();
}
当我调用selectSector方法时,第一个收发完成但第二个收不到,导致错误
android.nfc.TagLostException:标签丢失了。
如何在不获取TagLostException
的情况下选择和操作扇区?
答案 0 :(得分:0)
SECTOR_SELECT命令的第二阶段导致TagLostException
是正常的。这在许多Android设备上发生,并且是由SECTOR_SELECT命令的第二阶段确认的方式(被动ACK)引起的。收到该特定命令的例外后,您可以安全地继续与标记通信。只有当您收到TagLostException
的命令时,如果您希望有明确的ACK /响应数据,那么通信就会出现问题。
另请注意,选择扇区后不应关闭连接,因为这会重置某些Android设备上的标记。因此,以后重新连接标记时可能不再选择该扇区。
典型的扇区选择方法如下所示:
public boolean selectSector(int sector) throws IOException {
byte[] cmd_sel1 = { (byte)0xC2, (byte)0xFF };
byte[] cmd_sel2 = { (byte)sector, (byte)0x00, (byte)0x00, (byte)0x00 };
byte[] result1 = transceive(cmd_sel1);
if (result1 == null) {
throw new TagLostException();
} else if ((result1.length == 1) && ((result1[0] & 0x00A) == 0x000)) {
// NACK response according to DigitalProtocol
return false;
} else {
try {
byte[] result2 = transceive(cmd_sel2);
if (result2 == null) {
throw new TagLostException();
} else if ((result2.length == 1) && ((result2[0] & 0x00A) == 0x000)) {
// NACK response according to DigitalProtocol
return false;
} else {
return true;
}
} catch (Exception e) {
// passive ACK
return true;
}
}
}