From e49eb6c6600448f18f8bdcd0f59da85f04a3aa7f Mon Sep 17 00:00:00 2001 From: Romuald Conty Date: Thu, 26 Jan 2012 15:23:11 +0000 Subject: [PATCH 1/3] libnfc-1.5-acr122-usb> import partial work on "ACR122 without PCSC" driver --- configure.ac | 5 +- contrib/udev/42-pn53x.rules | 4 + debian/control | 6 +- debian/rules | 4 +- libnfc/Makefile.am | 5 - libnfc/drivers.h | 6 +- libnfc/drivers/Makefile.am | 9 +- libnfc/drivers/acr122.c | 495 --------------- libnfc/drivers/acr122_usb.c | 701 ++++++++++++++++++++++ libnfc/drivers/{acr122.h => acr122_usb.h} | 27 +- libnfc/nfc.c | 5 +- m4/libnfc_drivers.m4 | 3 +- 12 files changed, 733 insertions(+), 537 deletions(-) delete mode 100644 libnfc/drivers/acr122.c create mode 100644 libnfc/drivers/acr122_usb.c rename libnfc/drivers/{acr122.h => acr122_usb.h} (52%) diff --git a/configure.ac b/configure.ac index dd71f22..c471daa 100644 --- a/configure.ac +++ b/configure.ac @@ -116,12 +116,10 @@ AM_CONDITIONAL(DOC_ENABLED, [test x"$enable_doc" = xyes]) PKG_CONFIG_REQUIRES="" LIBNFC_CHECK_LIBUSB -LIBNFC_CHECK_PCSC AC_SUBST(PKG_CONFIG_REQUIRES) AM_CONDITIONAL(LIBUSB_ENABLED, [test "$HAVE_LIBUSB" = "1"]) -AM_CONDITIONAL(PCSC_ENABLED, [test "$HAVE_PCSC" = "1"]) CUTTER_REQUIRED_VERSION=1.1.8 m4_ifdef([AC_CHECK_CUTTER], [AC_CHECK_CUTTER([>= $CUTTER_REQUIRED_VERSION])], [ac_cv_use_cutter="no"]) @@ -138,6 +136,9 @@ CFLAGS="$CFLAGS -Wall -pedantic -Wextra" # Defines and C flags CFLAGS="$CFLAGS -std=c99" +# Workarounds for libusb in c99 +CFLAGS="$CFLAGS -Du_int8_t=uint8_t -Du_int16_t=uint16_t" + AC_CONFIG_FILES([ Doxyfile Makefile diff --git a/contrib/udev/42-pn53x.rules b/contrib/udev/42-pn53x.rules index f679fcc..3118b4b 100644 --- a/contrib/udev/42-pn53x.rules +++ b/contrib/udev/42-pn53x.rules @@ -14,4 +14,8 @@ ATTRS{idVendor}=="04e6", ATTRS{idProduct}=="5591", MODE="0664", GROUP="plugdev" ATTRS{idVendor}=="1fd3", ATTRS{idProduct}=="0608", MODE="0664", GROUP="plugdev" ATTRS{idVendor}=="054c", ATTRS{idProduct}=="02e1", MODE="0664", GROUP="plugdev" +# ACR122 / Touchatag +ATTRS{idVendor}=="072f", ATTRS{idProduct}=="2200", MODE="0664", GROUP="plugdev" +ATTRS{idVendor}=="072f", ATTRS{idProduct}=="90cc", MODE="0664", GROUP="plugdev" + LABEL="pn53x_rules_end" diff --git a/debian/control b/debian/control index 32597f5..7130d67 100644 --- a/debian/control +++ b/debian/control @@ -2,7 +2,7 @@ Source: libnfc Section: libs Priority: extra Maintainer: Thomas Hood -Build-Depends: debhelper (>= 7.0.50~), dh-autoreconf, libtool, pkg-config, libusb-dev, libpcsclite-dev +Build-Depends: debhelper (>= 7.0.50~), dh-autoreconf, libtool, pkg-config, libusb-dev Standards-Version: 3.9.2 Homepage: http://www.libnfc.org/ Vcs-Svn: http://libnfc.googlecode.com/svn/trunk @@ -11,7 +11,7 @@ Vcs-Browser: http://code.google.com/p/libnfc/source/browse/#svn/trunk Package: libnfc2 Section: libs Architecture: any -Depends: ${shlibs:Depends}, ${misc:Depends}, libusb-0.1-4, libpcsclite1 (>= 1.5), libccid (>= 1.3.10), pcscd (>= 1.5) +Depends: ${shlibs:Depends}, ${misc:Depends}, libusb-0.1-4 Description: Near Field Communication (NFC) library libnfc is a Free Software library for Near Field Communication. Supported NFC hardware devices are, theorically, all hardware @@ -20,7 +20,7 @@ Description: Near Field Communication (NFC) library Package: libnfc-dev Section: libdevel Architecture: any -Depends: ${misc:Depends}, libnfc2 (= ${binary:Version}), libusb-dev, libpcsclite-dev +Depends: ${misc:Depends}, libnfc2 (= ${binary:Version}), libusb-dev Description: Near Field Communication library (development files) libnfc is a free software library for near-field communication. It supports most hardware based on the NXP PN531, PN532 or PN533 diff --git a/debian/rules b/debian/rules index c0f6d3d..8ce4fd0 100755 --- a/debian/rules +++ b/debian/rules @@ -17,7 +17,9 @@ override_dh_installchangelogs: override_dh_auto_configure: # dh_auto_configure -- --enable-serial-autoprobe - dh_auto_configure -- --enable-debug --with-drivers=all --enable-serial-autoprobe +# dh_auto_configure -- --enable-debug --with-drivers=all --enable-serial-autoprobe +# dh_auto_configure -- --enable-debug --with-drivers=acr122 --enable-serial-autoprobe + dh_auto_configure -- --enable-debug --with-drivers=pn532_uart,pn53x_usb --enable-serial-autoprobe %: dh --with autoreconf $@ diff --git a/libnfc/Makefile.am b/libnfc/Makefile.am index 7a62c23..0d4a9b9 100644 --- a/libnfc/Makefile.am +++ b/libnfc/Makefile.am @@ -25,11 +25,6 @@ libnfc_la_LIBADD = \ $(top_builddir)/libnfc/buses/libnfcbuses.la \ $(top_builddir)/libnfc/drivers/libnfcdrivers.la -if PCSC_ENABLED - libnfc_la_CFLAGS += @libpcsclite_CFLAGS@ -DHAVE_PCSC - libnfc_la_LIBADD += @libpcsclite_LIBS@ -endif - if LIBUSB_ENABLED libnfc_la_CFLAGS += @libusb_CFLAGS@ -DHAVE_LIBUSB libnfc_la_LIBADD += @libusb_LIBS@ diff --git a/libnfc/drivers.h b/libnfc/drivers.h index 694b160..8df01c6 100644 --- a/libnfc/drivers.h +++ b/libnfc/drivers.h @@ -29,13 +29,9 @@ # include # if defined (DRIVER_ACR122_ENABLED) -# include "drivers/acr122.h" +# include "drivers/acr122_usb.h" # endif /* DRIVER_ACR122_ENABLED */ -# if defined (DRIVER_ACR122S_ENABLED) -# include "drivers/acr122s.h" -# endif /* DRIVER_ACR122S_ENABLED */ - # if defined (DRIVER_PN53X_USB_ENABLED) # include "drivers/pn53x_usb.h" # endif /* DRIVER_PN53X_USB_ENABLED */ diff --git a/libnfc/drivers/Makefile.am b/libnfc/drivers/Makefile.am index edfef5f..6745333 100644 --- a/libnfc/drivers/Makefile.am +++ b/libnfc/drivers/Makefile.am @@ -1,7 +1,7 @@ # set the include path found by configure INCLUDES= $(all_includes) $(LIBNFC_CFLAGS) -noinst_HEADERS = acr122.h acr122s.h arygon.h pn532_uart.h pn53x_usb.h +noinst_HEADERS = acr122_usb.h acr122s.h arygon.h pn532_uart.h pn53x_usb.h noinst_LTLIBRARIES = libnfcdrivers.la libnfcdrivers_la_SOURCES = @@ -9,7 +9,7 @@ libnfcdrivers_la_CFLAGS = @DRIVERS_CFLAGS@ -I$(top_srcdir)/libnfc -I$(top_srcdir libnfcdrivers_la_LIBADD = if DRIVER_ACR122_ENABLED -libnfcdrivers_la_SOURCES += acr122.c +libnfcdrivers_la_SOURCES += acr122_usb.c endif if DRIVER_ACR122S_ENABLED @@ -28,11 +28,6 @@ if DRIVER_PN532_UART_ENABLED libnfcdrivers_la_SOURCES += pn532_uart.c endif -if PCSC_ENABLED - libnfcdrivers_la_CFLAGS += @libpcsclite_CFLAGS@ - libnfcdrivers_la_LIBADD += @libpcsclite_LIBS@ -endif - if LIBUSB_ENABLED libnfcdrivers_la_CFLAGS += @libusb_CFLAGS@ libnfcdrivers_la_LIBADD += @libusb_LIBS@ diff --git a/libnfc/drivers/acr122.c b/libnfc/drivers/acr122.c deleted file mode 100644 index 2acfaf8..0000000 --- a/libnfc/drivers/acr122.c +++ /dev/null @@ -1,495 +0,0 @@ -/*- - * Public platform independent Near Field Communication (NFC) library - * - * Copyright (C) 2009, Roel Verdult - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ - -/** - * @file acr122.c - * @brief Driver for ACR122 devices (e.g. Tikitag, Touchatag, ACS ACR122) - */ - -#ifdef HAVE_CONFIG_H -# include "config.h" -#endif // HAVE_CONFIG_H - -#include -#include -#include -#include -#include - -#include - -#include "chips/pn53x.h" -#include "drivers/acr122.h" -#include "nfc-internal.h" - -// Bus -#include - -#define ACR122_DRIVER_NAME "acr122" - -#if defined (_WIN32) -# define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE SCARD_CTL_CODE(3500) -#elif defined(__APPLE__) -# include -# define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE (((0x31) << 16) | ((3500) << 2)) -#elif defined (__FreeBSD__) || defined (__OpenBSD__) -# define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE (((0x31) << 16) | ((3500) << 2)) -#elif defined (__linux__) -# include -// Escape IOCTL tested successfully: -# define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE SCARD_CTL_CODE(1) -#else -# error "Can't determine serial string for your system" -#endif - -#include - -#define SCARD_OPERATION_SUCCESS 0x61 -#define SCARD_OPERATION_ERROR 0x63 - -#ifndef SCARD_PROTOCOL_UNDEFINED -# define SCARD_PROTOCOL_UNDEFINED SCARD_PROTOCOL_UNSET -#endif - -#define FIRMWARE_TEXT "ACR122U" // Tested on: ACR122U101(ACS), ACR122U102(Tikitag), ACR122U203(ACS) - -#define ACR122_WRAP_LEN 5 -#define ACR122_COMMAND_LEN 266 -#define ACR122_RESPONSE_LEN 268 - -#define LOG_CATEGORY "libnfc.driver.acr122" - -const struct pn53x_io acr122_io; - -char *acr122_firmware (nfc_device *pnd); - -const char *supported_devices[] = { - "ACS ACR122", // ACR122U & Touchatag, last version - "ACS ACR 38U-CCID", // Touchatag, early version - "ACS ACR38U-CCID", // Touchatag, early version, under MacOSX - " CCID USB", // ?? - NULL -}; - -struct acr122_data { - SCARDHANDLE hCard; - SCARD_IO_REQUEST ioCard; - uint8_t abtRx[ACR122_RESPONSE_LEN]; - size_t szRx; -}; - -#define DRIVER_DATA(pnd) ((struct acr122_data*)(pnd->driver_data)) - -static SCARDCONTEXT _SCardContext; -static int _iSCardContextRefCount = 0; - -SCARDCONTEXT * -acr122_get_scardcontext (void) -{ - if (_iSCardContextRefCount == 0) { - if (SCardEstablishContext (SCARD_SCOPE_USER, NULL, NULL, &_SCardContext) != SCARD_S_SUCCESS) - return NULL; - } - _iSCardContextRefCount++; - - return &_SCardContext; -} - -void -acr122_free_scardcontext (void) -{ - if (_iSCardContextRefCount) { - _iSCardContextRefCount--; - if (!_iSCardContextRefCount) { - SCardReleaseContext (_SCardContext); - } - } -} - -#define PCSC_MAX_DEVICES 16 -/** - * @brief List opened devices - * - * Probe PCSC to find NFC capable hardware. - * - * @param pnddDevices Array of nfc_device_desc_t previously allocated by the caller. - * @param szDevices size of the pnddDevices array. - * @param pszDeviceFound number of devices found. - * @return true if succeeded, false otherwise. - */ -bool -acr122_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound) -{ - size_t szPos = 0; - char acDeviceNames[256 + 64 * PCSC_MAX_DEVICES]; - size_t szDeviceNamesLen = sizeof (acDeviceNames); - uint32_t uiBusIndex = 0; - SCARDCONTEXT *pscc; - bool bSupported; - int i; - - // Clear the reader list - memset (acDeviceNames, '\0', szDeviceNamesLen); - - *pszDeviceFound = 0; - - // Test if context succeeded - if (!(pscc = acr122_get_scardcontext ())) { - log_put (LOG_CATEGORY, NFC_PRIORITY_WARN, "%s", "PCSC context not found (make sure PCSC daemon is running)."); - return false; - } - // Retrieve the string array of all available pcsc readers - DWORD dwDeviceNamesLen = szDeviceNamesLen; - if (SCardListReaders (*pscc, NULL, acDeviceNames, &dwDeviceNamesLen) != SCARD_S_SUCCESS) - return false; - - while ((acDeviceNames[szPos] != '\0') && ((*pszDeviceFound) < connstrings_len)) { - uiBusIndex++; - - // DBG("- %s (pos=%ld)", acDeviceNames + szPos, (unsigned long) szPos); - - bSupported = false; - for (i = 0; supported_devices[i] && !bSupported; i++) { - int l = strlen (supported_devices[i]); - bSupported = 0 == strncmp (supported_devices[i], acDeviceNames + szPos, l); - } - - if (bSupported) { - // Supported ACR122 device found - snprintf (connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s:%"PRIu32, ACR122_DRIVER_NAME, acDeviceNames + szPos, uiBusIndex); - (*pszDeviceFound)++; - } else { - log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "PCSC device [%s] is not NFC capable or not supported by libnfc.", acDeviceNames + szPos); - } - - // Find next device name position - while (acDeviceNames[szPos++] != '\0'); - } - acr122_free_scardcontext (); - - return true; -} - -struct acr122_descriptor { - char pcsc_device_name[512]; - int bus_index; -}; - -int -acr122_connstring_decode (const nfc_connstring connstring, struct acr122_descriptor *desc) -{ - char *cs = malloc (strlen (connstring) + 1); - if (!cs) { - perror ("malloc"); - return -1; - } - strcpy (cs, connstring); - const char *driver_name = strtok (cs, ":"); - if (!driver_name) { - // Parse error - free (cs); - return -1; - } - - if (0 != strcmp (driver_name, ACR122_DRIVER_NAME)) { - // Driver name does not match. - free (cs); - return 0; - } - - const char *device_name = strtok (NULL, ":"); - if (!device_name) { - // Only driver name was specified (or parsing error) - free (cs); - return 1; - } - strncpy (desc->pcsc_device_name, device_name, sizeof(desc->pcsc_device_name)-1); - desc->pcsc_device_name[sizeof(desc->pcsc_device_name)-1] = '\0'; - - const char *bus_index_s = strtok (NULL, ":"); - if (!bus_index_s) { - // bus index not specified (or parsing error) - free (cs); - return 2; - } - unsigned long bus_index; - if (sscanf (bus_index_s, "%lu", &bus_index) != 1) { - // bus_index_s is not a number - free (cs); - return 2; - } - desc->bus_index = bus_index; - - free (cs); - return 3; -} - -nfc_device * -acr122_open (const nfc_connstring connstring) -{ - struct acr122_descriptor ndd; - int connstring_decode_level = acr122_connstring_decode (connstring, &ndd); - - if (connstring_decode_level < 2) { - return NULL; - } - // FIXME: acr122_open() does not take care about bus index - - char *pcFirmware; - nfc_device *pnd = nfc_device_new (connstring); - pnd->driver_data = malloc (sizeof (struct acr122_data)); - - // Alloc and init chip's data - pn53x_data_new (pnd, &acr122_io); - - SCARDCONTEXT *pscc; - - log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "Attempt to open %s", ndd.pcsc_device_name); - // Test if context succeeded - if (!(pscc = acr122_get_scardcontext ())) - goto error; - // Test if we were able to connect to the "emulator" card - if (SCardConnect (*pscc, ndd.pcsc_device_name, SCARD_SHARE_EXCLUSIVE, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &(DRIVER_DATA (pnd)->hCard), (void *) &(DRIVER_DATA (pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) { - // Connect to ACR122 firmware version >2.0 - if (SCardConnect (*pscc, ndd.pcsc_device_name, SCARD_SHARE_DIRECT, 0, &(DRIVER_DATA (pnd)->hCard), (void *) &(DRIVER_DATA (pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) { - // We can not connect to this device. - log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%s", "PCSC connect failed"); - goto error; - } - } - // Configure I/O settings for card communication - DRIVER_DATA (pnd)->ioCard.cbPciLength = sizeof (SCARD_IO_REQUEST); - - // Retrieve the current firmware version - pcFirmware = acr122_firmware (pnd); - if (strstr (pcFirmware, FIRMWARE_TEXT) != NULL) { - - // Done, we found the reader we are looking for - snprintf (pnd->name, sizeof (pnd->name), "%s / %s", ndd.pcsc_device_name, pcFirmware); - - // 50: empirical tuning on Touchatag - // 46: empirical tuning on ACR122U - CHIP_DATA (pnd)->timer_correction = 50; - - pnd->driver = &acr122_driver; - - pn53x_init (pnd); - - return pnd; - } - -error: - nfc_device_free (pnd); - - return NULL; -} - -void -acr122_close (nfc_device *pnd) -{ - SCardDisconnect (DRIVER_DATA (pnd)->hCard, SCARD_LEAVE_CARD); - acr122_free_scardcontext (); - - pn53x_data_free (pnd); - nfc_device_free (pnd); -} - -int -acr122_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) -{ - // FIXME: timeout is not handled - (void) timeout; - - // Make sure the command does not overflow the send buffer - if (szData > ACR122_COMMAND_LEN) { - pnd->last_error = NFC_EINVARG; - return pnd->last_error; - } - - // Prepare and transmit the send buffer - const size_t szTxBuf = szData + 6; - uint8_t abtTxBuf[ACR122_WRAP_LEN + ACR122_COMMAND_LEN] = { 0xFF, 0x00, 0x00, 0x00, szData + 1, 0xD4 }; - memcpy (abtTxBuf + 6, pbtData, szData); - LOG_HEX ("TX", abtTxBuf, szTxBuf); - - DRIVER_DATA (pnd)->szRx = 0; - - DWORD dwRxLen = sizeof (DRIVER_DATA (pnd)->abtRx); - - if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { - /* - * In this communication mode, we directly have the response from the - * PN532. Save it in the driver data structure so that it can be retrieved - * in ac122_receive(). - * - * Some devices will never enter this state (e.g. Touchatag) but are still - * supported through SCardTransmit calls (see bellow). - * - * This state is generaly reached when the ACR122 has no target in it's - * field. - */ - if (SCardControl (DRIVER_DATA (pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtTxBuf, szTxBuf, DRIVER_DATA (pnd)->abtRx, ACR122_RESPONSE_LEN, &dwRxLen) != SCARD_S_SUCCESS) { - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - } else { - /* - * In T=0 mode, we receive an acknoledge from the MCU, in T=1 mode, we - * receive the response from the PN532. - */ - if (SCardTransmit (DRIVER_DATA (pnd)->hCard, &(DRIVER_DATA (pnd)->ioCard), abtTxBuf, szTxBuf, NULL, DRIVER_DATA (pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) { - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - } - - if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) { - /* - * Check the MCU response - */ - - // Make sure we received the byte-count we expected - if (dwRxLen != 2) { - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - // Check if the operation was successful, so an answer is available - if (DRIVER_DATA (pnd)->abtRx[0] == SCARD_OPERATION_ERROR) { - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - } else { - DRIVER_DATA (pnd)->szRx = dwRxLen; - } - - return NFC_SUCCESS; -} - -int -acr122_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout) -{ - // FIXME: timeout is not handled - (void) timeout; - - int len; - uint8_t abtRxCmd[5] = { 0xFF, 0xC0, 0x00, 0x00 }; - - if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) { - /* - * Retrieve the PN532 response. - */ - DWORD dwRxLen = sizeof (DRIVER_DATA (pnd)->abtRx); - abtRxCmd[4] = DRIVER_DATA (pnd)->abtRx[1]; - if (SCardTransmit (DRIVER_DATA (pnd)->hCard, &(DRIVER_DATA (pnd)->ioCard), abtRxCmd, sizeof (abtRxCmd), NULL, DRIVER_DATA (pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) { - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - DRIVER_DATA (pnd)->szRx = dwRxLen; - } else { - /* - * We already have the PN532 answer, it was saved by acr122_send(). - */ - } - LOG_HEX ("RX", DRIVER_DATA (pnd)->abtRx, DRIVER_DATA (pnd)->szRx); - - // Make sure we have an emulated answer that fits the return buffer - if (DRIVER_DATA (pnd)->szRx < 4 || (DRIVER_DATA (pnd)->szRx - 4) > szData) { - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - // Wipe out the 4 APDU emulation bytes: D5 4B .. .. .. 90 00 - len = DRIVER_DATA (pnd)->szRx - 4; - memcpy (pbtData, DRIVER_DATA (pnd)->abtRx + 2, len); - - return len; -} - -char * -acr122_firmware (nfc_device *pnd) -{ - uint8_t abtGetFw[5] = { 0xFF, 0x00, 0x48, 0x00, 0x00 }; - uint32_t uiResult; - - static char abtFw[11]; - DWORD dwFwLen = sizeof (abtFw); - memset (abtFw, 0x00, sizeof (abtFw)); - if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { - uiResult = SCardControl (DRIVER_DATA (pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtGetFw, sizeof (abtGetFw), (uint8_t *) abtFw, dwFwLen-1, &dwFwLen); - } else { - uiResult = SCardTransmit (DRIVER_DATA (pnd)->hCard, &(DRIVER_DATA (pnd)->ioCard), abtGetFw, sizeof (abtGetFw), NULL, (uint8_t *) abtFw, &dwFwLen); - } - - if (uiResult != SCARD_S_SUCCESS) { - log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "No ACR122 firmware received, Error: %08x", uiResult); - } - - return abtFw; -} - -#if 0 -bool -acr122_led_red (nfc_device *pnd, bool bOn) -{ - uint8_t abtLed[9] = { 0xFF, 0x00, 0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x00 }; - uint8_t abtBuf[2]; - DWORD dwBufLen = sizeof (abtBuf); - (void) bOn; - if (DRIVER_DATA (pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { - return (SCardControl (DRIVER_DATA (pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtLed, sizeof (abtLed), abtBuf, dwBufLen, &dwBufLen) == SCARD_S_SUCCESS); - } else { - return (SCardTransmit (DRIVER_DATA (pnd)->hCard, &(DRIVER_DATA (pnd)->ioCard), abtLed, sizeof (abtLed), NULL, abtBuf, &dwBufLen) == SCARD_S_SUCCESS); - } -} -#endif - -const struct pn53x_io acr122_io = { - .send = acr122_send, - .receive = acr122_receive, -}; - -const struct nfc_driver acr122_driver = { - .name = ACR122_DRIVER_NAME, - .probe = acr122_probe, - .open = acr122_open, - .close = acr122_close, - .strerror = pn53x_strerror, - - .initiator_init = pn53x_initiator_init, - .initiator_select_passive_target = pn53x_initiator_select_passive_target, - .initiator_poll_target = pn53x_initiator_poll_target, - .initiator_select_dep_target = pn53x_initiator_select_dep_target, - .initiator_deselect_target = pn53x_initiator_deselect_target, - .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, - .initiator_transceive_bits = pn53x_initiator_transceive_bits, - .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, - .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, - - .target_init = pn53x_target_init, - .target_send_bytes = pn53x_target_send_bytes, - .target_receive_bytes = pn53x_target_receive_bytes, - .target_send_bits = pn53x_target_send_bits, - .target_receive_bits = pn53x_target_receive_bits, - - .device_set_property_bool = pn53x_set_property_bool, - .device_set_property_int = pn53x_set_property_int, - - .abort_command = NULL, // FIXME: abort is not supported in this driver - .idle = NULL, // FIXME: idle is not supported in this driver -}; - diff --git a/libnfc/drivers/acr122_usb.c b/libnfc/drivers/acr122_usb.c new file mode 100644 index 0000000..97452cb --- /dev/null +++ b/libnfc/drivers/acr122_usb.c @@ -0,0 +1,701 @@ +/*- + * Public platform independent Near Field Communication (NFC) library + * + * Copyright (C) 2009, Roel Verdult + * Copyright (C) 2010, Romain Tartière, Romuald Conty + * Copyright (C) 2011, Romain Tartière, Romuald Conty + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see + */ + +/** + * @file acr122_usb.c + * @brief Driver for ACR122 using direct USB (without PCSC) + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif // HAVE_CONFIG_H + +/* +Thanks to d18c7db and Okko for example code +*/ + +#include +#include +#include +#include +#include + +#ifndef _WIN32 + // Under POSIX system, we use libusb (>= 0.1.12) + #include + #define USB_TIMEDOUT ETIMEDOUT + #define _usb_strerror( X ) strerror(-X) +#else + // Under Windows we use libusb-win32 (>= 1.2.5) + #include + #define USB_TIMEDOUT 116 + #define _usb_strerror( X ) usb_strerror() +#endif + +#include + +#include + +#include "nfc-internal.h" +#include "chips/pn53x.h" +#include "chips/pn53x-internal.h" +#include "drivers/acr122_usb.h" + +#define PN53X_USB_DRIVER_NAME "acr122_usb" +#define LOG_CATEGORY "libnfc.driver.acr122_usb" + +#define USB_INFINITE_TIMEOUT 0 + +#define DRIVER_DATA(pnd) ((struct acr122_usb_data*)(pnd->driver_data)) + +typedef enum { + UNKNOWN, + ACR122, + TOUCHATAG, +} acr122_usb_model; + +struct acr122_usb_data { + usb_dev_handle *pudh; + acr122_usb_model model; + uint32_t uiEndPointIn; + uint32_t uiEndPointOut; + uint32_t uiMaxPacketSize; + volatile bool abort_flag; +}; + +const struct pn53x_io acr122_usb_io; +bool acr122_usb_get_usb_device_name (struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len); +int acr122_usb_init (nfc_device *pnd); + +int +acr122_usb_bulk_read (struct acr122_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout) +{ + int res = usb_bulk_read (data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout); + if (res > 0) { + LOG_HEX ("RX", abtRx, res); + } else if (res < 0) { + if (res != -USB_TIMEDOUT) + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror (res)); + } + return res; +} + +int +acr122_usb_bulk_write (struct acr122_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout) +{ + LOG_HEX ("TX", abtTx, szTx); + int res = usb_bulk_write (data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout); + if (res > 0) { + // HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details + if ((res % data->uiMaxPacketSize) == 0) { + usb_bulk_write (data->pudh, data->uiEndPointOut, "\0", 0, timeout); + } + } else { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror (res)); + } + return res; +} + +struct acr122_usb_supported_device { + uint16_t vendor_id; + uint16_t product_id; + acr122_usb_model model; + const char *name; +}; + +const struct acr122_usb_supported_device acr122_usb_supported_devices[] = { + { 0x072F, 0x2200, ACR122, "ACS ACR122" }, + { 0x072F, 0x90CC, TOUCHATAG, "Touchatag" }, +}; + +acr122_usb_model +acr122_usb_get_device_model (uint16_t vendor_id, uint16_t product_id) +{ + for (size_t n = 0; n < sizeof (acr122_usb_supported_devices) / sizeof (struct acr122_usb_supported_device); n++) { + if ((vendor_id == acr122_usb_supported_devices[n].vendor_id) && + (product_id == acr122_usb_supported_devices[n].product_id)) + return acr122_usb_supported_devices[n].model; + } + + return UNKNOWN; +} + +int acr122_usb_ack (nfc_device *pnd); + +// Find transfer endpoints for bulk transfers +void +acr122_usb_get_end_points (struct usb_device *dev, struct acr122_usb_data *data) +{ + uint32_t uiIndex; + uint32_t uiEndPoint; + struct usb_interface_descriptor *puid = dev->config->interface->altsetting; + + // 3 Endpoints maximum: Interrupt In, Bulk In, Bulk Out + for (uiIndex = 0; uiIndex < puid->bNumEndpoints; uiIndex++) { + // Only accept bulk transfer endpoints (ignore interrupt endpoints) + if (puid->endpoint[uiIndex].bmAttributes != USB_ENDPOINT_TYPE_BULK) + continue; + + // Copy the endpoint to a local var, makes it more readable code + uiEndPoint = puid->endpoint[uiIndex].bEndpointAddress; + + // Test if we dealing with a bulk IN endpoint + if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_IN) { + data->uiEndPointIn = uiEndPoint; + data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; + } + // Test if we dealing with a bulk OUT endpoint + if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_OUT) { + data->uiEndPointOut = uiEndPoint; + data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; + } + } +} + +bool +acr122_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound) +{ + usb_init (); + + int res; + // usb_find_busses will find all of the busses on the system. Returns the + // number of changes since previous call to this function (total of new + // busses and busses removed). + if ((res = usb_find_busses () < 0)) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror (res)); + return false; + } + // usb_find_devices will find all of the devices on each bus. This should be + // called after usb_find_busses. Returns the number of changes since the + // previous call to this function (total of new device and devices removed). + if ((res = usb_find_devices () < 0)) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror (res)); + return false; + } + + *pszDeviceFound = 0; + + uint32_t uiBusIndex = 0; + struct usb_bus *bus; + for (bus = usb_get_busses (); bus; bus = bus->next) { + struct usb_device *dev; + + for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) { + for (size_t n = 0; n < sizeof (acr122_usb_supported_devices) / sizeof (struct acr122_usb_supported_device); n++) { + if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && + (acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { + // Make sure there are 2 endpoints available + // with libusb-win32 we got some null pointers so be robust before looking at endpoints: + if (dev->config == NULL || dev->config->interface == NULL || dev->config->interface->altsetting == NULL) { + // Nope, we maybe want the next one, let's try to find another + continue; + } + if (dev->config->interface->altsetting->bNumEndpoints < 2) { + // Nope, we maybe want the next one, let's try to find another + continue; + } + + usb_dev_handle *udev = usb_open (dev); + + // Set configuration + int res = usb_set_configuration (udev, 1); + if (res < 0) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror (res)); + usb_close (udev); + // we failed to use the device + continue; + } + + // acr122_usb_get_usb_device_name (dev, udev, pnddDevices[*pszDeviceFound].acDevice, sizeof (pnddDevices[*pszDeviceFound].acDevice)); + log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "device found: Bus %s Device %s", bus->dirname, dev->filename); + usb_close (udev); + snprintf (connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s:%s", PN53X_USB_DRIVER_NAME, bus->dirname, dev->filename); + (*pszDeviceFound)++; + // Test if we reach the maximum "wanted" devices + if ((*pszDeviceFound) == connstrings_len) { + return true; + } + } + } + } + } + + return true; +} + +struct acr122_usb_descriptor { + uint16_t bus; + uint16_t dev; +}; + +int +acr122_usb_connstring_decode (const nfc_connstring connstring, struct acr122_usb_descriptor *desc) +{ + char *cs = malloc (strlen (connstring) + 1); + if (!cs) { + perror ("malloc"); + return -1; + } + strcpy (cs, connstring); + const char *driver_name = strtok (cs, ":"); + if (!driver_name) { + // Parse error + free (cs); + return -1; + } + + if (0 != strcmp (driver_name, PN53X_USB_DRIVER_NAME)) { + // Driver name does not match. + free (cs); + return 0; + } + + const char *bus_s = strtok (NULL, ":"); + if (!bus_s) { + // bus not specified (or parsing error) + free (cs); + return 1; + } + unsigned int bus; + if (sscanf (bus_s, "%u", &bus) != 1) { + // bus_s is not a number + free (cs); + return 1; + } + desc->bus = bus; + + const char *dev_s = strtok (NULL, ":"); + if (!dev_s) { + // dev not specified (or parsing error) + free (cs); + return 2; + } + unsigned int dev; + if (sscanf (dev_s, "%u", &dev) != 1) { + // dev_s is not a number + free (cs); + return 2; + } + desc->dev = dev; + free (cs); + return 3; +} + +bool +acr122_usb_get_usb_device_name (struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len) +{ + *buffer = '\0'; + + if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) { + if (udev) { + usb_get_string_simple (udev, dev->descriptor.iManufacturer, buffer, len); + if (strlen (buffer) > 0) + strcpy (buffer + strlen (buffer), " / "); + usb_get_string_simple (udev, dev->descriptor.iProduct, buffer + strlen (buffer), len - strlen (buffer)); + } + } + + if (!*buffer) { + for (size_t n = 0; n < sizeof (acr122_usb_supported_devices) / sizeof (struct acr122_usb_supported_device); n++) { + if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && + (acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { + strncpy (buffer, acr122_usb_supported_devices[n].name, len); + return true; + } + } + } + + return false; +} + +nfc_device * +acr122_usb_open (const nfc_connstring connstring) +{ + struct acr122_usb_descriptor desc; + int connstring_decode_level = acr122_usb_connstring_decode (connstring, &desc); + log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); + if (connstring_decode_level < 1) { + return NULL; + } + + nfc_device *pnd = NULL; + struct acr122_usb_data data = { + .pudh = NULL, + .uiEndPointIn = 0, + .uiEndPointOut = 0, + }; + struct usb_bus *bus; + struct usb_device *dev; + + usb_init (); + + for (bus = usb_get_busses (); bus; bus = bus->next) { + if (connstring_decode_level > 1) { + // A specific bus have been specified + unsigned int bus_current; + sscanf (bus->dirname, "%u", &bus_current); + if (bus_current != desc.bus) + continue; + } + for (dev = bus->devices; dev; dev = dev->next) { + if (connstring_decode_level > 2) { + // A specific dev have been specified + unsigned int dev_current; + sscanf (dev->filename, "%u", &dev_current); + if (dev_current != desc.dev) + continue; + } + // Open the USB device + data.pudh = usb_open (dev); + // Retrieve end points + acr122_usb_get_end_points (dev, &data); + // Set configuration + int res = usb_set_configuration (data.pudh, 1); + if (res < 0) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror (res)); + if (EPERM == -res) { + log_put (LOG_CATEGORY, NFC_PRIORITY_WARN, "Please double check USB permissions for device %04x:%04x", dev->descriptor.idVendor, dev->descriptor.idProduct); + } + usb_close (data.pudh); + // we failed to use the specified device + return NULL; + } + + res = usb_claim_interface (data.pudh, 0); + if (res < 0) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror (res)); + usb_close (data.pudh); + // we failed to use the specified device + return NULL; + } + data.model = acr122_usb_get_device_model (dev->descriptor.idVendor, dev->descriptor.idProduct); + // Allocate memory for the device info and specification, fill it and return the info + pnd = nfc_device_new (connstring); + acr122_usb_get_usb_device_name (dev, data.pudh, pnd->name, sizeof (pnd->name)); + + pnd->driver_data = malloc(sizeof(struct acr122_usb_data)); + *DRIVER_DATA (pnd) = data; + + // Alloc and init chip's data + pn53x_data_new (pnd, &acr122_usb_io); + + switch (DRIVER_DATA (pnd)->model) { + // empirical tuning + case ACR122: + CHIP_DATA (pnd)->timer_correction = 46; + break; + case TOUCHATAG: + CHIP_DATA (pnd)->timer_correction = 50; + break; + default: + break; + } + pnd->driver = &acr122_usb_driver; + + // HACK1: Send first an ACK as Abort command, to reset chip before talking to it: + acr122_usb_ack (pnd); + + // HACK2: Then send a GetFirmware command to resync USB toggle bit between host & device + // in case host used set_configuration and expects the device to have reset its toggle bit, which PN53x doesn't do + if (acr122_usb_init (pnd) < 0) { + usb_close (data.pudh); + goto error; + } + DRIVER_DATA (pnd)->abort_flag = false; + return pnd; + } + } + // We ran out of devices before the index required + return NULL; + +error: + // Free allocated structure on error. + nfc_device_free (pnd); + return NULL; +} + +void +acr122_usb_close (nfc_device *pnd) +{ + acr122_usb_ack (pnd); + + pn53x_idle (pnd); + + int res; + if ((res = usb_release_interface (DRIVER_DATA (pnd)->pudh, 0)) < 0) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror (res)); + } + + if ((res = usb_close (DRIVER_DATA (pnd)->pudh)) < 0) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror (res)); + } + pn53x_data_free (pnd); + nfc_device_free (pnd); +} + +#define PN53X_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) + +int +acr122_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout) +{ + uint8_t abtFrame[PN53X_USB_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" + size_t szFrame = 0; + + pn53x_build_frame (abtFrame, &szFrame, pbtData, szData); + + int res = acr122_usb_bulk_write (DRIVER_DATA (pnd), abtFrame, szFrame, timeout); + + if (res < 0) { + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + + uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; + res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), timeout); + if (res < 0) { + pnd->last_error = NFC_EIO; + // try to interrupt current device state + acr122_usb_ack(pnd); + return pnd->last_error; + } + + if (pn53x_check_ack_frame (pnd, abtRxBuf, res) == 0) { + // The PN53x is running the sent command + } else { + // For some reasons (eg. send another command while a previous one is + // running), the PN533 sometimes directly replies the response packet + // instead of ACK frame, so we send a NACK frame to force PN533 to resend + // response packet. With this hack, the nextly executed function (ie. + // acr122_usb_receive()) will be able to retreive the correct response + // packet. + // FIXME Sony reader is also affected by this bug but NACK is not supported + int res = acr122_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *)pn53x_nack_frame, sizeof(pn53x_nack_frame), timeout); + if (res < 0) { + pnd->last_error = NFC_EIO; + // try to interrupt current device state + acr122_usb_ack(pnd); + return pnd->last_error; + } + } + + return NFC_SUCCESS; +} + +#define USB_TIMEOUT_PER_PASS 200 +int +acr122_usb_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout) +{ + size_t len; + off_t offset = 0; + + uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; + int res; + + /* + * If no timeout is specified but the command is blocking, force a 200ms (USB_TIMEOUT_PER_PASS) + * timeout to allow breaking the loop if the user wants to stop it. + */ + int usb_timeout; + int remaining_time = timeout; +read: + if (timeout == USB_INFINITE_TIMEOUT) { + usb_timeout = USB_TIMEOUT_PER_PASS; + } else { + // A user-provided timeout is set, we have to cut it in multiple chunk to be able to keep an nfc_abort_command() mecanism + remaining_time -= USB_TIMEOUT_PER_PASS; + if (remaining_time <= 0) { + pnd->last_error = NFC_ETIMEOUT; + return pnd->last_error; + } else { + usb_timeout = MIN(remaining_time, USB_TIMEOUT_PER_PASS); + } + } + + res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), usb_timeout); + + if (res == -USB_TIMEDOUT) { + if (DRIVER_DATA (pnd)->abort_flag) { + DRIVER_DATA (pnd)->abort_flag = false; + acr122_usb_ack (pnd); + pnd->last_error = NFC_EOPABORTED; + return pnd->last_error; + } else { + goto read; + } + } + + if (res < 0) { + pnd->last_error = NFC_EIO; + // try to interrupt current device state + acr122_usb_ack(pnd); + return pnd->last_error; + } + + const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; + if (0 != (memcmp (abtRxBuf, pn53x_preamble, 3))) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + offset += 3; + + if ((0x01 == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { + // Error frame + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Application level error detected"); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } else if ((0xff == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { + // Extended frame + offset += 2; + + // (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] (LEN) include TFI + (CC+1) + len = (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] - 2; + if (((abtRxBuf[offset] + abtRxBuf[offset + 1] + abtRxBuf[offset + 2]) % 256) != 0) { + // TODO: Retry + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch"); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + offset += 3; + } else { + // Normal frame + if (256 != (abtRxBuf[offset] + abtRxBuf[offset + 1])) { + // TODO: Retry + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch"); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + + // abtRxBuf[3] (LEN) include TFI + (CC+1) + len = abtRxBuf[offset] - 2; + offset += 2; + } + + if (len > szDataLen) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + + // TFI + PD0 (CC+1) + if (abtRxBuf[offset] != 0xD5) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch"); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + offset += 1; + + if (abtRxBuf[offset] != CHIP_DATA (pnd)->last_command + 1) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Command Code verification failed"); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + offset += 1; + + memcpy (pbtData, abtRxBuf + offset, len); + offset += len; + + uint8_t btDCS = (256 - 0xD5); + btDCS -= CHIP_DATA (pnd)->last_command + 1; + for (size_t szPos = 0; szPos < len; szPos++) { + btDCS -= pbtData[szPos]; + } + + if (btDCS != abtRxBuf[offset]) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Data checksum mismatch"); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + offset += 1; + + if (0x00 != abtRxBuf[offset]) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + // The PN53x command is done and we successfully received the reply + pnd->last_error = 0; + return len; +} + +int +acr122_usb_ack (nfc_device *pnd) +{ + return acr122_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *) pn53x_ack_frame, sizeof (pn53x_ack_frame), 1000); +} + +int +acr122_usb_init (nfc_device *pnd) +{ + int res = 0; + // Sometimes PN53x USB doesn't reply ACK one the first frame, so we need to send a dummy one... + const uint8_t abtCmd[] = { GetFirmwareVersion }; + pn53x_transceive (pnd, abtCmd, sizeof (abtCmd), NULL, 0, -1); + // ...and we don't care about error + pnd->last_error = 0; + + if ((res = pn53x_init (pnd)) < 0) + return res; + + return NFC_SUCCESS; +} + +int +acr122_usb_abort_command (nfc_device *pnd) +{ + DRIVER_DATA (pnd)->abort_flag = true; + return NFC_SUCCESS; +} + +const struct pn53x_io acr122_usb_io = { + .send = acr122_usb_send, + .receive = acr122_usb_receive, +}; + +const struct nfc_driver acr122_usb_driver = { + .name = PN53X_USB_DRIVER_NAME, + .probe = acr122_usb_probe, + .open = acr122_usb_open, + .close = acr122_usb_close, + .strerror = pn53x_strerror, + + .initiator_init = pn53x_initiator_init, + .initiator_select_passive_target = pn53x_initiator_select_passive_target, + .initiator_poll_target = pn53x_initiator_poll_target, + .initiator_select_dep_target = pn53x_initiator_select_dep_target, + .initiator_deselect_target = pn53x_initiator_deselect_target, + .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, + .initiator_transceive_bits = pn53x_initiator_transceive_bits, + .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, + .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, + + .target_init = pn53x_target_init, + .target_send_bytes = pn53x_target_send_bytes, + .target_receive_bytes = pn53x_target_receive_bytes, + .target_send_bits = pn53x_target_send_bits, + .target_receive_bits = pn53x_target_receive_bits, + + .device_set_property_bool = pn53x_set_property_bool, + .device_set_property_int = pn53x_set_property_int, + + .abort_command = acr122_usb_abort_command, + .idle = pn53x_idle, +}; diff --git a/libnfc/drivers/acr122.h b/libnfc/drivers/acr122_usb.h similarity index 52% rename from libnfc/drivers/acr122.h rename to libnfc/drivers/acr122_usb.h index 5c2ba98..76ca4d9 100644 --- a/libnfc/drivers/acr122.h +++ b/libnfc/drivers/acr122_usb.h @@ -2,6 +2,7 @@ * Public platform independent Near Field Communication (NFC) library * * Copyright (C) 2009, Roel Verdult + * Copyright (C) 2011, Romain Tartière * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the @@ -17,23 +18,23 @@ * along with this program. If not, see * * - * @file acr122.h - * @brief Driver for ACR122 devices + * @file acr122_usb.h + * @brief Driver for ACR122 devices using direct USB connection (without PCSC) */ -#ifndef __NFC_DRIVER_ACR122_H__ -# define __NFC_DRIVER_ACR122_H__ +#ifndef __NFC_DRIVER_ACR122_USB_H__ +# define __NFC_DRIVER_ACR122_USB_H__ + +# include # include -bool acr122_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound); +bool acr122_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t *pszDeviceFound); +nfc_device *acr122_usb_connect (const nfc_connstring connstring); +int acr122_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); +int acr122_usb_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout); +void acr122_usb_disconnect (nfc_device *pnd); -// Functions used by developer to handle connection to this device -nfc_device *acr122_open (const nfc_connstring connstring); -int acr122_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); -int acr122_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout); -void acr122_close (nfc_device *pnd); +extern const struct nfc_driver acr122_usb_driver; -extern const struct nfc_driver acr122_driver; - -#endif // ! __NFC_DRIVER_ACR122_H__ +#endif // ! __NFC_DRIVER_ACR122_USB_H__ diff --git a/libnfc/nfc.c b/libnfc/nfc.c index 5105672..7d3f7e0 100644 --- a/libnfc/nfc.c +++ b/libnfc/nfc.c @@ -50,11 +50,8 @@ const struct nfc_driver *nfc_drivers[] = { &pn53x_usb_driver, # endif /* DRIVER_PN53X_USB_ENABLED */ # if defined (DRIVER_ACR122_ENABLED) - &acr122_driver, + &acr122_usb_driver, # endif /* DRIVER_ACR122_ENABLED */ -# if defined (DRIVER_ACR122S_ENABLED) - &acr122s_driver, -# endif /* DRIVER_ACR122S_ENABLED */ # if defined (DRIVER_PN532_UART_ENABLED) &pn532_uart_driver, # endif /* DRIVER_PN532_UART_ENABLED */ diff --git a/m4/libnfc_drivers.m4 b/m4/libnfc_drivers.m4 index fb49f6c..8f635f4 100644 --- a/m4/libnfc_drivers.m4 +++ b/m4/libnfc_drivers.m4 @@ -35,7 +35,6 @@ AC_DEFUN([LIBNFC_ARG_WITH_DRIVERS], DRIVERS_CFLAGS="" driver_acr122_enabled="no" - driver_acr122s_enabled="no" driver_pn53x_usb_enabled="no" driver_arygon_enabled="no" driver_pn532_uart_enabled="no" @@ -44,7 +43,7 @@ AC_DEFUN([LIBNFC_ARG_WITH_DRIVERS], do case "${driver}" in acr122) - pcsc_required="yes" + libusb_required="yes" driver_acr122_enabled="yes" DRIVERS_CFLAGS="$DRIVERS_CFLAGS -DDRIVER_ACR122_ENABLED" ;; From 24e298626a73f6ca4ac4a7de672fabb1fad98e8f Mon Sep 17 00:00:00 2001 From: Romuald Conty Date: Thu, 26 Jan 2012 21:36:08 +0000 Subject: [PATCH 2/3] libnfc-1.5-acr122-usb> fix minor bugs and apply pn53x_usb's patch to be used under FreeBSD too --- debian/rules | 4 +- libnfc/drivers/acr122_usb.c | 164 +++++++++++++++++------------------- libnfc/drivers/pn53x_usb.c | 6 +- utils/nfc-probe.c | 12 ++- 4 files changed, 90 insertions(+), 96 deletions(-) diff --git a/debian/rules b/debian/rules index 8ce4fd0..3acfff6 100755 --- a/debian/rules +++ b/debian/rules @@ -18,8 +18,8 @@ override_dh_installchangelogs: override_dh_auto_configure: # dh_auto_configure -- --enable-serial-autoprobe # dh_auto_configure -- --enable-debug --with-drivers=all --enable-serial-autoprobe -# dh_auto_configure -- --enable-debug --with-drivers=acr122 --enable-serial-autoprobe - dh_auto_configure -- --enable-debug --with-drivers=pn532_uart,pn53x_usb --enable-serial-autoprobe + dh_auto_configure -- --enable-debug --with-drivers=acr122 +# dh_auto_configure -- --enable-debug --with-drivers=pn532_uart,pn53x_usb --enable-serial-autoprobe %: dh --with autoreconf $@ diff --git a/libnfc/drivers/acr122_usb.c b/libnfc/drivers/acr122_usb.c index 97452cb..82a51b8 100644 --- a/libnfc/drivers/acr122_usb.c +++ b/libnfc/drivers/acr122_usb.c @@ -59,7 +59,7 @@ Thanks to d18c7db and Okko for example code #include "chips/pn53x-internal.h" #include "drivers/acr122_usb.h" -#define PN53X_USB_DRIVER_NAME "acr122_usb" +#define ACR122_USB_DRIVER_NAME "acr122_usb" #define LOG_CATEGORY "libnfc.driver.acr122_usb" #define USB_INFINITE_TIMEOUT 0 @@ -92,8 +92,12 @@ acr122_usb_bulk_read (struct acr122_usb_data *data, uint8_t abtRx[], const size_ if (res > 0) { LOG_HEX ("RX", abtRx, res); } else if (res < 0) { - if (res != -USB_TIMEDOUT) + if (res != -USB_TIMEDOUT) { + res = NFC_EIO; log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror (res)); + } else { + res = NFC_ETIMEOUT; + } } return res; } @@ -108,8 +112,13 @@ acr122_usb_bulk_write (struct acr122_usb_data *data, uint8_t abtTx[], const size if ((res % data->uiMaxPacketSize) == 0) { usb_bulk_write (data->pudh, data->uiEndPointOut, "\0", 0, timeout); } - } else { + } else if (res < 0) { log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror (res)); + if (res == -USB_TIMEDOUT) { + res = NFC_ETIMEOUT; + } else { + res = NFC_EIO; + } } return res; } @@ -227,7 +236,7 @@ acr122_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t * // acr122_usb_get_usb_device_name (dev, udev, pnddDevices[*pszDeviceFound].acDevice, sizeof (pnddDevices[*pszDeviceFound].acDevice)); log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "device found: Bus %s Device %s", bus->dirname, dev->filename); usb_close (udev); - snprintf (connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s:%s", PN53X_USB_DRIVER_NAME, bus->dirname, dev->filename); + snprintf (connstrings[*pszDeviceFound], sizeof(nfc_connstring), "%s:%s:%s", ACR122_USB_DRIVER_NAME, bus->dirname, dev->filename); (*pszDeviceFound)++; // Test if we reach the maximum "wanted" devices if ((*pszDeviceFound) == connstrings_len) { @@ -242,61 +251,35 @@ acr122_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t * } struct acr122_usb_descriptor { - uint16_t bus; - uint16_t dev; + char *dirname; + char *filename; }; int acr122_usb_connstring_decode (const nfc_connstring connstring, struct acr122_usb_descriptor *desc) { - char *cs = malloc (strlen (connstring) + 1); - if (!cs) { - perror ("malloc"); - return -1; - } - strcpy (cs, connstring); - const char *driver_name = strtok (cs, ":"); - if (!driver_name) { - // Parse error - free (cs); - return -1; - } + int n = strlen (connstring) + 1; + char *driver_name = malloc (n); + char *dirname = malloc (n); + char *filename = malloc (n); - if (0 != strcmp (driver_name, PN53X_USB_DRIVER_NAME)) { + driver_name[0] = '\0'; + + int res = sscanf (connstring, "%[^:]:%[^:]:%[^:]", driver_name, dirname, filename); + + if (!res || (0 != strcmp (driver_name, ACR122_USB_DRIVER_NAME))) { // Driver name does not match. - free (cs); - return 0; + res = 0; + } else { + desc->dirname = strdup (dirname); + desc->filename = strdup (filename); } - const char *bus_s = strtok (NULL, ":"); - if (!bus_s) { - // bus not specified (or parsing error) - free (cs); - return 1; - } - unsigned int bus; - if (sscanf (bus_s, "%u", &bus) != 1) { - // bus_s is not a number - free (cs); - return 1; - } - desc->bus = bus; + free (driver_name); + free (dirname); + free (filename); - const char *dev_s = strtok (NULL, ":"); - if (!dev_s) { - // dev not specified (or parsing error) - free (cs); - return 2; - } - unsigned int dev; - if (sscanf (dev_s, "%u", &dev) != 1) { - // dev_s is not a number - free (cs); - return 2; - } - desc->dev = dev; - free (cs); - return 3; + return res; } bool @@ -329,14 +312,14 @@ acr122_usb_get_usb_device_name (struct usb_device *dev, usb_dev_handle *udev, ch nfc_device * acr122_usb_open (const nfc_connstring connstring) { - struct acr122_usb_descriptor desc; + nfc_device *pnd = NULL; + struct acr122_usb_descriptor desc = { NULL, NULL }; int connstring_decode_level = acr122_usb_connstring_decode (connstring, &desc); - log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); + log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); if (connstring_decode_level < 1) { - return NULL; + goto free_mem; } - nfc_device *pnd = NULL; struct acr122_usb_data data = { .pudh = NULL, .uiEndPointIn = 0, @@ -347,20 +330,32 @@ acr122_usb_open (const nfc_connstring connstring) usb_init (); + int res; + // usb_find_busses will find all of the busses on the system. Returns the + // number of changes since previous call to this function (total of new + // busses and busses removed). + if ((res = usb_find_busses () < 0)) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror (res)); + goto free_mem; + } + // usb_find_devices will find all of the devices on each bus. This should be + // called after usb_find_busses. Returns the number of changes since the + // previous call to this function (total of new device and devices removed). + if ((res = usb_find_devices () < 0)) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror (res)); + goto free_mem; + } + for (bus = usb_get_busses (); bus; bus = bus->next) { if (connstring_decode_level > 1) { // A specific bus have been specified - unsigned int bus_current; - sscanf (bus->dirname, "%u", &bus_current); - if (bus_current != desc.bus) + if (0 != strcmp (bus->dirname, desc.dirname)) continue; } for (dev = bus->devices; dev; dev = dev->next) { if (connstring_decode_level > 2) { // A specific dev have been specified - unsigned int dev_current; - sscanf (dev->filename, "%u", &dev_current); - if (dev_current != desc.dev) + if (0 != strcmp (dev->filename, desc.filename)) continue; } // Open the USB device @@ -376,7 +371,7 @@ acr122_usb_open (const nfc_connstring connstring) } usb_close (data.pudh); // we failed to use the specified device - return NULL; + goto free_mem; } res = usb_claim_interface (data.pudh, 0); @@ -384,7 +379,7 @@ acr122_usb_open (const nfc_connstring connstring) log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror (res)); usb_close (data.pudh); // we failed to use the specified device - return NULL; + goto free_mem; } data.model = acr122_usb_get_device_model (dev->descriptor.idVendor, dev->descriptor.idProduct); // Allocate memory for the device info and specification, fill it and return the info @@ -420,16 +415,20 @@ acr122_usb_open (const nfc_connstring connstring) goto error; } DRIVER_DATA (pnd)->abort_flag = false; - return pnd; + goto free_mem; } } // We ran out of devices before the index required - return NULL; + goto free_mem; error: // Free allocated structure on error. nfc_device_free (pnd); - return NULL; + pnd = NULL; +free_mem: + free (desc.dirname); + free (desc.filename); + return pnd; } void @@ -451,29 +450,27 @@ acr122_usb_close (nfc_device *pnd) nfc_device_free (pnd); } -#define PN53X_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) +#define ACR122_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) int acr122_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout) { - uint8_t abtFrame[PN53X_USB_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" + uint8_t abtFrame[ACR122_USB_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" size_t szFrame = 0; pn53x_build_frame (abtFrame, &szFrame, pbtData, szData); - int res = acr122_usb_bulk_write (DRIVER_DATA (pnd), abtFrame, szFrame, timeout); - - if (res < 0) { - pnd->last_error = NFC_EIO; + int res; + if ((res = acr122_usb_bulk_write (DRIVER_DATA (pnd), abtFrame, szFrame, timeout)) < 0) { + pnd->last_error = res; return pnd->last_error; } - uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; - res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), timeout); - if (res < 0) { - pnd->last_error = NFC_EIO; + uint8_t abtRxBuf[ACR122_USB_BUFFER_LEN]; + if ((res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), timeout)) < 0) { // try to interrupt current device state acr122_usb_ack(pnd); + pnd->last_error = res; return pnd->last_error; } @@ -487,11 +484,10 @@ acr122_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, c // acr122_usb_receive()) will be able to retreive the correct response // packet. // FIXME Sony reader is also affected by this bug but NACK is not supported - int res = acr122_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *)pn53x_nack_frame, sizeof(pn53x_nack_frame), timeout); - if (res < 0) { - pnd->last_error = NFC_EIO; + if ((res = acr122_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *)pn53x_nack_frame, sizeof(pn53x_nack_frame), timeout)) < 0) { // try to interrupt current device state acr122_usb_ack(pnd); + pnd->last_error = res; return pnd->last_error; } } @@ -506,7 +502,7 @@ acr122_usb_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, c size_t len; off_t offset = 0; - uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; + uint8_t abtRxBuf[ACR122_USB_BUFFER_LEN]; int res; /* @@ -531,7 +527,7 @@ read: res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), usb_timeout); - if (res == -USB_TIMEDOUT) { + if (res == NFC_ETIMEOUT) { if (DRIVER_DATA (pnd)->abort_flag) { DRIVER_DATA (pnd)->abort_flag = false; acr122_usb_ack (pnd); @@ -543,9 +539,9 @@ read: } if (res < 0) { - pnd->last_error = NFC_EIO; // try to interrupt current device state acr122_usb_ack(pnd); + pnd->last_error = res; return pnd->last_error; } @@ -646,12 +642,6 @@ int acr122_usb_init (nfc_device *pnd) { int res = 0; - // Sometimes PN53x USB doesn't reply ACK one the first frame, so we need to send a dummy one... - const uint8_t abtCmd[] = { GetFirmwareVersion }; - pn53x_transceive (pnd, abtCmd, sizeof (abtCmd), NULL, 0, -1); - // ...and we don't care about error - pnd->last_error = 0; - if ((res = pn53x_init (pnd)) < 0) return res; @@ -671,7 +661,7 @@ const struct pn53x_io acr122_usb_io = { }; const struct nfc_driver acr122_usb_driver = { - .name = PN53X_USB_DRIVER_NAME, + .name = ACR122_USB_DRIVER_NAME, .probe = acr122_usb_probe, .open = acr122_usb_open, .close = acr122_usb_close, diff --git a/libnfc/drivers/pn53x_usb.c b/libnfc/drivers/pn53x_usb.c index 75f90fc..e3cd3f1 100644 --- a/libnfc/drivers/pn53x_usb.c +++ b/libnfc/drivers/pn53x_usb.c @@ -312,7 +312,7 @@ nfc_device * pn53x_usb_open (const nfc_connstring connstring) { nfc_device *pnd = NULL; - struct pn53x_usb_descriptor desc = { NULL, NULL } ; + struct pn53x_usb_descriptor desc = { NULL, NULL }; int connstring_decode_level = pn53x_usb_connstring_decode (connstring, &desc); log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); if (connstring_decode_level < 1) { @@ -479,9 +479,9 @@ pn53x_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, co uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; if ((res = pn53x_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), timeout)) < 0) { - pnd->last_error = res; // try to interrupt current device state pn53x_usb_ack(pnd); + pnd->last_error = res; return pnd->last_error; } @@ -550,9 +550,9 @@ read: } if (res < 0) { - pnd->last_error = res; // try to interrupt current device state pn53x_usb_ack(pnd); + pnd->last_error = res; return pnd->last_error; } diff --git a/utils/nfc-probe.c b/utils/nfc-probe.c index 9536398..71f69a5 100644 --- a/utils/nfc-probe.c +++ b/utils/nfc-probe.c @@ -97,19 +97,23 @@ main (int argc, const char *argv[]) nfc_connstring connstrings[MAX_DEVICE_COUNT]; size_t szDeviceFound = nfc_list_devices (NULL, connstrings, MAX_DEVICE_COUNT); + int res = EXIT_FAILURE; if (szDeviceFound == 0) { printf ("No NFC device found.\n"); + goto bye; } - printf ("%d NFC device(s) found:\n", szDeviceFound); + printf ("%d NFC device(s) found:\n", (int)szDeviceFound); for (i = 0; i < szDeviceFound; i++) { pnd = nfc_open (NULL, connstrings[i]); if (pnd != NULL) { printf ("- %s:\n %s\n", nfc_device_get_name (pnd), nfc_device_get_connstring (pnd)); + nfc_close (pnd); } - nfc_close (pnd); } - + res = EXIT_SUCCESS; + +bye: nfc_exit (NULL); - return 0; + return res; } From 70484509afe1475570fc9c7682a701928dd93a89 Mon Sep 17 00:00:00 2001 From: Romuald Conty Date: Fri, 27 Jan 2012 14:38:14 +0000 Subject: [PATCH 3/3] libnfc-1.5-acr122-usb> support for ACR122U only (not Touchatag) --- libnfc/drivers/acr122_usb.c | 168 ++++++++++++++---------------------- 1 file changed, 63 insertions(+), 105 deletions(-) diff --git a/libnfc/drivers/acr122_usb.c b/libnfc/drivers/acr122_usb.c index 82a51b8..b52177d 100644 --- a/libnfc/drivers/acr122_usb.c +++ b/libnfc/drivers/acr122_usb.c @@ -225,14 +225,6 @@ acr122_usb_probe (nfc_connstring connstrings[], size_t connstrings_len, size_t * usb_dev_handle *udev = usb_open (dev); // Set configuration - int res = usb_set_configuration (udev, 1); - if (res < 0) { - log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror (res)); - usb_close (udev); - // we failed to use the device - continue; - } - // acr122_usb_get_usb_device_name (dev, udev, pnddDevices[*pszDeviceFound].acDevice, sizeof (pnddDevices[*pszDeviceFound].acDevice)); log_put (LOG_CATEGORY, NFC_PRIORITY_TRACE, "device found: Bus %s Device %s", bus->dirname, dev->filename); usb_close (udev); @@ -360,20 +352,11 @@ acr122_usb_open (const nfc_connstring connstring) } // Open the USB device data.pudh = usb_open (dev); + // Reset device + usb_reset (data.pudh); // Retrieve end points acr122_usb_get_end_points (dev, &data); - // Set configuration - int res = usb_set_configuration (data.pudh, 1); - if (res < 0) { - log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror (res)); - if (EPERM == -res) { - log_put (LOG_CATEGORY, NFC_PRIORITY_WARN, "Please double check USB permissions for device %04x:%04x", dev->descriptor.idVendor, dev->descriptor.idProduct); - } - usb_close (data.pudh); - // we failed to use the specified device - goto free_mem; - } - + // Claim interface res = usb_claim_interface (data.pudh, 0); if (res < 0) { log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror (res)); @@ -381,6 +364,15 @@ acr122_usb_open (const nfc_connstring connstring) // we failed to use the specified device goto free_mem; } + + res = usb_set_altinterface (data.pudh, 0); + if (res < 0) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to set alternate setting on USB interface (%s)", _usb_strerror (res)); + usb_close (data.pudh); + // we failed to use the specified device + goto free_mem; + } + data.model = acr122_usb_get_device_model (dev->descriptor.idVendor, dev->descriptor.idProduct); // Allocate memory for the device info and specification, fill it and return the info pnd = nfc_device_new (connstring); @@ -451,47 +443,32 @@ acr122_usb_close (nfc_device *pnd) } #define ACR122_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) +size_t +acr122_build_frame (uint8_t *frame, const size_t frame_len, const uint8_t *data, const size_t data_len) +{ + frame[1] = data_len + 6; + frame[14] = data_len + 1; + memcpy (frame + 16, data, data_len); + return data_len + 16; +} int acr122_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout) { - uint8_t abtFrame[ACR122_USB_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" - size_t szFrame = 0; - - pn53x_build_frame (abtFrame, &szFrame, pbtData, szData); + uint8_t abtFrame[ACR122_USB_BUFFER_LEN] = { 0x6b, + 0x00, // len + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding + 0xff, 0x00, 0x00, 0x00, + 0x00, // pn532 command lenght + 0xd4, // direction + }; + size_t szFrame = acr122_build_frame (abtFrame, sizeof(abtFrame), pbtData, szData); int res; if ((res = acr122_usb_bulk_write (DRIVER_DATA (pnd), abtFrame, szFrame, timeout)) < 0) { pnd->last_error = res; return pnd->last_error; } - - uint8_t abtRxBuf[ACR122_USB_BUFFER_LEN]; - if ((res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), timeout)) < 0) { - // try to interrupt current device state - acr122_usb_ack(pnd); - pnd->last_error = res; - return pnd->last_error; - } - - if (pn53x_check_ack_frame (pnd, abtRxBuf, res) == 0) { - // The PN53x is running the sent command - } else { - // For some reasons (eg. send another command while a previous one is - // running), the PN533 sometimes directly replies the response packet - // instead of ACK frame, so we send a NACK frame to force PN533 to resend - // response packet. With this hack, the nextly executed function (ie. - // acr122_usb_receive()) will be able to retreive the correct response - // packet. - // FIXME Sony reader is also affected by this bug but NACK is not supported - if ((res = acr122_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *)pn53x_nack_frame, sizeof(pn53x_nack_frame), timeout)) < 0) { - // try to interrupt current device state - acr122_usb_ack(pnd); - pnd->last_error = res; - return pnd->last_error; - } - } - return NFC_SUCCESS; } @@ -499,7 +476,6 @@ acr122_usb_send (nfc_device *pnd, const uint8_t *pbtData, const size_t szData, c int acr122_usb_receive (nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout) { - size_t len; off_t offset = 0; uint8_t abtRxBuf[ACR122_USB_BUFFER_LEN]; @@ -545,45 +521,20 @@ read: return pnd->last_error; } - const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; - if (0 != (memcmp (abtRxBuf, pn53x_preamble, 3))) { - log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); + if (abtRxBuf[offset] != 0x83) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame header mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } - offset += 3; + offset++; - if ((0x01 == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { - // Error frame - log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Application level error detected"); + size_t len = abtRxBuf[offset++]; + if (len < 4) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Too small reply"); pnd->last_error = NFC_EIO; return pnd->last_error; - } else if ((0xff == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { - // Extended frame - offset += 2; - - // (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] (LEN) include TFI + (CC+1) - len = (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] - 2; - if (((abtRxBuf[offset] + abtRxBuf[offset + 1] + abtRxBuf[offset + 2]) % 256) != 0) { - // TODO: Retry - log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch"); - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - offset += 3; - } else { - // Normal frame - if (256 != (abtRxBuf[offset] + abtRxBuf[offset + 1])) { - // TODO: Retry - log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Length checksum mismatch"); - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - - // abtRxBuf[3] (LEN) include TFI + (CC+1) - len = abtRxBuf[offset] - 2; - offset += 2; } + len -= 4; if (len > szDataLen) { log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len); @@ -591,6 +542,14 @@ read: return pnd->last_error; } + const uint8_t acr122_preamble[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x81, 0x00 }; + if (0 != (memcmp (abtRxBuf + offset, acr122_preamble, sizeof(acr122_preamble)))) { + log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame preamble mismatch"); + pnd->last_error = NFC_EIO; + return pnd->last_error; + } + offset += sizeof(acr122_preamble); + // TFI + PD0 (CC+1) if (abtRxBuf[offset] != 0xD5) { log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "TFI Mismatch"); @@ -609,39 +568,38 @@ read: memcpy (pbtData, abtRxBuf + offset, len); offset += len; - uint8_t btDCS = (256 - 0xD5); - btDCS -= CHIP_DATA (pnd)->last_command + 1; - for (size_t szPos = 0; szPos < len; szPos++) { - btDCS -= pbtData[szPos]; - } - - if (btDCS != abtRxBuf[offset]) { - log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Data checksum mismatch"); - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - offset += 1; - - if (0x00 != abtRxBuf[offset]) { - log_put (LOG_CATEGORY, NFC_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); - pnd->last_error = NFC_EIO; - return pnd->last_error; - } - // The PN53x command is done and we successfully received the reply - pnd->last_error = 0; return len; } int acr122_usb_ack (nfc_device *pnd) { - return acr122_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *) pn53x_ack_frame, sizeof (pn53x_ack_frame), 1000); + return 0; + //return acr122_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *) pn53x_ack_frame, sizeof (pn53x_ack_frame), 1000); } int acr122_usb_init (nfc_device *pnd) { int res = 0; +/* + uint8_t frame[] = { 0x6B, + 0x07, + 0, 0, 0, 0, 0, 0, 0, 0, // padding + 0xFF, 0x00, 0x00, 0x00, 0x02, 0xD4, 0x02 // frame + }; + acr122_usb_bulk_write (DRIVER_DATA (pnd), frame, sizeof(frame), 300); + acr122_usb_bulk_read (DRIVER_DATA (pnd), frame, sizeof(frame), 0); +*/ + +/* + uint8_t frame[] = { 0x6B, + 5, // len + 0, 0, 0, 0, 0, 0, 0, 0, // padding + 0xFF, 0x00, 0x48, 0x00, 0x00 // frame + }; + acr122_usb_bulk_write (DRIVER_DATA (pnd), frame, sizeof(frame), 0); +*/ if ((res = pn53x_init (pnd)) < 0) return res;