在出示NFC卡时触发事件

Han*_*ank 5 javascript nfc chromebook google-chrome-app acr122

我正在尝试在Chromebook上构建一个webapp,我需要它来使用ACR122U NFC读取RFID卡序列号.我正在使用chrome-nfc.

我正在愉快地读卡片,但我不知道如何在出示卡片时发射事件.

我是否可以使用chrome-nfc中的任何事件来了解卡片何时被呈现给读者?

编辑:我一直在尝试使用chrome.nfc.wait_for_tag,但它的行为并不像我期望的那样.

// With a card on the reader
chrome.nfc.wait_for_tag(device, 10000, function(tag_type, tag_id){
  var CSN = new Uint32Array(tag_id)[0];
  console.log ( "CSN: " + CSN );
});

[DEBUG] acr122_set_timeout(round up to 1275 secs)
DEBUG: InListPassiveTarget SENS_REQ(ATQA)=0x4, SEL_RES(SAK)=0x8
DEBUG: tag_id: B6CA9B6B
DEBUG: found Mifare Classic 1K (106k type A)
[DEBUG] nfc.wait_for_passive_target: mifare_classic with ID: B6CA9B6B
CSN: 1805372086



// with no card on the reader
chrome.nfc.wait_for_tag(device, 10000, function(tag_type, tag_id){
  var CSN = new Uint32Array(tag_id)[0];
  console.log ( "CSN: " + CSN );
});

[DEBUG] acr122_set_timeout(round up to 1275 secs)
DEBUG: found 0 target, tg=144
Run Code Online (Sandbox Code Playgroud)

两者都立即返回上面的结果,似乎没关系我用于超时的数字...

如果我在阅读器上调用没有卡的功能,然后在功能调用后立即将卡放在阅读器上,我在控制台中没有输出.

Gri*_*inn 2

我不熟悉 chrome-nfc,但是通过对源进行逆向工程在黑暗中进行拍摄,看起来您会想要使用该wait_for_tag方法,例如:

chrome.nfc.wait_for_tag(device, 3000, function(tag_type, tag_id) {
    // Do your magic here.
});
Run Code Online (Sandbox Code Playgroud)

...device您的读者在哪里,3000是等待的最长时间(以毫秒为单位),并替换// Do your magic here.为您想要的逻辑。如果超时,则tag_type和都tag_id将为null

如果你想无限期地等待,你可以使用上面的代码递归调用一个函数。例子:

function waitAllDay(device) {
    chrome.nfc.wait_for_tag(device, 1000, function(tag_type, tag_id) {
        if(tag_type !== null && tag_id !== null)
        {
            // Do your magic here.
        }
        waitAllDay(device);
    });
}
Run Code Online (Sandbox Code Playgroud)

这是假设您希望它继续等待,即使在出现标签后也是如此。如果您希望它在读取标签后停止,请将 包裹起来waitAllDay(device);else

更新:看来该wait_for_tag方法没有按预期工作,所以我提出了第二种解决方案。我将保留现有的解决方案,以防 chrome-nfc 的开发人员修复该方法。

另一件要尝试的事情是使用chrome.nfc.read,在 内传递一个timeout选项window.setInterval

var timer = window.setInterval(function () {
        chrome.nfc.read(device, { timeout: 1000 }, function(type, ndef) {
            if(!!type && !!ndef) {
                // Do your magic here.
                // Uncomment the next line if you want it to stop once found.
                // window.clearInterval(timer);
            }
        });
    }, 1000);
Run Code Online (Sandbox Code Playgroud)

请务必window.clearInterval(timer)在您希望它停止监视标签时拨打电话。