我正在尝试在我的LG G2上使用HCE,并使用Elechouse NFC模块2.0向Arduino Uno发送一些数据。
问题是nfc.inDataExchange(selectApdu, sizeof(selectApdu), response, &responseLength)
总是返回false
。出了什么问题?
在Arduino论坛,弗伦奇先生让它成功了,我也在用同样的原理。我从Android HCE示例中获取了以下内容,并发送了一些垃圾数据:
@Override
public byte[] processCommandApdu(byte[] commandApdu, Bundle extras) {
Log.i(TAG, "Received APDU: " + ByteArrayToHexString(commandApdu));
// If the APDU matches the SELECT AID command for this service,
// send the loyalty card account number, followed by a SELECT_OK status trailer (0x9000).
if (Arrays.equals(SELECT_APDU, commandApdu)) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(Build.MANUFACTURER);
stringBuilder.append("#");
stringBuilder.append(Build.MODEL);
stringBuilder.append(((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId());
String data = stringBuilder.toString();
Log.i(TAG, "Data send");
return ConcatArrays(data.getBytes(), SELECT_OK_SW);
} else {
return UNKNOWN_CMD_SW;
}
}
在Arduino方面,我从Arduino论坛中获取代码并对其进行了一些更改。现在它看起来像
void loop(void) {
bool success;
Serial.println("Waiting for an ISO14443A card");
success = nfc.inListPassiveTarget();
if(success) {
Serial.println("Found something!");
uint8_t selectApdu[] = {
0x00, /* CLA */
0xA4, /* INS */
0x04, /* P1 */
0x00, /* P2 */
0x05, /* Length of AID */
0xF2, 0x22, 0x22, 0x22, 0x22,
0x00 /* Le */};
uint8_t response[256];
uint8_t responseLength = sizeof(response);
success = nfc.inDataExchange(selectApdu, sizeof(selectApdu), response, &responseLength);
if(success) {
Serial.print("RAW: ");
for (int i = 0; i < responseLength; ) {
Serial.print(response[i++]);
Serial.print(" ");
}
Serial.println(" ");
for (int i = 0; i < responseLength; i++) {
Serial.print((char)response[i]);
Serial.print(" ");
}
Serial.println(" ");
}
else{
Serial.println("Failed sending SELECT AID");
}
}
else {
Serial.println("Didn't find anything!");
}
delay(1000);
}
我使用Arduino UNO, NFC库"PN532"从https://github.com/elechouse/PN532
显然这些行会引起问题:
uint8_t response[256];
uint8_t responseLength = sizeof(response);
success = nfc.inDataExchange(selectApdu, sizeof(selectApdu), response, &responseLength);
在第一行中,创建一个256字节的数组。在下一行中,您将该数组的大小分配给8位无符号整数(uint8_t
)变量。uint8_t
只能保存0到255(= 2^8-1)之间的值。因此,response
(= 256)的大小将导致溢出。这导致responseLength
被设置为0(= 256模2^8)。因此,您提供给nfc.inDataExchange()
的响应长度太短,无法容纳任何响应。
uint8_t response[255];
uint8_t responseLength = sizeof(response);
。
这可能是离题,但我是按照你在这里发布的相同的确切代码,但我使用Seeed Studio的NFC Shield V2。我认为这可能对其他人也有帮助。我发现,一旦我删除了selectApdu数组中的最后一个字节:
uint8_t selectApdu[] = {
0x00, /* CLA */
0xA4, /* INS */
0x04, /* P1 */
0x00, /* P2 */
0x05, /* Length of AID */
0xF2, 0x22, 0x22, 0x22, 0x22,
0x00 /* Le */};
:
uint8_t selectApdu[] = {
0x00, /* CLA */
0xA4, /* INS */
0x04, /* P1 */
0x00, /* P2 */
0x05, /* Length of AID */
0xF2, 0x22, 0x22, 0x22, 0x22};
最终允许我的三星Note 4与Arduino和Seeed Studio库提供的示例android_hce进行通信。