Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added examples on how to write or read NDEF messages using nfccard-tool #31

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ This library uses pscslite native bindings [pokusew/node-pcsclite](https://githu
- [Can I use this library in my angular-electron app?](#can-i-use-this-library-in-my-angular-electron-app)
- [Do I have to use Babel in my app too?](#do-i-have-to-use-babel-in-my-app-too)
- [How do I require/import this library?](#how-do-i-requireimport-this-library)
- [Can I read a NDEF formatted tag?](#can-i-read-a-ndef-formatted-tag)
- [How to read or write NDEF messages?](#how-to-read-or-write-ndef-messages)
- [Frequent errors](#frequent-errors)
- [TypeError: NFC is not a constructor](#typeerror-nfc-is-not-a-constructor)
- [Transaction failed error when using `CONNECT_MODE_DIRECT`](#transaction-failed-error-when-using-connect_mode_direct)
Expand Down Expand Up @@ -332,12 +332,21 @@ If you want to import uncompiled source and transpile it yourself (not recommend
import { NFC } from 'nfc-pcsc/src';
```

### Can I read a NDEF formatted tag?
### How to read or write NDEF messages?

**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](https://github.com/TapTrack/NdefJS).
**Yes, you can!** First install nfc-tools:

**Psst!** There is also an example ([ndef.js](/examples/ndef.js)), but it is not finished yet. Feel free to contribute.
```sh
npm install nfc-tools --save
somq marked this conversation as resolved.
Show resolved Hide resolved
```

Then run the example:

```sh
npm run example-ndef
```

Read the doc at https://github.com/somq/nfccard-tool#nfccard-tool

## Frequent errors

Expand Down
117 changes: 117 additions & 0 deletions examples/ndef.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,120 @@

import { NFC, TAG_ISO_14443_3, TAG_ISO_14443_4, KEY_TYPE_A, KEY_TYPE_B } from '../src/index';
import pretty from './pretty';

const nfcCard = require('nfccard-tool');


const nfc = new NFC();

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

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

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

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


/**
* Write a card
*/

try {

/**
* 1 - READ HEADER
* Read header: we need to verify if we have read and write permissions
* and if prepared message length can fit onto the tag.
*/
const cardHeader = await reader.read(0, 20);

const tag = nfcCard.parseInfo(cardHeader);

/**
* 2 - WRITE A NDEF MESSAGE AND ITS RECORDS
*/
const message = [
{ type: 'text', text: 'I\'m a text message', language: 'en' },
{ type: 'uri', uri: 'https://github.com/somq/nfccard-tool' },
{ type: 'aar', packageName: 'com.github.nfccardtool' },
]

// Prepare the buffer to write on the card
const rawDataToWrite = nfcCard.prepareBytesToWrite(message);

// Write the buffer on the card starting at block 4
const preparationWrite = await reader.write(4, rawDataToWrite.preparedData);

// Success !
if (preparationWrite) {
console.log('Data have been written successfully.')
}

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


/**
* Read a card
*/

try {

/**
* READ MESSAGE AND ITS RECORDS
*/

/**
* 1 - READ HEADER
* Read from block 0 to block 4 (20 bytes length) in order to parse tag information
*/
// Starts reading in block 0 until end of block 4
const cardHeader = await reader.read(0, 20);

const tag = nfcCard.parseInfo(cardHeader);
console.log('tag info:', JSON.stringify(tag));

/**
* 2 - Read the NDEF message and parse it if it's supposed there is one
*/

// There might be a NDEF message and we are able to read the tag
if(nfcCard.isFormatedAsNDEF() && nfcCard.hasReadPermissions() && nfcCard.hasNDEFMessage()) {

// Read the appropriate length to get the NDEF message as buffer
const NDEFRawMessage = await reader.read(4, nfcCard.getNDEFMessageLengthToRead()); // starts reading in block 0 until 6

// Parse the buffer as a NDEF raw message
const NDEFMessage = nfcCard.parseNDEF(NDEFRawMessage);

console.log('NDEFMessage:', NDEFMessage);

} else {
console.log('Could not parse anything from this tag: \n The tag is either empty, locked, has a wrong NDEF format or is unreadable.')
}

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

});

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);
});