Git Product home page Git Product logo

react-native-hce's People

Contributors

appidea avatar linmic avatar luisdralves 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

Watchers

 avatar  avatar  avatar  avatar

react-native-hce's Issues

Invalid Capability Container CCLEN value

In the Android directory, the Capability Container (CCLEN) value is statically set to 0x0011 (17 bytes) size in react-native-hce/android/src/main/java/com/reactnativehce/apps/nfc/NFCTagType4.java line 24. "001120FFFFFFFF"

In line 50, within the setUpCapabilityContainerContent() function, when building the CC from CC_HEADER and controlTlv static values, the CC's actual size is 0x000F (15 bytes).

Please correct them in line 24. to "000F20FFFFFFFF"

Some libraries attempt to read the extra TLV block unsuccessfully and then exit with an error message: "Unexpected end of data".

Cannot read property 'on' of undefined

I tried to run this code, and i got cannot read property 'on' of undefined could you help me, am i doing something wrong?

import {
  HCESession,
  NFCTagType4NDEFContentType,
  NFCTagType4,
  HCESessionProvider,
} from 'react-native-hce';

function App() {
  let session;

  const startSession = async () => {
    const tag = new NFCTagType4({
      type: NFCTagType4NDEFContentType.Text,
      content: 'Hello world',
      writable: false,
    });

    session = await HCESession.getInstance();

    console.log('SESSION' + JSON.stringify(session));
    session.setApplication(tag);
    await session.setEnabled(true);
  };

  const stopSession = async () => {
    if (session) {
      await session.setEnabled(false);
    }
  };

  useEffect(() => {
    startSession();
    const removeListener = session.on(HCESession.Events.HCE_STATE_READ, () => {
      ToastAndroid.show('The tag has been read! Thank You.', ToastAndroid.LONG);
    });

    return () => {
      stopSession();
      removeListener();
    };
  }, []);

  return (
    <HCESessionProvider>
      <TouchableOpacity onPress={startSession}>
        <Text>EMULATE TAG CARD </Text>
      </TouchableOpacity>
    </HCESessionProvider>
  );
}

Getting id of emulated card

Hi,

I want to get emulated card unique id and match it to phone. When phone is readed to NFC device, I want to check uid of the card.

How can I get id of emulated card or is it possible to set card id manually?

Thank you !!

Listen for events while emulation doesn't work (HCESession.getInstance();)

Hello again,
the new HCE function and listen() function both don't work because of one error.

Error:

TypeError: _reactNativeHce.default.getInstance is not a function. (In '_reactNativeHce.default.getInstance()', 
'_reactNativeHce.default.getInstance' is undefined)

Issues with this line: const instance = await HCESession.getInstance();

old HCE function (works):

async function startSession() {

  console.log("Session starts!");

  const tag = new NFCTagType4(NFCContentType.Text, "Its working LOLLL Motherfuckers!!!");

  session = await (new HCESession(tag)).start();

  console.log("Successfull");
}

new listen() function:

const listen = async () => {
  const removeListener = session.on(HCESession.Events.HCE_STATE_READ, () => {
    ToastAndroid.show("The tag has been read! Thank You.", ToastAndroid.LONG);
  });

  removeListener();
}

old listen() function:

async function checkHCEStatus(){

  const instance = await HCESession.getInstance();
  const removeListener = instance.on(HCESession.Events.HCE_STATE_READ, () => {
    ToastAndroid.show("The tag has been read! Thank You.", ToastAndroid.LONG);
    removeListener();
  });

}

The only difference between those two listen() functions is that the old one calls the instance itself and the new one uses the instance from the HCE function.

Thanks for Help

How to compile Java code

Hello,

I'm trying to apply modifications to the Java code of react-native-hce.
My goal is to make it more flexible to use (configuring AID for instance).
Though I can't get to rebuild the Java part, either as a dependency in a React Native app, or as a standalone repository.

Could you provide some documentation to enable Java compiling as a subproject or as a whole please?

Thank you!

