Code Monkey home page Code Monkey logo

nfc-pcsc's Introduction

nfc-pcsc

npm build status nfc-pcsc channel on discord

Easy reading and writing NFC tags and cards in Node.js

Built-in support for auto-reading card UIDs and reading tags emulated with Android HCE.

NOTE: Reading tag UID and methods for writing and reading tag content depend on NFC reader commands support. It is tested to work with ACR122 USB reader but it should work with all PC/SC compliant devices.
When detecting tags does not work see Alternative usage.

This library uses pcsclite native bindings pokusew/node-pcsclite under the hood.

Psst! Problems upgrading to 0.6.0? Check out this migration note.

Content

Installation

Requirements: at least Node.js 8 or newer (see this FAQ for more info)

Note: This library can be used only in Node.js environments on Linux/UNIX, macOS and Windows. Read why here.

  1. Node Native Modules build tools

    Because this library (via pokusew/node-pcsclite under the hood) uses Node Native Modules (C++ Addons), which are automatically built (using node-gyp) when installing via npm or yarn, you need to have installed C/C++ compiler toolchain and some other tools depending on your OS.

    Please refer to the node-gyp > Installation for the list of required tools depending on your OS and steps how to install them.

  2. PC/SC API in your OS

    On macOS and Windows you don't have to install anything, pcsclite API is provided by the OS.

    On Linux/UNIX you'd probably need to install pcsclite library and daemon**.

    For example, in Debian/Ubuntu:

    apt-get install libpcsclite1 libpcsclite-dev

    To run any code you will also need to have installed the pcsc daemon:

    apt-get install pcscd
  3. Once you have all needed libraries, you can install nfc-pcsc using npm:

    npm install nfc-pcsc --save

    or using Yarn:

    yarn add nfc-pcsc

Flow of handling tags

When a NFC tag (card) is attached to the reader, the following is done:

  1. it tries to find out the standard of card (TAG_ISO_14443_3 or TAG_ISO_14443_4)

  2. it will connect to the card, so any other card specific commands could be sent

  3. handling of card

    • when autoProcessing is true (default value) it will handle card by the standard:

      TAG_ISO_14443_3 (MIFARE Ultralight, 1K ...): sends GET_DATA command to retrieve card UID
      TAG_ISO_14443_4 (e.g.: Android HCE): sends SELECT_APDU command to retrieve data by file

      then card event is fired, for which you can listen and then you can read or write data on the card
      see Basic usage how to do it

    • when autoProcessing is false (default value) it will only fire card event
      then you can send whatever commands you want using reader.transmit method
      see Alternative usage how to do it

  4. you can read data, write data and send other commands

Basic usage

Running examples locally

If you want see it in action, clone this repository, install dependencies with npm and run npm run example. Of course, instead of npm you can Yarn if you want. See scripts section of package.json for all available examples run commands.

git clone https://github.com/pokusew/nfc-pcsc.git
cd nfc-pcsc
npm install
npm run example

You can use this library in any Node.js 8+ environment (even in an Electron app).

// in ES6
import { NFC } from 'nfc-pcsc';

// without Babel in ES2015
const { NFC } = require('nfc-pcsc');

const nfc = new NFC(); // optionally you can pass logger

nfc.on('reader', reader => {

	console.log(`${reader.reader.name}  device attached`);

	// enable when you want to auto-process ISO 14443-4 tags (standard=TAG_ISO_14443_4)
	// when an ISO 14443-4 is detected, SELECT FILE command with the AID is issued
	// the response is available as card.data in the card event
	// see examples/basic.js line 17 for more info
	// reader.aid = 'F222222222';

	reader.on('card', card => {

		// card is object containing following data
		// [always] String type: TAG_ISO_14443_3 (standard nfc tags like MIFARE) or TAG_ISO_14443_4 (Android HCE and others)
		// [always] String standard: same as type
		// [only TAG_ISO_14443_3] String uid: tag uid
		// [only TAG_ISO_14443_4] Buffer data: raw data from select APDU response

		console.log(`${reader.reader.name}  card detected`, card);

	});

	reader.on('card.off', card => {
		console.log(`${reader.reader.name}  card removed`, card);
	});

	reader.on('error', err => {
		console.log(`${reader.reader.name}  an error occurred`, err);
	});

	reader.on('end', () => {
		console.log(`${reader.reader.name}  device removed`);
	});

});

nfc.on('error', err => {
	console.log('an error occurred', err);
});

Alternative usage

You can disable auto processing of tags and process them yourself. It may be useful when you are using other than ACR122 USB reader or non-standard tags.

// in ES6
import { NFC } from 'nfc-pcsc';

// without Babel in ES2015
const { NFC } = require('nfc-pcsc');

const nfc = new NFC(); // optionally you can pass logger

nfc.on('reader', reader => {

	// disable auto processing
	reader.autoProcessing = false;

	console.log(`${reader.reader.name}  device attached`);

	reader.on('card', card => {

		// card is object containing following data
		// String standard: TAG_ISO_14443_3 (standard nfc tags like MIFARE Ultralight) or TAG_ISO_14443_4 (Android HCE and others)
		// String type: same as standard
		// Buffer atr

		console.log(`${reader.reader.name}  card inserted`, card);

		// you can use reader.transmit to send commands and retrieve data
		// see https://github.com/pokusew/nfc-pcsc/blob/master/src/Reader.js#L291

	});
	
	reader.on('card.off', card => {	
		console.log(`${reader.reader.name}  card removed`, card);
	});

	reader.on('error', err => {
		console.log(`${reader.reader.name}  an error occurred`, err);
	});

	reader.on('end', () => {
		console.log(`${reader.reader.name}  device removed`);
	});

});

nfc.on('error', err => {
	console.log('an error occurred', err);
});

Reading and writing data

You can read from and write to numerous NFC tags including MIFARE Ultralight (tested), MIFARE Classic, MIFARE DESFire, ...

Actually, you can even read/write any possible non-standard NFC tag and card, via sending APDU commands according card's technical documentation via reader.transmit.

Here is a simple example showing reading and writing data to simple card without authenticating (e.g. MIFARE Ultralight):
See Basic usage how to set up reader or look here for full code

reader.on('card', async card => {

	console.log();
	console.log(`card detected`, card);

	// example reading 12 bytes assuming containing text in utf8
	try {

		// reader.read(blockNumber, length, blockSize = 4, packetSize = 16)
		const data = await reader.read(4, 12); // starts reading in block 4, continues to 5 and 6 in order to read 12 bytes
		console.log(`data read`, data);
		const payload = data.toString(); // utf8 is default encoding
		console.log(`data converted`, payload);

	} catch (err) {
		console.error(`error when reading data`, err);
	}

	// example write 12 bytes containing text in utf8
	try {

		const data = Buffer.allocUnsafe(12);
		data.fill(0);
		const text = (new Date()).toTimeString();
		data.write(text); // if text is longer than 12 bytes, it will be cut off
		// reader.write(blockNumber, data, blockSize = 4)
		await reader.write(4, data); // starts writing in block 4, continues to 5 and 6 in order to write 12 bytes
		console.log(`data written`);

	} catch (err) {
		console.error(`error when writing data`, err);
	}

});

