revtel / react-native-nfc-manager

React Native NFC module for Android & iOS
MIT License
1.33k stars 317 forks source link

Mifare usage Examples #417

Closed vincenzodomina closed 2 years ago

vincenzodomina commented 3 years ago

Thanks for this great library!

For my use case there was missing some Mifare examples to get started.

This is what is working for me so far, hoping for contribution on more.

Possible README entry:

Advanced: Mifare Ultralight usage

Here's an example to read a Mifare Ultrlight tag:

import NfcManager, {NfcTech} from 'react-native-nfc-manager';

// Pre-step, call this before any NFC operations
async function initNfc() {
  await NfcManager.start();
}

async function readMifare() {
  try {
      // 0. Request Mifare technology
      let reqMifare = await NfcManager.requestTechnology(NfcTech.MifareUltralight);
      if (reqMifare !== 'MifareUltralight') {
          throw new Error('[NFC Read] [ERR] Mifare technology could not be requested');
      };

      // 1. Get NFC Tag information
      const nfcTag = await NfcManager.getTag()
      console.log('[NFC Read] [INFO] Tag: ', nfcTag);

      // 2. Read pages
      const pagesCount = 60;
      let mifarePages = [];
      const mifarePagesRead = await Promise.all([...Array(pagesCount).keys()].map(async (_, i) => {
          const pageOffset = i * 4; // 4 Pages are read at once, so offset should be in steps with length 4
          let pages = await NfcManager.mifareUltralightHandlerAndroid.mifareUltralightReadPages(pageOffset);
          mifarePages.push(pages);
          console.log(`[NFC Read] [INFO] Mifare Page: ${pageOffset}`, pages);
          //await _wait(500); // If Mifare Chip is to slow
      }));

      // 3. Success
      console.log('[NFC Read] [INFO] Success reading Mifare');

      // 4. Cleanup
      _cleanup();
  } catch (ex) {
      console.warn('[NFC Read] [ERR] Failed Reading Mifare: ', ex);
      _cleanup();
  }
};

function _cleanup() {
    NfcManager.cancelTechnologyRequest().catch(() => 0);
};

function _wait = (time) {
  return new Promise((res) => setTimeout(res, time));
};

Would you like pull requests for stuff like this?

whitedogg13 commented 3 years ago

@vincenzodomina Sure, it's awesome! Please fire a PR and I will be very happy to merge. BTW, If you're interested in involving more in this project, please send me an email: whitedogg13@gmail.com :)

vincenzodomina commented 2 years ago

441

gshoanganh commented 1 year ago

@vincenzodomina can't use it for mifare classic card.

vincenzodomina commented 1 year ago

@vincenzodomina can't use it for mifare classic card.

That is another Nfc technology, right?

w3blogfr commented 1 year ago

Hello @vincenzodomina , do you may have a write exemple? with authentication?