Build fails on the latest version of React Native v0.76.7

Fresh project installed from React Native v0.76.7

npx react-native run-android
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':react-native-hce'.
> Failed to notify project evaluation listener.
   > Could not create task ':react-native-hce:compileDebugAndroidTestKotlin'.
      > Cannot use @TaskAction annotation on method AbstractKotlinCompile.execute() because interface org.gradle.api.tasks.incremental.IncrementalTaskInputs is not a valid parameter to an action method.
   > KotlinJvmAndroidCompilation with name 'debugAndroidTest' not found.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
error Failed to install the app. Command failed with exit code 1: ./gradlew tasks FAILURE: Build failed with an exception. * What went wrong:
A problem occurred configuring project ':react-native-hce'.
> Failed to notify project evaluation listener. > Could not create task ':react-native-hce:compileDebugAndroidTestKotlin'. > Cannot use @TaskAction annotation on method AbstractKotlinCompile.execute() because interface org.gradle.api.tasks.incremental.IncrementalTaskInputs is not a valid parameter to an action method. > KotlinJvmAndroidCompilation with name 'debugAndroidTest' not found. * Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 2s
> Task :gradle-plugin:compileKotlin UP-TO-DATE
> Task :gradle-plugin:compileJava NO-SOURCE
> Task :gradle-plugin:pluginDescriptors UP-TO-DATE
> Task :gradle-plugin:processResources UP-TO-DATE
> Task :gradle-plugin:classes UP-TO-DATE
> Task :gradle-plugin:jar UP-TO-DATE
> Task :gradle-plugin:inspectClassesForKotlinIC UP-TO-DATE Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0. You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins. See https://docs.gradle.org/8.0.1/userguide/command_line_interface.html#sec:command_line_warnings
5 actionable tasks: 5 up-to-date.

NFC Permissions

How can we force android to ask user permissions to acess NFC module?

Am emulating a tag, and i only start the emulation process when user clicks on a button but if the user doesn't have the nfc turned on, the aplication doesn't ask for permissions.
I already looked up react native documentation but i didn't found a permission for NFC.

listen() function isseus

Hello again;)
im facing issues with the listen() function.
If im calling the listen() function in the startsession() function, the phone recognizes when there is an actual data transfer and everything works the first time great.
But when im calling the startsession() function a second time, the listen() output from the first time gets printed and fucks everything up.

Is there any way to avoid this?

Thanks for Help!

Example doesnt work

Hi folks, we love your work, please help revise your guideline and example because we evaluated the apk built from the latest sourcebase, it shows that the scanner apps cant detect any HCE-based tag, we tested on popular NFC reader apps.
Refs for NFC reader apps:

  1. https://play.google.com/store/apps/details?id=com.wakdev.wdnfc&hl=en&gl=US
  2. https://play.google.com/store/apps/details?id=com.gonext.nfcreader&hl=en&gl=US
  3. https://play.google.com/store/apps/details?id=com.nxp.taginfolite&hl=en&gl=US
  4. The APK built from example sourcebase

Make this library to be usable with Expo

That would be awesome if you could make this library available for Expo, like react native nfc manager library.
To do that you have to write a config plugin to be usable in managed expo projects. Wodin from expo's forum wrote a config plugin for this library, but I have just started to test it, and at present it's not working, because the hce service does not appear in Android's settings, and when I send APDU I always get 62 82 which means "File not found". So the aid_list.xml maybe missing somehow?!
Here is the config plugin for managed expo projects:
But I do not know it's working as it expeted...