More examples

๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ You can find more examples in examples folder, including:

  • read-write.js โ€“ detecting, reading and writing cards standard ISO/IEC 14443-3 cards (NTAG, MIFARE Ultralight, ...)
  • mifare-classic.js โ€“ authenticating, reading and writing MIFARE Classic cards
  • mifare-desfire.js โ€“ authenticating and accessing data on MIFARE DESFire cards
  • mifare-ultralight-ntag.js โ€“ an example implementation of Mifare Ultralight EV1 and NTAG specific commands
  • basic.js โ€“ reader events explanation
  • led.js โ€“ controlling LED and buzzer of ACR122U reader
  • uid-logger.js โ€“ logs uid when a card is detected

Feel free to open pull request, if you have any useful example, that you'd like to add.

FAQ

Migration from older versions to 0.6.0

There was a breaking change in 0.6.0, as the default export was removed (because of non-standard behaviour of ES6 modules in ES5 env (see #12 and v0.6.0 release changelog)).

You have to update all requires or imports of this library to the following (note the brackets around NFC):

// in ES6 environment
import { NFC } from 'nfc-pcsc';

// in ES2015 environment
const { NFC } = require('nfc-pcsc');

Can I use this library in my Electron app?

Yes, you can! It works well.

But please note, that this library uses Node Native Modules (underlying library pokusew/node-pcsclite which provides access to PC/SC API).

Read carefully Using Native Node Modules guide in Electron documentation to fully understand the problematic.

Note, that because of Node Native Modules, you must build your app on target platform (you must run Windows build on Windows machine, etc.).
You can use CI/CD server to build your app for certain platforms.
For Windows, I recommend you to use AppVeyor.
For macOS and Linux build, there are plenty of services to choose from, for example CircleCI, Travis CI CodeShip.

Can I use this library in my angular-electron app?

Yes, you can! But as this library uses Node Native Modules, you must change some config in package.json and webpack.config.js as described in this comment.

Do I have to use Babel in my app too?

No, you don't have to. This library works great in any Node.js 8+ environment (even in an Electron app).

Psst! Instead of using async/await (like in examples), you can use Promises.

reader
  .read(...)
  .then(data => ...)
  .catch(err => ...))

Babel is used under the hood to transpile features, that are not supported in Node.js 8 (for example ES6 modules โ€“ import/export, see .babelrc for list of used plugins). The transpiled code (in the dist folder) is then published into npm and when you install and require the library, the transpiled code is used, so you don't have to worry about anything.

Which Node.js versions are supported?

nfc-pcsc officially supports the following Node.js versions: 8.x, 9.x, 10.x, 11.x, 12.x, 13.x, 14.x, 16.x, 18.x, 20.x.

How do I require/import this library?

// in ES6 environment
import { NFC } from 'nfc-pcsc';

// in ES2015 environment
const { NFC } = require('nfc-pcsc');

If you want to import uncompiled source and transpile it yourself (not recommended), you can do it as follows:

import { NFC } from 'nfc-pcsc/src';

Can I read a NDEF formatted tag?

Yes, you can! You can read raw byte card data with reader.read method, and then you can parse it with any NDEF parser, e.g. TapTrack/NdefJS.

Psst! There is also an example (ndef.js), but it is not finished yet. Feel free to contribute.

Can I use this library in my React Native app?

Short answer: NO

Explanation: Mobile support is virtually impossible because nfc-pcsc uses Node Native Modules to access system PC/SC API (actually under the hood, the pcsclite native binding is implemented in @pokusew/pcsclite). So the Node.js runtime and PC/SC API are required for nfc-pcsc to run. That makes it possible to use it on the most of OS (Windows, macOS, Linux) directly in Node.js or in Electron.js and NW.js desktop apps.

Frequent errors

TypeError: NFC is not a constructor

No worry, just check that you import/require the library like this (note the brackets around NFC):

// in ES6 environment
import { NFC } from 'nfc-pcsc';

// in ES2015 environment
const { NFC } = require('nfc-pcsc');

Take a look at How do I require/import this library? section for more info.

Note, that const NFC = require('nfc-pcsc'); or import NFC from 'nfc-pcsc' (NFC without brackets) won't work, because there is no default export.
It was removed for non-standard behaviour of ES6 modules in ES5 env (see #12 and v0.6.0 release changelog)

Transaction failed error when using CONNECT_MODE_DIRECT

No worry, just needs a proper configuration, see explanation and instructions here.

MIFARE Classic: Authentication Error after Multiple Writes

No worry, you have probably modified a sector trailer instead of a data block, see explanation and instructions here.

Reading data from a type 4 tags inside a Elsys.se sensors

According to @martijnthe's findings, it seems to be necessary to change the CLASS of READ BINARY APDU command from the default value of 0xFF to 0x00 in order to make a successful read.

If you experience the same problems, you can try setting the fourth argument (readClass) of the reader.read(blockNumber, length, blockSize, packetSize, readClass) method to value 0x00.

Relevant conversation: #55 (comment)

License

MIT

nfc-pcsc's People

Contributors

amilajack avatar andresbono avatar foxxyz avatar johnmclear avatar martijnthe avatar matyulabz avatar pokusew avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nfc-pcsc's Issues

Problem with angular-electron?

Hello, I've got empty angular-electron app and wanted to add NFC to it. The problem is that when I copy the first example to HomeComponent I can't compile it.

ERROR in vendor.bundle.js from UglifyJs Unexpected token: name (ACR122Reader)
error comes out, any ideas?

Additionally this happens whenI try to run in dev mode.
I'm using the newest electron and nodejs.

Can not make it run with electron

Hello,

thanks for this great package! I already developed some business logic an am able to access my cards via nodejs. Thats fun, unfortunately i can not make it run with electron. Can you please tell me what versions of electron and nfc-pcsc are compatible? I rebuilt the modules like explained but i always get the same kind of error:

Error: The module '.../node_modules/@pokusew/pcsclite/build/Release/pcsclite.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 51. This version of Node.js requires
NODE_MODULE_VERSION 53. Please try re-compiling or re-installing

I am simply too stupid to figure it out :-(

changing nodejs version does not help since electron seems to use its own node version.

thanks in advance

Unexpected token when running example

Hi,

Im having problem with the sample code.
Im using node v11

C:\Program Files\nodejs\node.exe --inspect-brk=31374 nfc-pcsc\examples\basic.js
Debugger listening on ws://127.0.0.1:31374/44f7c3dd-ad54-42e3-90ad-014997bf8ae2
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
c:\Users\emond\Desktop\nfc\nfc-pcsc\examples\basic.js:8
import { NFC } from "../src/index.js";
^

SyntaxError: Unexpected token {
at new Script (vm.js:80:7)
at createScript (vm.js:264:10)
at Object.runInThisContext (vm.js:316:10)
at Module._compile (internal/modules/cjs/loader.js:670:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:760:12)
at startup (internal/bootstrap/node.js:308:19)
Waiting for the debugger to disconnect...
SyntaxError: Unexpected token {
vm.js:80
at new Script (vm.js:80:7)
at createScript (vm.js:264:10)
at Object.runInThisContext (vm.js:316:10)

Error when trying to authenticate

Hi,
I got this error:

err:
  name:     AuthenticationError
  code:     unable_to_load_key
  previous:
    name:     LoadAuthenticationKeyError
    code:     null
    previous:
      name:     TransmitError
      code:     failure
      previous:

I use this Gist from yours, and replace the keyType to TAG_ISO_14443_3, since I'm using Mifare card.

I'm new to this, how can I know the correct Key to use? Any ideas/suggestions are highly appreciated.

Let me know if you need anything from my end. Thanks!

Recovering from Error

I'm trying to write some methods that are checking if a card (in my case NTAG-21x) needs authentication or not.

So far what I'm doing is reading 4 Bytes from Page 4 and if it fails, it means that I need to authenticate.

The problem occurs that the error thrown during that reading failure is preventing me from doing anything meaningful until I disconnect and reconnect the card.

Here some code:

try {
	let data = await this.reader.read(4, 4);
	return true;
} catch (err) {
	console.log("Cannot read, so we must authenticate!");
}

try {
	// if first try block is commented out, this block here works just fine!!!
	console.log("This fails, even though this area is not password protected");
	let data2 = await this.reader.read(0, 4);
} catch (err) {
	console.log("I will always be thrown, no matter what... WHY?", err);
}

Errors looks somewhat like this:

first try/catch:

ERR-0: { ReadError: Read operation failed: Status code: 0x6300
at /home/yoga/node/backend/node_modules/nfc-pcsc/dist/Reader.js:503:11
at Generator.next (<anonymous>)
at step (/home/yoga/node/backend/node_modules/nfc-pcsc/dist/Reader.js:18:191)
at /home/yoga/node/backend/node_modules/nfc-pcsc/dist/Reader.js:18:361
at <anonymous> name: 'ReadError', code: 'operation_failed' }

second try/catch:

ERR-1: { ReadError: Read operation failed: Status code: 0x6300
at /home/yoga/node/backend/node_modules/nfc-pcsc/dist/Reader.js:503:11
at Generator.next (<anonymous>)
at step (/home/yoga/node/backend/node_modules/nfc-pcsc/dist/Reader.js:18:191)
at /home/yoga/node/backend/node_modules/nfc-pcsc/dist/Reader.js:18:361
at <anonymous> name: 'ReadError', code: 'operation_failed' }

Is there a way to reset the state without disconnecting the card?
... or is my authentication approach simply inefficient?

Error while transmitting: Card was reset

I often get a WriteError but can't really find a workaround for this. I also have no clue what the error message even means. Does someone have a clue how I can solve this?

{ WriteError: An error occurred while transmitting.
    at /Users/sam/Projects/playground/usb/node_modules/nfc-pcsc/dist/Reader.js:573:11
    at throw (native)
    at step (/Users/sam/Projects/playground/usb/node_modules/nfc-pcsc/dist/Reader.js:16:191)
    at /Users/sam/Projects/playground/usb/node_modules/nfc-pcsc/dist/Reader.js:16:402
  name: 'WriteError',
  code: null,
  previous:
   { TransmitError: An error occurred while transmitting.
       at reader.transmit (/Users/sam/Projects/playground/usb/node_modules/nfc-pcsc/dist/Reader.js:271:20)
     name: 'TransmitError',
     code: 'failure',
     previous:
      Error: SCardTransmit error: Card was reset.(0x80100068)
          at Error (native) } }

Windows packaging error

I recently made an electron project with a sample code as mentioned below...

`
//============================= nfc begin============================
// 'use strict';

      var _nfcPcsc = require('nfc-pcsc');

      var _nfcPcsc2 = _interopRequireDefault(_nfcPcsc);

      function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

      var nfc = new _nfcPcsc2.default();

      // var mod=require('nfc-pcsc');
      // var nfc=new mod.NFC();
       
      nfc.on('reader', reader => {
       
          // console.log(`${reader.reader.name}  device attached`);
       
          // needed for reading tags emulated with Android HCE 
          // custom AID, change according to your Android for tag emulation 
          // see https://developer.android.com/guide/topics/connectivity/nfc/hce.html 
          reader.aid = 'F222222222';
       
          reader.on('card', card => {
              console.log("==================================================");
              var cardid=card.uid;
              console.log(cardid);
              
              mainWindow.loadURL('http://localhost/AA-EMR/interface/main/card_dashboard.php?card_id='+cardid);
       
          });
       
          reader.on('error', err => {
              console.log(`${reader.reader.name}  an error occurred`, err);
          });
       
          reader.on('end', () => {
              console.log(`${reader.reader.name}  device removed`);
          });
       
      });
       
      nfc.on('error', err => {
          console.log('an error occurred', err);
      });  
      //============================= nfc end============================`

Packaging the project for liniux seems to be okay but when I package it for windows, I get the following error...

Error X A JavaScript error occurred in the main process Uncaught Exception: Error: %1 is not a valid Win32 application. MCAUsers \ Dell \ Desktop \ DMS_Releasa\ DMS-win32-x64 resourca\ app\ nod..Apcsclite.node at Error (native) at process.module.(anonymous function) [as dlopen] (ELECTRON_ASARjs:173:20) at Object.Moduleโ€žectensions..node (modulejs:583:18) at Object.module.(anonymous function) [as .node] (ELECTRON_ASARjs:173:20) at Module.load (modulejs:473:32) at tryModuleLoad (modulejs:432:12) at Function.Module,load (modulejs:424:3) at Module.require (modulejs:483:17) at require (internaVmodulejs:20:19) at bindings (C: \ Users\ Dell \ Desktop\ DMS_Releases\ DMS-win32-x64\resources\app modules\bi...:44)

Any help would be really helpful..
Thank You
Hari

Native building issue using Electron

Hi,

I am attempting to build an electron app using NFC-PCSC lib.
There is an issue when rebuilding the library using electron-rebuild :

gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | win32 | x64
gyp info spawn C:\Users\yciurlik.windows-build-tools\python27\python.exe
gyp info spawn args [ 'C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\gyp\gyp_main.py',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'msvs',
gyp info spawn args '-G',
gyp info spawn args 'msvs_version=2015',
gyp info spawn args '-I',
gyp info spawn args 'C:\Users\yciurlik\Documents\PROJETS_CAP\DCX\AVV\16 - Chanel Refull\poc\node_modules\@pokusew\pcsclite\build\config.gypi',
gyp info spawn args '-I',
gyp info spawn args 'C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\addon.gypi',
gyp info spawn args '-I',
gyp info spawn args 'C:\Users\yciurlik\.electron-gyp\iojs-1.8.3\common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=C:\Users\yciurlik\.electron-gyp\iojs-1.8.3',
gyp info spawn args '-Dnode_gyp_dir=C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp',
gyp info spawn args '-Dnode_lib_file=C:\Users\yciurlik\.electron-gyp\iojs-1.8.3\<(target_arch)\iojs.lib',
gyp info spawn args '-Dmodule_root_dir=C:\Users\yciurlik\Documents\PROJETS_CAP\DCX\AVV\16 - Chanel Refull\poc\node_modules\@pokusew\pcsclite',
gyp info spawn args '-Dnode_engine=v8',
gyp info spawn args '--depth=.',
gyp info spawn args '--no-parallel',
gyp info spawn args '--generator-output',
gyp info spawn args 'C:\Users\yciurlik\Documents\PROJETS_CAP\DCX\AVV\16 - Chanel Refull\poc\node_modules\@pokusew\pcsclite\build',
gyp info spawn args '-Goutput_dir=.' ]
gyp info spawn C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe
gyp info spawn args [ 'build/binding.sln',
gyp info spawn args '/clp:Verbosity=minimal',
gyp info spawn args '/nologo',
gyp info spawn args '/p:Configuration=Release;Platform=x64' ]
gyp ERR! build error
gyp ERR! stack Error: C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:258:23)
gyp ERR! stack at emitTwo (events.js:126:13)
gyp ERR! stack at ChildProcess.emit (events.js:214:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\yciurlik\Documents\PROJETS_CAP\DCX\AVV\16 - Chanel Refull\poc\node_modules@pokusew\pcsclite
gyp ERR! node -v v8.9.1
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
error An unexpected error occurred: "Command failed.
Exit code: 1

Version:

  • Node : 8.9.1
  • NPM : 5.7.1
  • Yarn : 1.5.1
  • electron : 1.8.3
  • electron-builder : 20.4.1
  • nfc-pcsc : 0.6.1

You'll find the full log attached.
Thanks a lot for your help.

Write NDEF record

Hi,
First thanks for this library!
I cannot manage to write an NDEF record to a card. I believe it should be possible...
Here is what I tried:

const { NFC } = require('nfc-pcsc');
const nfc = new NFC();
const ndef = require('@taptrack/ndef');

nfc.on('reader', reader => {
  reader.aid = 'F222222222';

  reader.on('card', async card => {
    try {
      var textRecord = ndef.Utils.createUriRecord("http://www.exemple.com");
      var message = new ndef.Message([textRecord]);
      var bytes = message.toByteArray();

      await reader.write(4, bytes);
    } catch (err) {
      console.error(`error while writing data`, err);
    }
  });
});

Which gave me this error:

error while writing data TypeError: "list" argument must be an Array of Buffers
    at Function.Buffer.concat (buffer.js:332:13)
    at /home/pi/node_modules/nfc-pcsc/dist/Reader.js:562:26
    at Generator.next (<anonymous>)
    at step (/home/pi/node_modules/nfc-pcsc/dist/Reader.js:18:191)
    at /home/pi/node_modules/nfc-pcsc/dist/Reader.js:18:437
    at /home/pi/node_modules/nfc-pcsc/dist/Reader.js:18:99
    at Reader.write (/home/pi/node_modules/nfc-pcsc/dist/Reader.js:583:5)
    at /home/pi/node_modules/nfc-pcsc/dist/Reader.js:546:27
    at Generator.next (<anonymous>)
    at step (/home/pi/node_modules/nfc-pcsc/dist/Reader.js:18:191)

Am I missing something?

DESFire Example Error

Hey @pokusew,

I've noticed the DESFire example doesn't work with a Blank Card. Is there something I am missing? I am currently looking into this option instead of using Mifare Classic.

Thanks again!

C:\Users\User\Desktop\nfc-pcsc-master>npm run example-desfire

> [email protected] example-desfire C:\Users\User\Desktop\nfc-pcsc-master
> node -r babel-register examples/desfire.js

7:54:34 PM info ACS ACR122 0  device attached
7:54:40 PM info ACS ACR122 0  card detected
card:
  atr:
    0: 59
    1: 129
    2: 128
    3: 1
    4: 128
    5: 128
  standard: TAG_ISO_14443_4
[step 1 - select app] sending <Buffer 90 5a 00 00 03 00 00 00 00>
[step 1 - select app] received data <Buffer 91 00>
[step 2 - authenticate] sending <Buffer 90 0a 00 00 01 00 00>
[step 2 - authenticate] received data <Buffer 6b 58 43 85 e0 ad 5d 80 91 af>
[step 2 - set up RndA] sending <Buffer 90 af 00 00 10 d5 f5 58 dd 18 23 28 47 50 c0 b9 ec 75 ea 8d 6c 00>
[step 2 - set up RndA] received data <Buffer bd 52 c8 3c f3 59 ac eb 91 00>
[step 3 - read] sending <Buffer 90 bd 00 00 07 02 00 00 00 0e 00 00 00>
[step 3 - read] received data <Buffer 91 9d>
7:54:40 PM error ACS ACR122 0  error occurred during processing steps
Error: error in step 3 - read
    at C:/Users/User/Desktop/nfc-pcsc-master/examples/desfire.js:158:11
    at next (native)
    at step (C:\Users\User\Desktop\nfc-pcsc-master\examples\desfire.js:25:191)
    at C:\Users\User\Desktop\nfc-pcsc-master\examples\desfire.js:25:361

Read NDEF formatted cards

I can see you have an example started but not completed. Any updates on this?

I have a large numbers of cards all was URL stored on them and need to be able to read the data.

Won't write/read to card - tried to wipe using GoToTags

Hey there!

I recently found this library and have been trying to get the example to read/write to my card but it keeps erroring. The errors aren't really help as you can see:

> [email protected] example C:\Users\Omar\Documents\Programming\fullstack\nfc-pcsc
> node -r babel-register examples/index.js

08:56:42 info ACS ACR122 0  device attached
(node:2944) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
08:56:44 info ACS ACR122 0  card detected
card:
  atr:
    0:  59
    1:  143
    2:  128
    3:  1
    4:  128
    5:  79
    6:  12
    7:  160
    8:  0
    9:  0
    10: 3
    11: 6
    12: 3
    13: 0
    14: 1
    15: 0
    16: 0
    17: 0
    18: 0
    19: 106
  standard: TAG_ISO_14443_3
  type:     TAG_ISO_14443_3
  uid:      ca318459
08:56:44 error ACS ACR122 0  error when reading data
err:
  name: ReadError
  code: operation_failed
08:56:44 error ACS ACR122 0  error when writing data
err:
  name: WriteError
  code: operation_failed
08:56:53 error ACS ACR122 0  an error occurred
err:
08:56:53 info ACS ACR122 0  device removed
[ <1 empty item> ]
08:59:49 info ACS ACR122 0  device attached
08:59:59 info ACS ACR122 0  card detected
card:
  atr:
    0:  59
    1:  143
    2:  128
    3:  1
    4:  128
    5:  79
    6:  12
    7:  160
    8:  0
    9:  0
    10: 3
    11: 6
    12: 3
    13: 0
    14: 1
    15: 0
    16: 0
    17: 0
    18: 0
    19: 106
  standard: TAG_ISO_14443_3
  type:     TAG_ISO_14443_3
  uid:      ca318459
08:59:59 error ACS ACR122 0  error when reading data
err:
  name: ReadError
  code: operation_failed
08:59:59 error ACS ACR122 0  error when writing data
err:
  name: WriteError
  code: operation_failed

I did join your Discord but I have yet to see you on. Would appreciate some assistance.
Thanks!

MIFARE Ultralight C authentication

First of all, great work @pokusew, is amazing and super usefull having resources like yours. Thank you!

I'm on firts step on authentication of MIFARE Ultraligh C tags. Related to the doc I need to use a command to have the default tag key in return.
https://www.nxp.com/docs/en/data-sheet/MF0ICU2.pdf (page 15)

I'm using a block like that:

reader.on('card', async card => {
	console.log(`${reader.reader.name}  card ${card.uid} inserted`, card);
	try {
		const buffer = Buffer.from([0x1a, 0x00]);
		return resolve(await reader.transmit(buffer, 26));				
	} cache (err) {
                 console.log(err);
        };			
});

The main issue here is that always return a byteArray like that: Uint8Array(2) [99, 0]
instead of the expected 8 bytes string.
Maybe I am missing something but the following code: 0x1a, 0x00 is neccessary as first authentication step.

PD: Reader device: ACR1222L

Thank you all ;)

Write operation failed: Status code: 0x6300

A very simple program that just writes to a card:

const { NFC } = require('nfc-pcsc');
const nfc = new NFC();

nfc.on('reader', (reader) => {
	reader.on('card', async (card) => {
		try {
			const data = Buffer.allocUnsafe(16);
			data.fill(0);
			const randomNumber = Math.round(Math.random() * 1000);
			data.writeInt16BE(randomNumber);

			await reader.write(4, data);
		} catch (err) {
			console.error(err)
		}
	})
})

When a card is touched to the reader, the error occurs:

{ Error: Write operation failed: Status code: 0x6300
    at /.../node_modules/nfc-pcsc/dist/Reader.js:578:11
    at Generator.next (<anonymous>)
    at step (/.../node_modules/nfc-pcsc/dist/Reader.js:18:191)
    at /.../node_modules/nfc-pcsc/dist/Reader.js:18:361
    at <anonymous> name: 'WriteError', code: 'operation_failed' }

Before writing, I've tried adding:

await reader.authenticate(4, KEY_TYPE_A, 'ffffffffffff')

and

await reader.loadAuthenticationKey(0, 'ffffffffffff')
await reader.authenticate(4, KEY_TYPE_A, 'ffffffffffff')

without success.

What's causing this? Is this a bug?

I was getting the same status code at a lower level, as well.

Card events returned multiple times

Hi eveyone,

I have a simple local app angularjs app and that sends a request to my backend (nodejs) to read an nfc tag and get a response back.

this is my method handling the request:

`
var sent = false;

	nfc = new NFC();
	nfc.on('reader', reader => {
		reader.on('card', async card => {
			try {
				const textRecord = ndef.Utils.createTextRecord(card.uid);
				const message = new ndef.Message([textRecord]);
				const bytes = message.toByteArray();
				const data = encapsulate(Buffer.from(bytes.buffer));
				await reader.write(4, data); // starts writing in block 4, continues to 5 and 6 in order to 
				
				if (sent) {
					console.log("sent : ", sent);
					return;
				} else {
					sent = true;
					socketServer.emit('nfcScanned', {
						result: "success",
						data: card
					});
					console.log("SENDING RESPONSE ", sent);
					return res.json({
						// result: "success"
						result: "success",
						data: card
					});
				}
			} catch (err) {
				// if (sent) {
				// 	console.log("ALREADY SENT");
				// } else {
				// nfc = undefined;
				// socketServer.emit('nfcNotScanned', {
				// 	result: "failed",
				// 	error: err
				// });

				// // sent = true;
				// return res.json({
				// 	// result: "success"
				// 	result: "error",
				// 	data: card
				// });
				// }
			}
		});

		reader.on('card.off', card => {
			
		});

		reader.on('error', err => {
		
		});

		reader.on('end', () => {
			
		});


	});

	nfc.on('error', err => {
		console.error(err);
	});`

What happens is when i trigger this method call the first time, all is good and i get the uid back on the client. However, each subsequent call the client makes to scan a new tag and get the next uid, it returns the result multiple times (first req, 1 response; 2nd request 2 responses, n requests - n responses).

Regardless of whether i manage to reduce the number of events i emit back to the client (socket triggers multiple messages although the regular http response is only triggering once), the reader gets slower and slower to read/write tag and it gets sort of exponentially slower. any idea?

not working with angular 6 while importing

it is not working with angular 6 and it throwing error while importing like "nfc is not a constructor".

import {NFC} from 'nfc-pcsc' throwing error

ERROR in ./node_modules/bindings/bindings.js
Module not found: Error: Can't resolve 'fs' in 'C:\Users\Admin\Desktop\electronapp\node_modules\bindings'
ERROR in ./node_modules/bindings/bindings.js
Module not found: Error: Can't resolve 'path' in 'C:\Users\Admin\Desktop\electronapp\node_modules\bindings'

reason i found fs module will not work with angular 6. by inbuilt nfc containing fs .

because of these reason i accessed nfc from html and i declared in angular 6 component like "declare var NFC: any; "
because of above i am getting nfc is not a constructor

non-babel version

Do you have a non-babel version of this module? Node v7.10 has all the es2017 features I need, so I don't need to add the babel dependencies.

Or is the best/only way to clone and run your build then include your code that is put into the dist dir?

Detect attached card reader on app start

Hello @pokusew .
This is a great lib.

I'm using it on an Electron app with an ACS ACR1251 Dual Reader.

If I connect the reader after the app is started all is good, the reader is detected, but if the app starts and the reader is already connected to the PC, it does not register it.
Any help ?

Stop reader

Is there a way to stop the reader from listening? If I use reader.close(), the entire node.js process stops (on mac). reader.disconnect() doesn't work either. Reader keeps listening.

reader.on('card.off', card => {

            try {

              reader.emit('end');


          	} catch (err) {
          		console.error('error when reading data', err);
          	}
});

reader.on('end', () => {

          reader.close();
});

I basically want to have an interface with a button 'read NFC' and on click it needs to listen for nfc input, but once the card leaves and input is read, I want the nfc process killed. Help would be much appreciated.

Can not use ACS ACR1252 1S CL Reader

I am trying to run the example with npm run example. We are using ACR1252U USB NFC Reader, but when I do plug and tap in a card, the reader can't read with the following errors :

> [email protected] example .../belajar-electron/nfc-reader
> node -r babel-register examples/index.js

2:41:21 PM info ACS ACR1252 1S CL Reader(1)  device attached
2:41:21 PM info ACS ACR1252 1S CL Reader(2)  device attached
2:41:22 PM error ACS ACR1252 1S CL Reader(2)  an error occurred
err: 
2:43:51 PM info ACS ACR1252 1S CL Reader(1)  device removed
[ <1 empty item>,
  Reader {
    _events: { card: [Function], error: [Function], end: [Function] },
    _eventsCount: 3,
    _maxListeners: undefined,
    reader:
     CardReader {
       name: 'ACS ACR1252 1S CL Reader(2)',
       connected: true,
       _events: [Object],
       _eventsCount: 4,
       state: 6 },
    logger:
     { log: [Function: log],
       debug: [Function: debug],
       info: [Function: info],
       warn: [Function: warn],
       error: [Function: error] },
    connection: { type: 2, protocol: 2 },
    card:
     { atr:
        <Buffer 3b df 18 ff 81 f1 fe 43 00 3f 03 83 4d 49 46 41 52 45 20 50 6c 75 73 20 53 41 4d 3b>,
       standard: 'TAG_ISO_14443_4',
       type: 'TAG_ISO_14443_4' },
    autoProcessing: true,
    _aid: 'F222222222',
    _parsedAid: [ 242, 34, 34, 34, 34 ],
    keyStorage: { '0': null, '1': null },
    pendingLoadAuthenticationKey: {} } ]
2:43:51 PM info ACS ACR1252 1S CL Reader(2)  device removed
[ <2 empty items> ]
2:49:20 PM info ACS ACR1252 1S CL Reader(2)  device attached
2:49:21 PM error ACS ACR1252 1S CL Reader(2)  an error occurred
err: 
2:49:26 PM error ACS ACR1252 1S CL Reader(1)  an error occurred
err: 
  name:     GetUIDError
  code:     null
  previous: 
    name:     TransmitError
    code:     failure
    previous: 

Here is some logs when I attached the ARC12U NFC Reader :

2:52:47 PM info ACS ACR122U  device attached
2:52:58 PM error ACS ACR122U  an error occurred
err: 

I use node v10.14.0 and npm 6.4.1. Any clue or advice is appreciated. Thank you.

WriteError: Write operation failed: Status code: 0x6300

I'm trying to write in a Mifare 1k card empty with all keys to FFFFFFFFFFFF, I followed the examples and read some similar questions but I always end up with the same error.

My testing code is:

const { NFC } = require('nfc-pcsc');
const nfc = new NFC();
const KEY_TYPE_A = 0x60
const KEY_TYPE_B = 0x61
nfc.on('reader', (reader) => {
	reader.on('card', async (card) => {
		try {
			const data = Buffer.allocUnsafe(16);
			data.fill(0);
			const randomNumber = Math.round(Math.random() * 1000);
			data.writeInt16BE(randomNumber);

			await reader.authenticate(4, KEY_TYPE_A, 'ffffffffffff')
			await reader.authenticate(5, KEY_TYPE_A, 'ffffffffffff')
			await reader.authenticate(6, KEY_TYPE_A, 'ffffffffffff')
			await reader.write(4, data, 16);
		} catch (err) {
			console.error(err)
		}
	})
})

This is the error I'm getting:

{ WriteError: Write operation failed: Status code: 0x6300
    at /home/XXXXXX/node_modules/nfc-pcsc/dist/Reader.js:579:11
    at Generator.next (<anonymous>)
    at step (/home/XXXXXX/node_modules/nfc-pcsc/dist/Reader.js:18:191)
    at /home/XXXXXX/node_modules/nfc-pcsc/dist/Reader.js:18:361
    at <anonymous> name: 'WriteError', code: 'operation_failed' }

I'm using an empty card with the following content (with gen1 backdoor):

0102030404080400000000000000beaf
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
ffffffffffff08778f00ffffffffffff
00000000000000000000000000000000

Thanks

Fails to start using Electron 4 and npm on Windows

When starting demo using NPM and electron start script nfc-pcsc fails. Starting using only node everything works perfectly.

From log:
10 silly lifecycle [email protected]start: Args: [ '/d /s /c', 'electron .' ]
11 silly lifecycle [email protected]
start: Returned: code: 3228369023 signal: null
12 info lifecycle [email protected]~start: Failed to exec start script
13 verbose stack Error: [email protected] start: electron .
13 verbose stack Exit status 3228369023
13 verbose stack at EventEmitter. (C:\Users\mads\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack at EventEmitter.emit (events.js:182:13)
13 verbose stack at ChildProcess. (C:\Users\mads\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:182:13)
13 verbose stack at maybeClose (internal/child_process.js:962:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
14 verbose pkgid [email protected]
15 verbose cwd C:\Users\mads\Source\Repos\Re5.com\Electron.CardLoader
16 verbose Windows_NT 10.0.17134
17 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Users\mads\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "start"
18 verbose node v10.14.2
19 verbose npm v6.5.0
20 error code ELIFECYCLE
21 error errno 3228369023
22 error [email protected] start: electron .
22 error Exit status 3228369023
23 error Failed at the [email protected] start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 3228369023, true ]

Additional info:
This happens for all libs using santigimeno/node-pcsclite

Can't read in Android

Hello

After I run the most simple example of write on nfc tag (14443-3A Ultralight C), I'm able to read using the read example but not on Android app (like NFC Tools)
How can I fix it? I need to write on a desktop and read using Android (a thirdparty app).

Thanks!

NTAG 21x Authentication

Is there a way to password protect NTAG21X cards / Type TAG_ISO_14443_3 via ACR122U?

I was trying my luck with a previously posted thread about Mifare Ultralight cards, but I end up with 0x6300 errors.

Code:

try {
	// APDU CMD: Update Binary Block
	const packet = new Buffer([
		0xFF, // Class
		0x00,
		0x00,
		0x00,
		0x07, //Length
		0xD4, // inserted
		0x42, // inserted
		0x1B, //PWD_AUTH
		0x11, //my pass
		0x22, //my pass
		0x33, //my pass
		0x44 //my pass
	]);
	var pwdResponse = await reader.transmit(packet, 7);
	console.log('pwd response', pwdResponse);
} catch (err) {
	console.log('error pwd_auth');
}

This works, but any read or write attempt after, does not work anymore:

0|yogaman  | 2018/02/18 19:03:08: Error when reading data: { ReadError: Read operation failed: Status code: 0x6300
0|yogaman  |     at /home/node/backend/node_modules/nfc-pcsc/dist/Reader.js:503:11
0|yogaman  |     at Generator.next (<anonymous>)
0|yogaman  |     at step (/home/node/backend/node_modules/nfc-pcsc/dist/Reader.js:18:191)
0|yogaman  |     at /home/node/backend/node_modules/nfc-pcsc/dist/Reader.js:18:361
0|yogaman  |     at <anonymous> name: 'ReadError', code: 'operation_failed' }

Uncaught Error: DLL Initialization routine failed

I recently switched computers and re-installed node, electron, etc. Now I'm getting the following error when running my NFC application:

Uncaught Error: a dynamic link library (dll) initialization routine failed.
\?\C:\Users\Mike\desktop\pos\node_modules@pokusew\pcsclite\build\Release\pcsclite.node
at process.module.(anonymous function) [as dlopen] (ELECTRON_ASAR.js:166:20)
at Object.Module._extensions..node (internal/modules/cjs/loader.js:740)
at Object.module.(anonymous function) [as .node] (ELECTRON_ASAR.js:166:20)
at Module.load (internal/modules/cjs/loader.js:620)
at tryModuleLoad (internal/modules/cjs/loader.js:559)
at Function.Module._load (internal/modules/cjs/loader.js:551)
at Module.require (internal/modules/cjs/loader.js:658)
at require (internal/modules/cjs/helpers.js:20)
at bindings (C:\Users\Mike\desktop\pos\node_modules\bindings\bindings.js:81)
at Object. (C:\Users\Mike\desktop\pos\node_modules@pokusew\pcsclite\lib\pcsclite.js:4)

  • Electron version: 3.0.9
    Can someone help me?
    Thanks in advance!

Mike

"Failed to minify code" (create-react-app)

I'm trying to use this library together with resin.io's electron + react template, which uses create-react-app.

When I run the build script it fails telling me that this library (specifically dist/Reader.js) can't be minified and directs me to this link, which suggests filing an issue on the dependency in question, so here I am.

Native node modules + create-react-app + electron is asking for trouble, I know, but maybe you have some suggestions?

Is that possible add Feitian R502?

Hi Martin

Good to see this repo.

Is that possible support Feitian R502 reader? I can share our demo unit for evaluation, and our engineer also can support on this.

Thanks and looking forward your reply.

Mifare Classic 1K: Authentication Error after Multiple Writes

Hi @pokusew,

Something weird is happening when attempting multiple writes. I have the following simple script that (1) Authenticates Blocks 4-7, Reads Blocks 4-7 and then Writes to Blocks 4-7.

It seems that the cards become unusable after attempting multiple write operations as they refuse to Authenticate. I have also tried this using promises.

I really like this package due to its quality, straightforward installation across platforms and Electron support.

Any suggestions or advice from your side?

https://gist.github.com/therealri/96adfa625d8bb3b2929a956ec1919cda

1:53:04 AM info ACS ACR122 0  device attached
1:53:05 AM info ACS ACR122 0  card detected
card:
  type: TAG_ISO_14443_3
  uid:  4e62e3f5
1:53:05 AM error ACS ACR122 0  error when authenticating data
card:
  type: TAG_ISO_14443_3
  uid:  4e62e3f5
err:
  name: AuthenticationError
  code: operation_failed

Malformed SELECT FILE command?

Hi there, thanks for your library.

I'm having some trouble with an NXP NFC Tag type 4 tag (AID D2760000850101).
I inspected your code and compared it to another program that works correctly.

I noticed the code that sends the AID looks malformed:
https://github.com/pokusew/nfc-pcsc/blob/master/src/Reader.js#L736

According to this source, there should be an Lc field containing the length of the (AID) data, prior to the AID data. There's a field that has a comment Le but it's hard-coded to 5. Also, an empty / 00 byte (for the actual Le) seems to be missing.

What do you think?

When using Angular2/TypeScript: TypeError: exists is not a function

Hi,
I have an Angular CLI project running in Electron. When I follow your instructions and import the module like this import NFC from '../../../node_modules/nfc-pcsc';, and call const nfc = new NFC(minilogger);, then I get the following error in the console:

TypeError: exists is not a function

And during the build process

WARNING in ./~/bindings/bindings.js
76:22-40 Critical dependency: the request of a dependency is an expression

Require in non-babel env needs .default suffix

I am trying to create application using Electron. In the beginning I was getting problem with node Module versions that was expecting 51 but required 53. I installed Electron 1.5.1 and that error is fixed but now I am getting error that says:

TypeError: NFC is not a constructor

I just used your example and error is coming from this line:

const nfc = new NFC();

did I miss something or is it about node native modules ?

Thanks in advance

Emit a card 'off' event

First, thanks for writing this library!

I've got a use for it at the moment where it would be useful if the Reader would emit an event when the card is removed. Had a quick look and it'd be a very quick fix; if I submitted a PR would you be interested in merging it in?

Cheers :)

Ultralight EV1 password authentication

Hello,
Thanks a lot for this library!
I'm try write data to Mifare Ultralight EV1 card with password.
Before write, i'm try send pseudo-APDU command PWD_AUTH (0x1B) but response empty buffer and data write error.
How can i send authenticate command?
Pleas help.

Here is my code:

const { NFC } = require('nfc-pcsc');
const nfc = new NFC();

nfc.on('reader', reader => {

    console.log(`${ reader.reader.name } device attached`);

    reader.on('card', async card => {

        try {
            // APDU CMD: Update Binary Block
            const packet = new Buffer([
                0xFF, // Class				
                0x00,
                0x00,
                0x00,
                0x05, //Length
                0x1B, //PWD_AUTH
                0x11, //my pass
                0x22, //my pass
                0x33, //my pass
                0x44 //my pass
            ]);
            var pwdResponse = await reader.transmit(packet, 2);  
            console.log('pwd response', pwdResponse);
        } catch (err) {
            console.log('error pwd_auth');
        }
        
        try {
            const data = Buffer.allocUnsafe(12);
            data.fill(0);
            const text = (new Date()).toTimeString();
            data.write(text);      
            await reader.write(4, data); 

            console.log('data written');
           
        } catch (err) {
            console.error('error when writing data', err);
        }       
    });
});
ACS ACR122 0 device attached
pwd response <Buffer >
error when writing data { WriteError: Write operation failed: Status code: 0x6300
    at C:\Users\admin\Documents\acr122u\node_modules\nfc-pcsc\dist\Reader.js:579:11
    at Generator.next (<anonymous>)
    at step (C:\Users\admin\Documents\acr122u\node_modules\nfc-pcsc\dist\Reader.js:18:191)
    at C:\Users\admin\Documents\acr122u\node_modules\nfc-pcsc\dist\Reader.js:18:361
    at <anonymous> name: 'WriteError', code: 'operation_failed' }

Whats the license?

What is the OSS license for this project?

Thanks for you work on this by the way

Starting issue with electron

Hello. I'm developing a React+Electron app and I'm also using this library to read some bands with a nfc reader. The problem I have is that on some computers the app runs perfectly, but on the others, the app starts as a background process and it stays there with no error.
Any idea what can cause this to happen?
46721354-76bde400-cc7b-11e8-9e98-01bd1a694fe1
LE: If I remove the line this.nfc = new NFC();, the app starts normally on all computers. So it's something cause by the initialization.

Transmit example

Hey man, thanks for all the hard work on this project :)

I'm working on some logic which can get the SEID from an IC using an APDU. Pretty simple stuff I have working on other platforms (Cordova etc.) but I seem to struggling with this project. It's likely I'm a bit rusty as I haven't worked on it for a few years so apology if this is user error however I have read through the docs and do feel like the transmit method docs could do with some additional input (of which I will be happy to do once I am comfortable with the method).

The following:

nfc.on('reader', reader => {
  reader.autoProcessing = false; // Required else you won't get here..

  reader.on('card', async card => {

    // APDU Transmit logic
    console.log("card detected");
    const apdu = "80CA9F7F2C"; // Perhaps I should be providing this as hex array then converting to Buffer?
    var buf = Buffer.from(apdu, 'utf8'); // Maybe this should be hex?

    try{
      let uid = await reader.transmit(buf, 12); // Tried different buffer length values.
      console.log("UID", uid.toString('hex')); // UID / SEID value is wrong.  It should be 16 chars or so but we only get 4...
    }catch(err){
      console.log(err); // No error is thrown :)
    }
...

Returns:

...
card inserted <Buffer 3b 8e 80 01 80 31 80 66 b1 84 0c 01 6e 01 83 00 90 00 1c>
trying to connect CONNECT_MODE_CARD 2
connected { type: 2, protocol: 2 }
card detected
transmitting <Buffer 38 30 43 41 39 46 37 46 32 43> 12
UID 6e00
status { state: 4063250, atr: <Buffer > }
changes 196656
card removed
trying to disconnect { type: 2, protocol: 2 }
disconnected

The UID value should be much longer.

I'm 99% correct the APDU is correct.

I'm only making assumptions I'm doing transmit correctly.

I think the error lies in the format I'm encoding the APDU (from string to Buffer?)

Can't turn off buzzer

Hi,
First of all, thanks for this library. It's really easy to use and works perfectly for my project.

But I stumbled across a problem while using it in an electron app running on a raspberry pi 3.
I try to turn off the beep signal.

try {
  reader.connect('CONNECT_MODE_DIRECT').then(()=>{console.log('connected')
    reader.setBuzzerOutput(false).then(()=>{console.log('buzzer off')
    reader.disconnect().then(()=>{console.log('disconnected off')}).catch((err)=>{console.error('can\'t disconnect... reason', err)});
    }).catch((err)=>{console.error('can\'t turn off buzz', err)})
  }).catch((err)=>{console.error('can\'t connect', err)})
} catch (err) {
  console.error(err)
}

But I get this error message:

โ” Electron -------------------

  can't turn off buzz { Error: An error occurred while transmitting control.
      at reader.control (/home/pi/rfid-play/node_modules/nfc-pcsc/dist/Reader.js:296:20)
      at /home/pi/rfid-play/node_modules/@pokusew/pcsclite/lib/pcsclite.js:169:11
    name: 'ControlError',
    code: 'failure',
    previous: Error: SCardControl error: Transaction failed.(0x80100016) }
  
โ”— ----------------------------

Do you have an idea how to solve this issue? Or maybe you know a better way how to turn the beep sound off.

Thank you very much.
Philipp

Control Error in LED Example

Hey @pokusew,

Thanks for this great package!

I am getting this error when trying to run the led.js example on macOS 10.12.4:

*[master][~/Desktop/nfc-pcsc]$ node -r babel-register examples/led.js 
New reader detected ACS ACR122U
12:38:01 AM info ACS ACR122U  device attached
Setting AID to F222222222
AID parsed [ 242, 34, 34, 34, 34 ]

trying to connect CONNECT_MODE_DIRECT 3
status { state: 18, atr: <Buffer > }
changes 18
card removed
connected { type: 3, protocol: 3 }
<Buffer ff 00 52 00 00>
transmitting control <Buffer ff 00 52 00 00> 2
{ ControlError: An error occurred while transmitting control.
    at reader.control (/Users/risean/Desktop/nfc-pcsc/src/Reader.js:327:20)
    at /Users/risean/Desktop/nfc-pcsc/node_modules/@pokusew/pcsclite/lib/pcsclite.js:169:11
  name: 'ControlError',
  code: 'failure',
  previous: 
   Error: SCardControl error: Transaction failed.(0x80100016)
       at Error (native) }

Write to Mifare Classic 1K card in Electron App

Hi @pokusew,

Thanks for the great library, it has saved me a lot of time! I am currently working on a app that should write some data to a Mifare 1Kb card from within an Electron app.

Because Electron does not support async and await I'm having some trouble integrating the example as shown in the readme.

This is my current code:

reader.on('card', card => {

        // card is object containig folowing data
        // [always] String type: TAG_ISO_14443_3 (standard nfc tags like Mifare) or TAG_ISO_14443_4 (Android HCE and others)
        // [only TAG_ISO_14443_3] String uid: tag uid
        // [only TAG_ISO_14443_4] Buffer data: raw data from select APDU response

        console.log(`${reader.reader.name}  card detected`, card);

        try {
          
         const key = 'FFFFFFFFFFFF';
         const keyType = 0x61;
        
         // we will authenticate block 4, 5, 6, 7 (which we want to read)
         Promise.all([
             reader.authenticate(4, keyType, key),
             reader.authenticate(5, keyType, key),
             reader.authenticate(6, keyType, key),
             reader.authenticate(7, keyType, key)
         ]);
        
         console.log(`blocks successfully authenticated`);
        
        } catch (err) {
         console.error(`error when authenticating data`, { reader: reader.name, card, err });
         return;
        }
        
        // I added the TimeOut to work around the missing await support
        setTimeout(function() {

          // example write 16bit integer
        try {

              // reader.write(blockNumber, data, blockSize = 4)
              // - blockNumber - memory block number where to start writing
              // - data - what to write
              // ! Caution! data.length must be divisible by blockSize

              const data = Buffer.allocUnsafe(16);
              data.writeInt16BE(800);

              reader.write(4, data);

              console.log(`data written`, { reader: reader.name, card });

          } catch (err) {
              console.error(`error when writing data`, { reader: reader.name, card, err });
          }

        }, 4000);

        

    });

This however does not work, I alway get the blocks successfully authenticated message, but I think that this since i removed await the catch function never gets called. The error message that I receive is Uncaught (in promise) WriteError: Write operation failed: Status code: 0x6300. Please see the screenshot below for the full output (the Data and Object array that are logged are other functions from the program, separate from this issue):
schermafbeelding 2017-02-16 om 14 57 56

If you require any more information I would be happy to provide it!
Thanks in advance,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.