NFC-V "Tag Lost" Xamarin 和 ST M24LR 标签异常

NFC-V "Tag Lost" exception with Xamarin and ST M24LR tag

我是 Xamarin 的新手,也是 Android 开发的新手。我有一个 NFC 标签,特别是 ST M24LR64E,上面有数据。我可以在 Google Play 上使用 ST 应用程序查看数据块。在我的 Xamarin 应用程序中,我无法在未收到 TagLostException 的情况下向标签发送消息。我可以毫无问题地查询标签 ID,但尝试读取单个数据块时,出现异常。任何方向将不胜感激。

byte[] response = new byte[] { 0x0A };

byte[] cmd = new byte[]
{
    (byte) 0x26,
    (byte) 0x01,
    0x00
};
response = nfcv.Transceive(cmd);

byte[] single = new byte[]
{
    (byte) 0x40, // FLAGS
    (byte) 0x20, // READ_SINGLE_BLOCK
    0, 0, 0, 0, 0, 0, 0, 0,
    (byte) (0 & 0x0ff)
};
Array.Copy(id, 0, single, 2, 8);
response = nfcv.Transceive(single);

第一个 Transceive() 没问题,我看到返回了 10 个字节。我一尝试读取数据块,就收到 TagLostException。

使用 NfcV 标签技术,TagLostException 可能表示 reader 无法再与标签通信或命令导致错误。

根据其manual,M24LR64E只支持READ_SINGLE_BLOCK命令的扩展版本(Protocol Extension flag set):

The Protocol_extension_flag should be set to 1 for the M24LR64E-R to operate correctly. If the Protocol_extension_flag is at 0, the M24LR64E-R answers with an error code.

因此,您的 READ_SINGLE_BLOCK 命令版本与标签不兼容。您需要设置协议扩展标志并提供一个 16 位的块号。应该工作的版本是:

int blockNumber = 0;
byte[] readSingleBlock = new byte[] {
        (byte) 0x28, // Flags: Addressed (bit 5), Protocol Extension (bit 3)
        (byte) 0x20, // Command: READ_SINGLE_BLOCK
        0, 0, 0, 0, 0, 0, 0, 0,  // placeholder for UID
        (byte) (blockNumber & 0x0ff),
        (byte) ((blockNumber >> 8) & 0x0ff)
};
byte[] id = nfcv.GetTag().GetId();
Array.Copy(id, 0, readSingleBlock, 2, 8);
response = nfcv.Transceive(readSingleBlock);

由于您在 INVENTORY 命令中使用了高数据速率(Data_rate 标志设置),您可能还想在 READ_SINGLE_BLOCK 命令中使用高数据速率。在这种情况下,您将使用标志值 0x2A(而不是 0x28)。

最后,您应该避免向任何 NfcX 标签技术对象发送 anti-collision/enumeration 命令,例如 INVENTORY 命令。虽然这可能有效,但您可能会混淆 ANdroid NFC 堆栈的内部状态保持,因为它已经为您执行了这些命令并跟踪枚举标签。您可以获得通过 Tag 对象和 NfcV 对象的 INVENTORY 请求获得的所有信息:

  • tag.GetId() 为您提供标签的 UID。
  • nfcv.GetDsfId() 为您提供标签的 DSFID。
  • nfcv.GetResponseFlags() 为您提供 INVENTORY 响应的标志字节。