`const { withAndroidManifest, withPlugins } = require("@expo/config-plugins");
const xml2js = require("xml2js");
const { mkdirSync, writeFileSync } = require("fs");

const NfcHceServiceXml = <service android:name="com.reactnativehce.services.CardService" android:exported="true" android:enabled="false" android:permission="android.permission.BIND_NFC_SERVICE"> <intent-filter> <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> <meta-data android:name="android.nfc.cardemulation.host_apdu_service" android:resource="@xml/aid_list"/> </service>;

let NfcHceService;
xml2js.parseString(NfcHceServiceXml, (err, result) => (NfcHceService = result.service));

function withNfcHceAndroidManifest(config, { appIds }) {
return withAndroidManifest(config, (config) => {
config.modResults = addNfcPermissionToManifest(config.modResults);
config.modResults = addNfcHceHardwareFeatureToManifest(config.modResults);
config.modResults = addNfcHceServiceToManifest(config.modResults);
writeAidList(appIds);
return config;
});
}

function addNfcPermissionToManifest(androidManifest) {
// Add <uses-permission android:name="android.permission.NFC" /> to the AndroidManifest.xml
if (!Array.isArray(androidManifest.manifest["uses-permission"])) {
androidManifest.manifest["uses-permission"] = [];
}

if (
    !androidManifest.manifest["uses-permission"].find(
        (item) => item.$["android:name"] === "android.permission.NFC"
    )
) {
    androidManifest.manifest["uses-permission"].push({
        $: {
            "android:name": "android.permission.NFC",
        },
    });
}
return androidManifest;

}

function addNfcHceHardwareFeatureToManifest(androidManifest) {
// Add <uses-feature android:name="android.hardware.nfc.hce" android:required="true" /> to the AndroidManifest.xml
if (!Array.isArray(androidManifest.manifest["uses-feature"])) {
androidManifest.manifest["uses-feature"] = [];
}

if (
    !androidManifest.manifest["uses-feature"].find(
        (item) => item.$["android:name"] === "android.hardware.nfc.hce"
    )
) {
    androidManifest.manifest["uses-feature"].push({
        $: {
            "android:name": "android.hardware.nfc.hce",
            "android:required": "true",
        },
    });
}
return androidManifest;

}

function addNfcHceServiceToManifest(androidManifest) {
const { manifest } = androidManifest;

if (!Array.isArray(manifest["application"])) {
    console.warn("withReactNativeHce: No manifest.application array?");
    return androidManifest;
}

const application = manifest["application"].find(
    (item) => item.$["android:name"] === ".MainApplication"
);
if (!application) {
    console.warn("withReactNativeHce: No .MainApplication?");
    return androidManifest;
}

if (!Array.isArray(application["service"])) {
    application["service"] = [];
}

if (
    !application["service"].find(
        (item) =>
            item.$["android:name"] === "com.reactnativehce.services.CardService"
    )
) {
    application["service"].push(NfcHceService);
}

return androidManifest;

}

function aidFilters(appIds) {
return appIds.map((appId) => ({ $: { "android:name": appId } }));
}

function aidGroup(appIds) {
return [
{
$: {
"android:category": "other",
"android:description": "@string/app_name",
},
"aid-filter": aidFilters(appIds),
},
];
}

function hostApduService(appIds) {
return {
"host-apdu-service": {
$: {
"xmlns:android": "http://schemas.android.com/apk/res/android",
"android:description": "@string/app_name",
"android:requireDeviceUnlock": "false",
},
"aid-group": aidGroup(appIds),
},
};
}

function writeAidList(appIds) {
const obj = hostApduService(appIds);
const builder = new xml2js.Builder();
const xml = builder.buildObject(obj);
const dir = "android/app/src/main/res/xml";

mkdirSync(dir, { recursive: true });
writeFileSync(`${dir}/aid_list.xml`, xml);

}

module.exports = (config, props) =>
withPlugins(config, [[withNfcHceAndroidManifest, props]]);`

Can I open a specific application when the Emulating device is read.

First of all, thanks a lot for this package! Really appreciate it.

I am a noob to Mobile app development, so please forgive me if I am wrong. So, when I emulate a phone using this package, I want the reading device/phone to open a specific app. Can we do this using this package? Is this handled here or is it handled by the reader? Because I saw this article from Android official documentation - https://developer.android.com/guide/topics/connectivity/nfc/nfc?authuser=1#tag-dispatch

If it's possible please let me know! Thanks

