使用Java中的smartcardio在Raspberry Pi上安装多个NFC ACR122U设备

时间:2013-11-27 14:09:35

标签: java linux multithreading raspberry-pi smartcard-reader

我有3个连接到Raspberry Pi的ACR122U NFC读卡器。我有一个Java程序,它使用javax.smartcardio与读者进行交互。我的程序为每个找到的读者创建线程:

List<CardTerminal> terminals = TerminalFactory.getDefault().terminals().list();
int terminalCount = terminals.size();        
System.out.println("Detected " + String.valueOf(terminalCount) + " terminal/s");
for(int i = 0; i < terminalCount; i++)
{
     System.out.println("Initiating thread :" + String.valueOf(i));
     new Thread(new AccessTerminal(i,terminals.get(i))).start();
}

每个线程类都运行一个AccessTerminal类,它基本上执行以下操作:

System.out.println("Thread started... Waiting for card...");
cardTerminal.waitForCardPresent(0);
System.out.println("Card found");
card = cardTerminal.connect("*");
cardChannel = card.getBasicChannel();
if(authenticate())
{
     int UID = getUID();
     System.out.println("User identified as :" + String.valueOf(UID));
}
cardTerminal.waitForCardAbsent(0);

如果仅连接1个ACR122U,则上述代码运行良好。当我将3个ACR122U连接到WINDOWS机器时,它也可以完美运行。然而,如果我有两个或更多连接到树莓派,一个读者什么都没做,但如果我第一次扫描其他读者然后它得到“卡找到”的一半然后冻结,然后我可以刷其他读者,它来了带有NoCardPresent异常。贝娄是错误。

Starting system...
Detected 2 terminal/s
Initiating thread :0
Initiating thread :1
Thread started... Waiting for card...
Thread started... Waiting for card...
Card found
Card found
Card not valid
Nov 27, 2013 1:02:01 PM livaccess.AccessTerminal run
SEVERE: null
javax.smartcardio.CardNotPresentException: No card present
    at sun.security.smartcardio.TerminalImpl.connect(TerminalImpl.java:82)
    at livaccess.AccessTerminal.run(AccessTerminal.java:41)
    at java.lang.Thread.run(Thread.java:722)
Caused by: sun.security.smartcardio.PCSCException: SCARD_W_REMOVED_CARD
    at sun.security.smartcardio.PCSC.SCardStatus(Native Method)
    at sun.security.smartcardio.CardImpl.<init>(CardImpl.java:85)
    at sun.security.smartcardio.TerminalImpl.connect(TerminalImpl.java:78)
    ... 2 more

如果我在Windows机器上使用相同的设置执行完全相同的程序,我会得到以下输出:

Starting system...
Detected 2 terminal/s
Initiating thread :0
Initiating thread :1
Thread started... Waiting for card...
Thread started... Waiting for card...
Card found
Card is valid
User identified as :1534
Thread started... Waiting for card...
Card found
Card is valid
User identified as :1534

在这两种情况下,我都在两个读卡器上刷了同一张卡片。不要担心卡无效或有效,这是我的代码中不相关的检查。

如果有人为我提供解决方案,我会非常满意。我觉得它与linux有关,不区分两个USB设备。

感谢阅读!

1 个答案:

答案 0 :(得分:1)

似乎Raspberry Pi OS使用单独的线程无法很好地处理USB驱动程序。我没有启动新的Java线程来处理每个设备,而是在轮询卡时只通过所有设备进行单线程循环。

我使用smartcard.io java包找到了更多类似上面的问题。最后我切换到C ++ libnfc库来处理我的设备。

libnfc变得更快更稳定。特别是在一个系统上处理多个设备时。

希望这有助于某人;)