Troubles in google pixel 7a/4a

The code emulates fine on Android 11 ZTE blade, everything is great.
But when I run it on Android 13 (Google Pixel 7a or Google Pixel 4a), the content doesn't generate.

React native HCE

I could not install the application and access it. It gives me error while launching the app.

HCE_STATE_READ event is fired multiple times on tag reading

I'm trying to emulate a NFCtagType4 with an Android device.
I'm able to read the tag but HCE_STATE_READ event is fired 3 times.
Is that the desired behaviour?
I fixed it locally in respondRead method inside NFCTagType4 class:

if (realLength == slicedResponse.length) {
      this.hceModel.getLastState()
                   .setValue(HceViewModel.HCE_STATE_READ);
    }

Could it be a valid solution to avoid multiple firings?

Appropiate installation

Hi there!

First of all, thank you so much for this library! I assume something, I would like to know if am I right or not.
So I assume that if I did everything correctly, then the hce service should appear in the Android settings of services, where we can select the service.
So if I developed well my current app, the service should appear isn't it?
At present the service does not appear. :/
Thank you for your reply.

React-native-hce. Build failed

Sorry for my english.
Failure: build failed with an exception.
I'm try use example, but program drop exception with creating task.
Error message:
`
FAILURE: Build failed with an exception.

What went wrong:
A problem occurred configuring project ':react-native-hce'.

Failed to notify project evaluation listener.
Could not create task ':react-native-hce:compileDebugAndroidTestKotlin'.
> Cannot use @TaskAction annotation on method AbstractKotlinCompile.execute() because interface org.gradle.api.tasks.incremental.IncrementalTaskInputs is not a valid parameter to an action method.
KotlinJvmAndroidCompilation with name 'debugAndroidTest' not found.
Try:
Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.
BUILD FAILED in 4s
error Failed to install the app.
`

Issues with the new Update

Dear Appidea,
im having issues with your latest react-native-hce Commit.

Error 1:

Error: TypeError: undefined is not an object (evaluating '_reactNativeHce.NFCTagType4NDEFContentType.Text')

Code:

const tag = new NFCTagType4({
    type: NFCTagType4NDEFContentType.Text,
    content: "Hello world",
    writable: false
});

This one works: const tag = new NFCTagType4(NFCContentType.Text, "Its working LOLLL Motherfuckers!!!");

Error 2:

If I´m using the working code, im getting the second error:

TypeError: undefined is not an object (evaluating '_reactNativeHce.HCESession.getInstance')

Thanks for Help and this great Repository;)

Fixed: Unable to send NDEF message

Hello, I am the owner of Pixel 4a and 7a (android 13 and 14). I couldn't emulate the tag.
I found the solution in the following: in the NFCTagType4.java file
change
public final byte[] ndefDataBuffer = new byte[0xFFFE];
on
public final byte[] ndefDataBuffer = new byte[0x7FFF];

change
public final byte[] ccDataBuffer = new byte[15];
on
public final byte[] ccDataBuffer = new byte[] {
0x00, 0x0f, // CCLEN
0x20, // Mapping Version
0x00, 0x3b, // Maximum R-APDU data size
0x00, 0x34, // Maximum C-APDU data size
0x04, 0x06, // Tag & Length
(byte)0xe1, 0x04, // NDEF File Identifier
(byte)0x7F, (byte)0xFF, // Maximum NDEF size
0x00, // NDEF file read access granted
(byte)0xff, // NDEF File write access denied
};

delete
setUpCapabilityContainerContent and its call
I don't use tag rewriting and I don't care about the writable property.
Please improve these points. Thank you

Record Doesn't Send From Samsung Galaxy Note 20

Greetings

When activating hce with text content type on a Samsung Galaxy Note 20, the record doesn't transfer when read.

Thank you for all the amazing work, I heavily appreciate all the efforts put in the library, It's been a god-send for me so far.

Issues with 2 installed HCE Apps

Hello,
im having issues with two installed HCE Apps on one Android Device.
If im calling the HCE function and enter with another phone the NFC field, the HCE phone asks which HCE protocol I want to use.

Example:
Phone 1: Has two Apps with Android HCE installed
Phone 2: should receive the emulated Data from Phone 1
If im calling the HCE function on Phone 1 and enter with Phone 2 the NFC field, Phone 1 asks which HCE protocol I want to use.

How can I declare in my HCE App, that I want to use this one?

Thanks for Help;)

NFC Link Lost

Hi!
I included this library in an app I'm using to send data to a PN532.
I am able to detect the emulated tag, however the NFC link is always lost right after I read the nlen value (Finishing service: 0).
I used NDEF Tag Emulator to test the PN532 code and it was able to successfully read the data from the emulated card.
I am using a Samsung Galaxy S10e to test my app.
Do you have any idea why this may be happening?

Thanks!

The Data is sent only which App is in Background?

Hi,
I integrate this lib in my current project but the issue is when i start simulation with text, if app is in forground the other device don't scan text. But If i put app in background then Other device recieve data .
Please help in doing this in foreground as well.
Thanks in Advance.Please answer asap.
Shashi.

Express Mode

Hello!
I'm using this library on one of my projects and it works great! thanks for sharing it!
I'd like to implement the HCE feature on iOS, but I understand that it's not possible, right?

Also, I noticed that Apple has an express mode: With Express Mode, you can use some of your cards, keys, and passes in Apple Wallet without waking or unlocking your device, or authenticating with Face ID, Touch ID, or your passcode. You might even be able to use your card, pass, or key when your device needs to be charged. https://support.apple.com/en-us/HT212171

Do you know if that is possible to implement using this library on Android? maybe it's a feature that is not development, but I'm happy to contribute if you see it possible to implement it.

Thanks!
Charlie Fontana

Unable to Send NDEF message from android 10 to android 12

Hello, first of all, thank you very much for a great job with this react native library.

I am experiencing the following issue:

I am able to use the HCE library on both android 10 and 12, which are the devices I am testing with.

Both are able to send the HCE message, however android 12 is unable to read the message from android 10.

For example, I can send an NDEF message from android 10 to another android 10 device as a reader.

However, if a try to send the NDEF message from android 10 to a Samsung S22+ with android 12, the reader is unable to receive the NDEF messages, there are no errors on any of the two sides. There is just a small bubble on the HCE side (android 10) which states that there are no apps available to receive the tag.

As a side note I am using this library as a reader:

https://github.com/revtel/react-native-nfc-manager

Also, I tested sending the HCE NDEF message with another google play store library and the message is properly sent from android 10 to 12 with this one:

https://play.google.com/store/apps/details?id=com.maxsoft.ndeftagemulator&hl=en&gl=US

Just wanted to know I anyone has experienced something similar or has any clue of what could be happening. Thanks in advance!

trouble setting up an AID

hi,

I am having some troubles setting the aid with this library.
If I use any other aid than the one in the example D2760000850101 the app is never selected
this is the debug output for D2760000850102 for example

card inserted <Buffer 3b 80 80 01 01>
trying to connect CONNECT_MODE_CARD 2
connected { type: 2, protocol: 2 }
handling tag {
  atr: <Buffer 3b 80 80 01 01>,
  standard: 'TAG_ISO_14443_4',
  type: 'TAG_ISO_14443_4'
}
processing ISO 14443-4 tag {
  atr: <Buffer 3b 80 80 01 01>,
  standard: 'TAG_ISO_14443_4',
  type: 'TAG_ISO_14443_4'
}
transmitting <Buffer 00 a4 04 00 07 d2 76 00 00 85 01 02 00> 40
transmit response received <Buffer 6a 82> 2

so I am getting 6a 82 - app not found instead of 90 00 when I use anything than your sample aid.

any idea why it might happening?

but even with your aid no data is being transmitted..

  • the app does appear in nfc settings under other.

I've tired clearing the cache and reinstalling the app..

thanks cheers
dan

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.