├── ios ├── Hce-Bridging-Header.h ├── Hce.swift ├── Hce.m └── Hce.xcodeproj │ └── project.pbxproj ├── logo.png ├── .gitattributes ├── example ├── app.json ├── tsconfig.json ├── android │ ├── app │ │ ├── debug.keystore │ │ ├── src │ │ │ ├── main │ │ │ │ ├── res │ │ │ │ │ ├── values │ │ │ │ │ │ ├── strings.xml │ │ │ │ │ │ └── styles.xml │ │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ │ └── xml │ │ │ │ │ │ └── aid_list.xml │ │ │ │ ├── java │ │ │ │ │ └── com │ │ │ │ │ │ └── example │ │ │ │ │ │ └── reactnativehce │ │ │ │ │ │ ├── MainActivity.java │ │ │ │ │ │ └── MainApplication.java │ │ │ │ └── AndroidManifest.xml │ │ │ └── debug │ │ │ │ └── AndroidManifest.xml │ │ ├── proguard-rules.pro │ │ └── build.gradle │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── settings.gradle │ ├── build.gradle │ ├── gradle.properties │ ├── gradlew.bat │ └── gradlew ├── src │ ├── images │ │ ├── btn-active.png │ │ └── btn-inactive.png │ ├── DataLayerTypes.ts │ ├── Controls │ │ ├── NavButton.tsx │ │ └── FormRow.tsx │ ├── StateFAB.tsx │ ├── LogView.tsx │ ├── App.tsx │ ├── SetupView.tsx │ └── useDataLayer.ts ├── index.js ├── babel.config.js ├── package.json └── metro.config.js ├── babel.config.js ├── android ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradle.properties ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── com │ │ └── reactnativehce │ │ ├── IHCEApplication.java │ │ ├── utils │ │ ├── ByteArrayOperations.java │ │ ├── ApduHelper.java │ │ ├── BinaryUtils.java │ │ └── LICENSE │ │ ├── HcePackage.java │ │ ├── managers │ │ ├── HceViewModel.java │ │ ├── PrefManager.java │ │ └── EventManager.java │ │ ├── services │ │ └── CardService.java │ │ ├── apps │ │ └── nfc │ │ │ ├── NdefEntity.java │ │ │ └── NFCTagType4.java │ │ └── HceModule.java ├── gradlew.bat ├── build.gradle └── gradlew ├── src ├── __tests__ │ └── index.test.tsx ├── index.ts ├── HCEApplication.ts ├── HCESessionContext.tsx ├── NFCTagType4 │ └── index.ts └── HCESession.ts ├── .editorconfig ├── tsconfig.json ├── react-native-hce.podspec ├── .gitignore ├── LICENSE ├── CONTRIBUTING.md ├── package.json └── README.md /ios/Hce-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | #import 2 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/logo.png -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | # specific for windows script files 3 | *.bat text eol=crlf -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "HceExample", 3 | "displayName": "Hce Example" 4 | } 5 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@react-native/typescript-config/tsconfig.json" 3 | } 4 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /example/android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/debug.keystore -------------------------------------------------------------------------------- /example/src/images/btn-active.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/src/images/btn-active.png -------------------------------------------------------------------------------- /example/src/images/btn-inactive.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/src/images/btn-inactive.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Hce Example 3 | 4 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | Hce_kotlinVersion=1.3.50 2 | Hce_compileSdkVersion=28 3 | Hce_buildToolsVersion=28.0.3 4 | Hce_targetSdkVersion=28 5 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appidea/react-native-hce/HEAD/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | import { AppRegistry } from 'react-native'; 2 | import App from './src/App'; 3 | import { name as appName } from './app.json'; 4 | 5 | AppRegistry.registerComponent(appName, () => App); 6 | -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ios/Hce.swift: -------------------------------------------------------------------------------- 1 | @objc(Hce) 2 | class Hce: NSObject { 3 | 4 | @objc(multiply:withB:withResolver:withRejecter:) 5 | func multiply(a: Float, b: Float, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void { 6 | resolve(a*b) 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Sep 24 15:15:49 CEST 2020 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/__tests__/index.test.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | it.todo('write a test'); 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | indent_style = space 10 | indent_size = 2 11 | 12 | end_of_line = lf 13 | charset = utf-8 14 | trim_trailing_whitespace = true 15 | insert_final_newline = true 16 | -------------------------------------------------------------------------------- /ios/Hce.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | @interface RCT_EXTERN_MODULE(Hce, NSObject) 4 | 5 | RCT_EXTERN_METHOD(multiply:(float)a withB:(float)b 6 | withResolver:(RCTPromiseResolveBlock)resolve 7 | withRejecter:(RCTPromiseRejectBlock)reject) 8 | 9 | + (BOOL)requiresMainQueueSetup 10 | { 11 | return YES; 12 | } 13 | 14 | @end 15 | -------------------------------------------------------------------------------- /example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'HceExample' 2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 3 | include ':app', ':models' 4 | includeBuild('../node_modules/@react-native/gradle-plugin') 5 | 6 | include ':react-native-hce' 7 | project(':react-native-hce').projectDir = new File(rootProject.projectDir, '../../android') 8 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/xml/aid_list.xml: -------------------------------------------------------------------------------- 1 | 4 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { 2 | HCESession, 3 | HCESessionEvents, 4 | HCESessionEventListener, 5 | HCESessionEventListenerCancel, 6 | } from './HCESession'; 7 | export { 8 | HCESessionContext, 9 | HCESessionProvider, 10 | HCEReactContextValue, 11 | } from './HCESessionContext'; 12 | export { 13 | NFCTagType4, 14 | NFCTagType4NDEFContentType, 15 | NFCTagType4NDEFRecord, 16 | } from './NFCTagType4'; 17 | export type { HCEApplication } from './HCEApplication'; 18 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/example/reactnativehce/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.reactnativehce; 2 | 3 | import com.facebook.react.ReactActivity; 4 | 5 | public class MainActivity extends ReactActivity { 6 | 7 | /** 8 | * Returns the name of the main component registered from JavaScript. This is used to schedule 9 | * rendering of the component. 10 | */ 11 | @Override 12 | protected String getMainComponentName() { 13 | return "HceExample"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /example/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "lib": ["ES2018", "ES2018.AsyncIterable"], 4 | "target": "ES2018", 5 | "noImplicitAny": true, 6 | "declaration": true, 7 | "baseUrl": "./src", 8 | "esModuleInterop": true, 9 | "sourceMap": true, 10 | "outDir": "./dist", 11 | "moduleResolution": "Node", 12 | "jsx": "react", 13 | "resolveJsonModule": true, 14 | "skipLibCheck": true, 15 | "emitDeclarationOnly": true 16 | }, 17 | "exclude": ["node_modules", "dist", "example"] 18 | } 19 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/IHCEApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce; 8 | 9 | public interface IHCEApplication { 10 | byte[] processCommand(byte[] command); 11 | boolean assertSelectCommand(byte[] command); 12 | void onDestroy(int reason); 13 | } 14 | -------------------------------------------------------------------------------- /react-native-hce.podspec: -------------------------------------------------------------------------------- 1 | require "json" 2 | 3 | package = JSON.parse(File.read(File.join(__dir__, "package.json"))) 4 | 5 | Pod::Spec.new do |s| 6 | s.name = "react-native-hce" 7 | s.version = package["version"] 8 | s.summary = package["description"] 9 | s.homepage = package["homepage"] 10 | s.license = package["license"] 11 | s.authors = package["author"] 12 | 13 | s.platforms = { :ios => "9.0" } 14 | s.source = { :git => "https://github.com/appidea/react-native-hce.git", :tag => "#{s.version}" } 15 | 16 | 17 | s.source_files = "ios/**/*.{h,m,mm,swift}" 18 | 19 | 20 | s.dependency "React" 21 | end 22 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/utils/ByteArrayOperations.java: -------------------------------------------------------------------------------- 1 | package com.reactnativehce.utils; 2 | 3 | public class ByteArrayOperations { 4 | public static byte[] fillByteArrayToFixedDimension(byte[] array, int fixedSize) { 5 | if (array.length == fixedSize) { 6 | return array; 7 | } 8 | 9 | byte[] start = BinaryUtils.HexStringToByteArray("00"); 10 | byte[] filledArray = new byte[start.length + array.length]; 11 | System.arraycopy(start, 0, filledArray, 0, start.length); 12 | System.arraycopy(array, 0, filledArray, start.length, array.length); 13 | return fillByteArrayToFixedDimension(filledArray, fixedSize); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/HCEApplication.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | /** 8 | * This interface is intended to describe the "card application" state that 9 | * can be represented in Host card emulation. Intended to be immutable. 10 | */ 11 | export interface HCEApplication { 12 | /** 13 | * Internal unique identifier of application type. 14 | */ 15 | type: string; 16 | 17 | /** 18 | * The content of application that can vary during the lifetime, e.g. internal files. 19 | */ 20 | content: any; 21 | } 22 | -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | gradle.startParameter.excludedTaskNames.addAll( 2 | gradle.startParameter.taskNames.findAll { it.contains("testClasses") } 3 | ) 4 | 5 | buildscript { 6 | ext { 7 | buildToolsVersion = "34.0.0" 8 | minSdkVersion = 26 9 | compileSdkVersion = 34 10 | targetSdkVersion = 34 11 | ndkVersion = "26.1.10909125" 12 | kotlinVersion = "1.9.22" 13 | } 14 | repositories { 15 | google() 16 | mavenCentral() 17 | } 18 | dependencies { 19 | classpath("com.android.tools.build:gradle") 20 | classpath("com.facebook.react:react-native-gradle-plugin") 21 | classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") 22 | } 23 | } 24 | 25 | apply plugin: "com.facebook.react.rootproject" 26 | -------------------------------------------------------------------------------- /example/src/DataLayerTypes.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | export interface LogEntry { 8 | time: string; 9 | message: string; 10 | } 11 | 12 | export interface NFCTagReactStateProps { 13 | content: string; 14 | type: string; 15 | writable: boolean; 16 | _pristine: boolean; 17 | } 18 | 19 | export interface DataLayer { 20 | nfcTagProps: NFCTagReactStateProps; 21 | updateProp: any; 22 | switchSession: (enable: boolean) => Promise; 23 | enabled: boolean; 24 | log: LogEntry[]; 25 | loading: boolean; 26 | } 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # XDE 6 | .expo/ 7 | 8 | # VSCode 9 | .vscode/ 10 | jsconfig.json 11 | 12 | # Xcode 13 | # 14 | build/ 15 | *.pbxuser 16 | !default.pbxuser 17 | *.mode1v3 18 | !default.mode1v3 19 | *.mode2v3 20 | !default.mode2v3 21 | *.perspectivev3 22 | !default.perspectivev3 23 | xcuserdata 24 | *.xccheckout 25 | *.moved-aside 26 | DerivedData 27 | *.hmap 28 | *.ipa 29 | *.xcuserstate 30 | project.xcworkspace 31 | 32 | # Android/IJ 33 | # 34 | .idea 35 | .gradle 36 | local.properties 37 | android.iml 38 | .settings 39 | 40 | # Cocoapods 41 | # 42 | example/ios/Pods 43 | 44 | # node.js 45 | # 46 | node_modules/ 47 | npm-debug.log 48 | yarn-debug.log 49 | yarn-error.log 50 | 51 | # BUCK 52 | buck-out/ 53 | \.buckd/ 54 | android/app/libs 55 | android/keystores/debug.keystore 56 | 57 | # Expo 58 | .expo/* 59 | 60 | # generated by bob 61 | lib/ 62 | 63 | ## Generated docs 64 | docs/ 65 | dist/ -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = { 5 | presets: ['module:metro-react-native-babel-preset'], 6 | plugins: [ 7 | ['@babel/plugin-transform-class-properties', { loose: false }], 8 | ['@babel/plugin-transform-private-methods', { loose: false }], 9 | ['@babel/plugin-transform-private-property-in-object', { loose: false }], 10 | [ 11 | 'module-resolver', 12 | { 13 | extensions: [ 14 | '.js', 15 | '.ts', 16 | '.tsx', 17 | '.ios.js', 18 | '.ios.ts', 19 | '.android.js', 20 | '.android.ts', 21 | '.json', 22 | ], 23 | root: [path.join(__dirname, '..')], 24 | alias: { 25 | 'react-native-hce': path.join(__dirname, '..'), 26 | // [pak.name]: path.join(__dirname, '..', pak.source), 27 | }, 28 | }, 29 | ], 30 | ], 31 | }; 32 | -------------------------------------------------------------------------------- /example/src/Controls/NavButton.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import React from 'react'; 8 | import { StyleSheet, Text, TouchableOpacity } from 'react-native'; 9 | 10 | interface NavButtonProps { 11 | onPress: () => any; 12 | active: boolean; 13 | title: string; 14 | } 15 | 16 | const NavButton = ({ onPress, active, title }: NavButtonProps) => { 17 | return ( 18 | 19 | {title} 20 | 21 | ); 22 | }; 23 | 24 | const styles = StyleSheet.create({ 25 | container: { margin: 10 }, 26 | boldText: { 27 | fontWeight: 'bold', 28 | }, 29 | normalText: { 30 | fontWeight: 'normal', 31 | }, 32 | }); 33 | 34 | export default NavButton; 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Mateusz Falkowski 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /example/src/Controls/FormRow.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import React from 'react'; 8 | import { View, Text, StyleSheet } from 'react-native'; 9 | 10 | interface FormRowProps { 11 | label: string; 12 | children: any; 13 | } 14 | 15 | const FormRow = ({ label, children }: FormRowProps) => { 16 | return ( 17 | 18 | {label} 19 | {children} 20 | 21 | ); 22 | }; 23 | 24 | const styles = StyleSheet.create({ 25 | container: { marginBottom: 10, width: '100%', alignItems: 'flex-start' }, 26 | label: { 27 | fontSize: 12, 28 | color: '#737373', 29 | letterSpacing: 1, 30 | fontWeight: 'bold', 31 | textTransform: 'uppercase', 32 | paddingLeft: 6, 33 | }, 34 | content: { width: '100%' }, 35 | }); 36 | 37 | export default FormRow; 38 | -------------------------------------------------------------------------------- /example/src/StateFAB.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import React from 'react'; 8 | import { Image, StyleSheet, TouchableOpacity, View } from 'react-native'; 9 | import type { DataLayer } from './DataLayerTypes'; 10 | 11 | const activeBtn = require('./images/btn-active.png'); 12 | const inactiveBtn = require('./images/btn-inactive.png'); 13 | 14 | const StateFAB = ({ enabled, switchSession }: DataLayer) => ( 15 | 16 | switchSession(!enabled)}> 17 | 18 | 19 | 20 | ); 21 | 22 | const styles = StyleSheet.create({ 23 | container: { 24 | flexDirection: 'row', 25 | position: 'absolute', 26 | bottom: 15, 27 | right: 15, 28 | }, 29 | icon: { 30 | width: 80, 31 | height: 80, 32 | }, 33 | }); 34 | 35 | export default StateFAB; 36 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/HcePackage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce; 8 | 9 | import com.facebook.react.ReactPackage; 10 | import com.facebook.react.bridge.NativeModule; 11 | import com.facebook.react.bridge.ReactApplicationContext; 12 | import com.facebook.react.uimanager.ViewManager; 13 | 14 | import androidx.annotation.NonNull; 15 | 16 | import java.util.ArrayList; 17 | import java.util.Collections; 18 | import java.util.List; 19 | 20 | public class HcePackage implements ReactPackage { 21 | @NonNull 22 | @Override 23 | public List createViewManagers(@NonNull ReactApplicationContext reactContext) { 24 | return Collections.emptyList(); 25 | } 26 | 27 | @NonNull 28 | @Override 29 | public List createNativeModules(@NonNull ReactApplicationContext reactContext) { 30 | List modules = new ArrayList<>(); 31 | 32 | modules.add(new HceModule(reactContext)); 33 | 34 | return modules; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/utils/ApduHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce.utils; 8 | 9 | import com.reactnativehce.utils.BinaryUtils; 10 | 11 | import java.util.Arrays; 12 | 13 | public class ApduHelper { 14 | public static final byte[] C_APDU_SELECT_APP = BinaryUtils.HexStringToByteArray("00A40400"); 15 | public static final byte[] C_APDU_SELECT_FILE = BinaryUtils.HexStringToByteArray("00A4000C02"); 16 | public static final byte[] C_APDU_READ = BinaryUtils.HexStringToByteArray("00B0"); 17 | public static final byte[] C_APDU_WRITE = BinaryUtils.HexStringToByteArray("00D6"); 18 | public static final byte[] R_APDU_OK = BinaryUtils.HexStringToByteArray("9000"); 19 | public static final byte[] R_APDU_ERROR = BinaryUtils.HexStringToByteArray("6A82"); 20 | 21 | public static Boolean commandByRangeEquals(byte[] command, Integer from, Integer to, byte[] expectedCommand) { 22 | return Arrays.equals(Arrays.copyOfRange(command, from, to), expectedCommand); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hce-example", 3 | "version": "0.0.1", 4 | "main": "index.tsx", 5 | "private": true, 6 | "scripts": { 7 | "android": "react-native run-android", 8 | "ios": "react-native run-ios", 9 | "lint": "eslint .", 10 | "start": "react-native start", 11 | "test": "jest" 12 | }, 13 | "dependencies": { 14 | "@react-native-picker/picker": "^2.4.4", 15 | "react": "18.2.0", 16 | "react-native": "0.74.5" 17 | }, 18 | "devDependencies": { 19 | "@babel/core": "^7.20.0", 20 | "@babel/preset-env": "^7.20.0", 21 | "@babel/runtime": "^7.20.0", 22 | "@react-native/babel-preset": "0.74.87", 23 | "@react-native/eslint-config": "0.74.87", 24 | "@react-native/metro-babel-transformer": "^0.80.2", 25 | "@react-native/metro-config": "0.74.87", 26 | "@react-native/typescript-config": "0.74.87", 27 | "@types/react": "^18.2.6", 28 | "@types/react-test-renderer": "^18.0.0", 29 | "babel-jest": "^29.6.3", 30 | "babel-plugin-module-resolver": "^5.0.2", 31 | "eslint": "^8.19.0", 32 | "jest": "^29.6.3", 33 | "metro-react-native-babel-preset": "^0.77.0", 34 | "prettier": "2.8.8", 35 | "react-test-renderer": "18.2.0", 36 | "typescript": "5.0.4" 37 | }, 38 | "engines": { 39 | "node": ">=18" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /example/metro.config.js: -------------------------------------------------------------------------------- 1 | const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); 2 | const path = require('path'); 3 | const pak = require('../package.json'); 4 | const blacklist = require('metro-config/src/defaults/exclusionList'); 5 | 6 | const root = path.resolve(__dirname, '..'); 7 | 8 | const modules = Object.keys({ 9 | ...pak.peerDependencies, 10 | }); 11 | 12 | const extraNodeModules = { 13 | ...modules.reduce((acc, name) => { 14 | acc[name] = path.join(__dirname, 'node_modules', name); 15 | return acc; 16 | }, {}), 17 | 'react-native-hce': path.join(__dirname, '..'), 18 | }; 19 | 20 | /** 21 | * Metro configuration 22 | * https://reactnative.dev/docs/metro 23 | * 24 | * @type {import('metro-config').MetroConfig} 25 | */ 26 | const config = { 27 | resolver: { 28 | blacklistRE: blacklist( 29 | modules.map( 30 | (m) => 31 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 32 | ) 33 | ), 34 | 35 | extraNodeModules, 36 | }, 37 | transformer: { 38 | babelTransformerPath: require.resolve( 39 | '@react-native/metro-babel-transformer' 40 | ), 41 | getTransformOptions: async () => ({ 42 | transform: { 43 | experimentalImportSupport: false, 44 | inlineRequires: true, 45 | }, 46 | }), 47 | }, 48 | watchFolders: [ 49 | path.resolve(__dirname, '..'), 50 | path.resolve(__dirname, '../node_modules'), // sometimes needed 51 | ], 52 | projectRoot: path.resolve('.'), 53 | }; 54 | 55 | module.exports = mergeConfig(getDefaultConfig(__dirname), config); 56 | -------------------------------------------------------------------------------- /example/src/LogView.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import React from 'react'; 8 | import { ScrollView, StyleSheet, Text, View } from 'react-native'; 9 | import type { DataLayer } from './DataLayerTypes'; 10 | 11 | const LogView = ({ log }: DataLayer) => { 12 | return ( 13 | 14 | 15 | 16 | Event Log 17 | 18 | 19 | 20 | 21 | {log.map((line, key) => ( 22 | {line.time + ' ' + line.message} 23 | ))} 24 | 25 | 26 | 27 | 28 | ); 29 | }; 30 | 31 | const styles = StyleSheet.create({ 32 | container: { 33 | flex: 1, 34 | alignItems: 'center', 35 | justifyContent: 'center', 36 | }, 37 | log: { 38 | width: '100%', 39 | borderWidth: 1, 40 | marginTop: 20, 41 | }, 42 | logTitle: { 43 | backgroundColor: '#000', 44 | }, 45 | logTitleText: { 46 | color: '#FFF', 47 | padding: 8, 48 | }, 49 | logContent: { 50 | height: 200, 51 | }, 52 | logContentInner: { 53 | padding: 8, 54 | }, 55 | }); 56 | 57 | export default LogView; 58 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/example/reactnativehce/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.reactnativehce; 2 | 3 | import android.app.Application; 4 | import com.facebook.react.PackageList; 5 | import com.facebook.react.ReactApplication; 6 | import com.facebook.react.ReactNativeHost; 7 | import com.facebook.react.ReactPackage; 8 | import com.facebook.soloader.SoLoader; 9 | import java.util.List; 10 | 11 | import com.reactnativehce.HcePackage; 12 | 13 | public class MainApplication extends Application implements ReactApplication { 14 | 15 | private final ReactNativeHost mReactNativeHost = 16 | new ReactNativeHost(this) { 17 | @Override 18 | public boolean getUseDeveloperSupport() { 19 | return BuildConfig.DEBUG; 20 | } 21 | 22 | @Override 23 | protected List getPackages() { 24 | @SuppressWarnings("UnnecessaryLocalVariable") 25 | List packages = new PackageList(this).getPackages(); 26 | // Packages that cannot be autolinked yet can be added manually here, for HceExample: 27 | // packages.add(new MyReactNativePackage()); 28 | packages.add(new HcePackage()); 29 | 30 | return packages; 31 | } 32 | 33 | @Override 34 | protected String getJSMainModuleName() { 35 | return "index"; 36 | } 37 | }; 38 | 39 | @Override 40 | public ReactNativeHost getReactNativeHost() { 41 | return mReactNativeHost; 42 | } 43 | 44 | @Override 45 | public void onCreate() { 46 | super.onCreate(); 47 | SoLoader.init(this, /* native exopackage */ false); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 13 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 32 | 33 | 34 | 35 | 36 | 37 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/managers/HceViewModel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce.managers; 8 | 9 | import android.app.Application; 10 | import android.content.Context; 11 | import androidx.annotation.NonNull; 12 | import androidx.lifecycle.AndroidViewModel; 13 | import androidx.lifecycle.MutableLiveData; 14 | import androidx.lifecycle.ViewModelProvider; 15 | 16 | public class HceViewModel extends AndroidViewModel { 17 | private MutableLiveData lastState; 18 | private static HceViewModel instance = null; 19 | 20 | public static String HCE_STATE_CONNECTED = "connected"; 21 | public static String HCE_STATE_DISCONNECTED = "disconnected"; 22 | public static String HCE_STATE_ENABLED = "enabled"; 23 | public static String HCE_STATE_DISABLED = "disabled"; 24 | public static String HCE_STATE_READ = "read"; 25 | public static String HCE_STATE_WRITE_FULL = "writeFull"; 26 | public static String HCE_STATE_WRITE_PARTIAL = "writePartial"; 27 | public static String HCE_STATE_UPDATE_APPLICATION = "updateApplication"; 28 | 29 | public HceViewModel(@NonNull Application application) { 30 | super(application); 31 | } 32 | 33 | public static HceViewModel getInstance(Context appContext) { 34 | if (instance == null) { 35 | instance = ViewModelProvider.AndroidViewModelFactory.getInstance( 36 | (Application) appContext 37 | ).create(HceViewModel.class); 38 | } 39 | 40 | return instance; 41 | } 42 | 43 | public MutableLiveData getLastState() { 44 | if (lastState == null) { 45 | lastState = new MutableLiveData<>(); 46 | } 47 | 48 | return lastState; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) members: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m 13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | # Automatically convert third-party libraries to use AndroidX 25 | android.enableJetifier=true 26 | 27 | # Use this property to specify which architecture you want to build. 28 | # You can also override it from the CLI using 29 | # ./gradlew -PreactNativeArchitectures=x86_64 30 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 31 | 32 | # Use this property to enable support to the new architecture. 33 | # This will allow you to use TurboModules and the Fabric render in 34 | # your application. You should enable this flag either if you want 35 | # to write custom TurboModules/Fabric components OR use libraries that 36 | # are providing them. 37 | newArchEnabled=false 38 | 39 | # Use this property to enable or disable the Hermes JS engine. 40 | # If set to false, you will be using JSC instead. 41 | hermesEnabled=true -------------------------------------------------------------------------------- /src/HCESessionContext.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import React, { createContext, useEffect, useState } from 'react'; 8 | import { HCESession } from './HCESession'; 9 | 10 | /** 11 | * Interface to specify the value of {@link HCESessionContext}. 12 | * 13 | * The only one element is a {@link HCESession} class. 14 | * 15 | * @group React 16 | */ 17 | export interface HCEReactContextValue { 18 | session: HCESession; 19 | } 20 | 21 | /** 22 | * {@link https://reactjs.org/docs/context.html React Context} wrapper for {@link HCESession} class. 23 | * 24 | * Use in couple with {@link HCESessionProvider} 25 | * 26 | * @group React 27 | */ 28 | export const HCESessionContext = createContext({ 29 | session: new HCESession(), 30 | }); 31 | 32 | /** 33 | * {@link https://reactjs.org/docs/context.html React Context} wrapper for {@link HCESession} class - provider. 34 | * 35 | * Use it to provide the singleton instance of {@link HCESession} 36 | * to React application instead of calling {@link HCESession.getInstance} manually. 37 | * The provider will not render the children until the HCESession class will not be 38 | * properly picked or created. 39 | * 40 | * @group React 41 | * @constructor 42 | */ 43 | export const HCESessionProvider: React.FC<{ 44 | children?: React.ReactNode; 45 | }> = (props) => { 46 | const [session, setSession] = useState(); 47 | 48 | useEffect(() => { 49 | if (!session) { 50 | HCESession.getInstance().then((instance) => { 51 | setSession(instance); 52 | }); 53 | } 54 | }, [session, setSession]); 55 | 56 | if (!session) { 57 | return null; 58 | } 59 | 60 | return ; 61 | }; 62 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/managers/PrefManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce.managers; 8 | 9 | import android.content.Context; 10 | import android.content.SharedPreferences; 11 | 12 | public class PrefManager { 13 | private static PrefManager instance = null; 14 | private final static String PREF_LIB_SUFFIX = ".HCE_DATA"; 15 | private final SharedPreferences preferences; 16 | 17 | public PrefManager(Context applicationContext) { 18 | this.preferences = applicationContext.getSharedPreferences( 19 | applicationContext.getPackageName() + PREF_LIB_SUFFIX, 20 | Context.MODE_PRIVATE 21 | ); 22 | } 23 | 24 | public static PrefManager getInstance(Context applicationContext) { 25 | if (instance == null) { 26 | instance = new PrefManager(applicationContext); 27 | } 28 | 29 | return instance; 30 | } 31 | 32 | public Boolean exists() { 33 | return preferences.contains("type"); 34 | } 35 | 36 | public void setContent(String text) { 37 | preferences.edit().putString("content", text).apply(); 38 | } 39 | 40 | public String getContent() { 41 | return preferences.getString("content", ""); 42 | } 43 | 44 | public void setType(String text) { 45 | preferences.edit().putString("type", text).apply(); 46 | } 47 | 48 | public String getType() { 49 | return preferences.getString("type", ""); 50 | } 51 | 52 | public void setWritable(Boolean writable) { 53 | preferences.edit().putBoolean("writable", writable).apply(); 54 | } 55 | 56 | public Boolean getWritable() { 57 | return preferences.getBoolean("writable", false); 58 | } 59 | 60 | public void setEnabled(Boolean enabled) { 61 | preferences.edit().putBoolean("enabled", enabled).apply(); 62 | } 63 | 64 | public Boolean getEnabled() { 65 | return preferences.getBoolean("enabled", false); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import React, { useState } from 'react'; 8 | import { StyleSheet, View, Text } from 'react-native'; 9 | import { HCESessionProvider } from 'react-native-hce'; 10 | import SetupView from './SetupView'; 11 | import LogView from './LogView'; 12 | import NavButton from './Controls/NavButton'; 13 | import StateFab from './StateFAB'; 14 | import type { DataLayer } from './DataLayerTypes'; 15 | import useDataLayer from './useDataLayer'; 16 | 17 | enum Views { 18 | VIEW_SETUP, 19 | VIEW_LOG, 20 | } 21 | 22 | const App: React.FC = (): JSX.Element => { 23 | const [currentView, setCurrentView] = useState(Views.VIEW_SETUP); 24 | const dataLayer: DataLayer = useDataLayer(); 25 | 26 | return ( 27 | 28 | 29 | setCurrentView(Views.VIEW_SETUP)} 32 | active={currentView === Views.VIEW_SETUP} 33 | /> 34 | 35 | setCurrentView(Views.VIEW_LOG)} 38 | active={currentView === Views.VIEW_LOG} 39 | /> 40 | 41 | 42 | 43 | {dataLayer.loading && Loading...} 44 | {currentView === Views.VIEW_SETUP && } 45 | {currentView === Views.VIEW_LOG && } 46 | 47 | 48 | 49 | 50 | ); 51 | }; 52 | 53 | export default () => ( 54 | 55 | 56 | 57 | ); 58 | 59 | const styles = StyleSheet.create({ 60 | container: { 61 | flex: 1, 62 | alignItems: 'center', 63 | justifyContent: 'center', 64 | }, 65 | navigation: { 66 | flexDirection: 'row', 67 | margin: 10, 68 | }, 69 | content: { 70 | flex: 1, 71 | width: '100%', 72 | }, 73 | }); 74 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/services/CardService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce.services; 8 | 9 | import android.content.Context; 10 | import android.nfc.cardemulation.HostApduService; 11 | import android.os.Bundle; 12 | import android.util.Log; 13 | 14 | import com.reactnativehce.utils.ApduHelper; 15 | import com.reactnativehce.managers.HceViewModel; 16 | import com.reactnativehce.IHCEApplication; 17 | import com.reactnativehce.managers.PrefManager; 18 | import com.reactnativehce.apps.nfc.NFCTagType4; 19 | 20 | import java.util.ArrayList; 21 | 22 | public class CardService extends HostApduService { 23 | private static final String TAG = "CardService"; 24 | 25 | private final ArrayList registeredHCEApplications = new ArrayList<>(); 26 | private IHCEApplication currentHCEApplication = null; 27 | 28 | @Override 29 | public byte[] processCommandApdu(byte[] command, Bundle extras) { 30 | if (currentHCEApplication != null) { 31 | return currentHCEApplication.processCommand(command); 32 | } 33 | 34 | if (ApduHelper.commandByRangeEquals(command, 0, 4, ApduHelper.C_APDU_SELECT_APP)) { 35 | for (IHCEApplication app : registeredHCEApplications) { 36 | if (app.assertSelectCommand(command)) { 37 | currentHCEApplication = app; 38 | return ApduHelper.R_APDU_OK; 39 | } 40 | } 41 | } 42 | 43 | return ApduHelper.R_APDU_ERROR; 44 | } 45 | 46 | @Override 47 | public void onCreate() { 48 | Log.d(TAG, "Starting service"); 49 | Context context = getApplicationContext(); 50 | 51 | registeredHCEApplications.add(new NFCTagType4( 52 | PrefManager.getInstance(context), 53 | HceViewModel.getInstance(context) 54 | )); 55 | } 56 | 57 | @Override 58 | public void onDeactivated(int reason) { 59 | Log.d(TAG, "Finishing service: " + reason); 60 | this.currentHCEApplication.onDestroy(reason); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. 4 | 5 | ## Development workflow 6 | 7 | To get started with the project, run `npm install` in the root directory to install the required dependencies for each package: 8 | 9 | ```sh 10 | npm install 11 | ``` 12 | 13 | While developing, you can run the [example app](/example/) to test your changes. 14 | 15 | 16 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 17 | 18 | ```sh 19 | npm run lint 20 | ``` 21 | 22 | Remember to add tests for your change if possible. Run the unit tests by: 23 | 24 | ```sh 25 | npm run test 26 | ``` 27 | 28 | To edit the Objective-C files, open `example/ios/HceExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-hce`. 29 | 30 | To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativehce` under `Android`. 31 | 32 | ### Commit message convention 33 | 34 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 35 | 36 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 37 | - `feat`: new features, e.g. add new method to the module. 38 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 39 | - `docs`: changes into documentation, e.g. add usage example for the module.. 40 | - `test`: adding or updating tests, eg add integration tests using detox. 41 | - `chore`: tooling changes, e.g. change CI config. 42 | 43 | Our pre-commit hooks verify that your commit message matches this format when committing. 44 | 45 | ### Sending a pull request 46 | 47 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github). 48 | 49 | When you're sending a pull request: 50 | 51 | - Prefer small pull requests focused on one change. 52 | - Verify that linters and tests are passing. 53 | - Review the documentation to make sure it looks good. 54 | - Follow the pull request template when opening a pull request. 55 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 56 | -------------------------------------------------------------------------------- /android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/managers/EventManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce.managers; 8 | 9 | import android.os.Handler; 10 | import android.os.Looper; 11 | import android.util.Log; 12 | 13 | import androidx.annotation.Nullable; 14 | import androidx.lifecycle.Observer; 15 | 16 | import com.facebook.react.bridge.ReactApplicationContext; 17 | import com.facebook.react.modules.core.DeviceEventManagerModule; 18 | 19 | import java.util.HashSet; 20 | 21 | public class EventManager { 22 | public static final String TAG = "EventManager"; 23 | private static EventManager instance = null; 24 | private final HashSet observedEvents; 25 | private ReactApplicationContext context; 26 | private HceViewModel model; 27 | 28 | public final static String EVENT_STATE = "hceState"; 29 | 30 | final Observer observer = new Observer() { 31 | @Override 32 | public void onChanged(@Nullable final String lastState) { 33 | try { 34 | context 35 | .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) 36 | .emit(EVENT_STATE, lastState); 37 | } catch (Exception e) { 38 | Log.w(TAG, "There was a problem when attempting to send event to RN bridge: " + e.getMessage()); 39 | } 40 | } 41 | }; 42 | 43 | public EventManager() { 44 | observedEvents = new HashSet<>(); 45 | } 46 | 47 | public void setContext(ReactApplicationContext context) { 48 | this.context = context; 49 | } 50 | 51 | public static EventManager getInstance(ReactApplicationContext c) { 52 | if (instance == null) { 53 | instance = new EventManager(); 54 | } 55 | 56 | instance.setContext(c); 57 | 58 | return instance; 59 | } 60 | 61 | public void addListener(String eventName) { 62 | if (observedEvents.contains(eventName)) { 63 | return; 64 | } 65 | 66 | observedEvents.add(eventName); 67 | 68 | if (this.model == null) { 69 | this.model = HceViewModel.getInstance(context.getApplicationContext()); 70 | } 71 | 72 | new Handler(Looper.getMainLooper()) 73 | .post(() -> this.model.getLastState().observeForever(observer)); 74 | } 75 | 76 | public void clear() { 77 | observedEvents.clear(); 78 | 79 | if (this.model == null) { 80 | return; 81 | } 82 | 83 | new Handler(Looper.getMainLooper()) 84 | .post(() -> this.model.getLastState().removeObserver(observer)); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/apps/nfc/NdefEntity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce.apps.nfc; 8 | 9 | import android.nfc.NdefMessage; 10 | import android.nfc.NdefRecord; 11 | 12 | import java.math.BigInteger; 13 | import java.util.Arrays; 14 | 15 | import com.reactnativehce.utils.ByteArrayOperations; 16 | 17 | public class NdefEntity { 18 | private final NdefMessage message; 19 | private final String type; 20 | private final String content; 21 | 22 | public NdefEntity(String type, String content) { 23 | this.type = type; 24 | this.content = content; 25 | 26 | NdefRecord record; 27 | 28 | if (type.equals("text")) { 29 | record = NdefRecord.createTextRecord("en", content); 30 | } else if (type.equals("url")) { 31 | record = NdefRecord.createUri(content); 32 | } else { 33 | throw new IllegalArgumentException("Wrong NFC tag content type"); 34 | } 35 | 36 | this.message = new NdefMessage(record); 37 | } 38 | 39 | public String getType() { 40 | return this.type; 41 | } 42 | 43 | public String getContent() { 44 | return this.content; 45 | } 46 | 47 | public byte[] getNdefContent() { 48 | byte[] payload = this.message.toByteArray(); 49 | byte[] messageLength = ByteArrayOperations.fillByteArrayToFixedDimension( 50 | BigInteger.valueOf(this.message.getByteArrayLength()).toByteArray(), 51 | 2 52 | ); 53 | 54 | byte[] fullResponse = new byte[messageLength.length + payload.length]; 55 | System.arraycopy(messageLength, 0, fullResponse, 0, messageLength.length); 56 | System.arraycopy(payload,0, fullResponse, messageLength.length, payload.length); 57 | 58 | return fullResponse; 59 | } 60 | 61 | public static NdefEntity fromBytes(byte[] bytes) throws Exception { 62 | NdefMessage message = new NdefMessage(bytes); 63 | NdefRecord record = message.getRecords()[0]; 64 | 65 | byte[] payload = record.getPayload(); 66 | 67 | if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(record.getType(), NdefRecord.RTD_TEXT)) { 68 | String content = new String(Arrays.copyOfRange(payload, 3, payload.length)); 69 | return new NdefEntity("text", content); 70 | } else if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(record.getType(), NdefRecord.RTD_URI)) { 71 | String content = record.toUri().toString(); 72 | return new NdefEntity("url", content); 73 | } 74 | 75 | throw new Exception("Unexpected NDEF type"); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/utils/BinaryUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Content of "BinaryUtils" class: 3 | * Original source: https://github.com/googlearchive/android-CardEmulation 4 | * 5 | * --- 6 | * 7 | * Copyright (C) 2013 The Android Open Source Project 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | * 21 | */ 22 | 23 | package com.reactnativehce.utils; 24 | 25 | public class BinaryUtils { 26 | /** 27 | * Utility method to convert a byte array to a hexadecimal string. 28 | * 29 | * @param bytes Bytes to convert 30 | * @return String, containing hexadecimal representation. 31 | */ 32 | public static String ByteArrayToHexString(byte[] bytes) { 33 | final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; 34 | char[] hexChars = new char[bytes.length * 2]; // Each byte has two hex characters (nibbles) 35 | int v; 36 | for (int j = 0; j < bytes.length; j++) { 37 | v = bytes[j] & 0xFF; // Cast bytes[j] to int, treating as unsigned value 38 | hexChars[j * 2] = hexArray[v >>> 4]; // Select hex character from upper nibble 39 | hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // Select hex character from lower nibble 40 | } 41 | return new String(hexChars); 42 | } 43 | 44 | /** 45 | * Utility method to convert a hexadecimal string to a byte string. 46 | * 47 | *

Behavior with input strings containing non-hexadecimal characters is undefined. 48 | * 49 | * @param s String containing hexadecimal characters to convert 50 | * @return Byte array generated from input 51 | * @throws java.lang.IllegalArgumentException if input length is incorrect 52 | */ 53 | public static byte[] HexStringToByteArray(String s) throws IllegalArgumentException { 54 | int len = s.length(); 55 | if (len % 2 == 1) { 56 | throw new IllegalArgumentException("Hex string must have even number of characters"); 57 | } 58 | byte[] data = new byte[len / 2]; // Allocate 1 byte per 2 hex characters 59 | for (int i = 0; i < len; i += 2) { 60 | // Convert each character into a integer (base-16), then bit-shift into place 61 | data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) 62 | + Character.digit(s.charAt(i+1), 16)); 63 | } 64 | return data; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-hce", 3 | "version": "0.3.0", 4 | "description": "React Native HCE", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "files": [ 8 | "dist", 9 | "android", 10 | "ios", 11 | "react-native-hce.podspec", 12 | "!lib/typescript/example", 13 | "!**/__tests__", 14 | "!**/__fixtures__", 15 | "!**/__mocks__", 16 | "!**/build", 17 | "!**/.idea", 18 | "!**/.gradle", 19 | "!**/Pods", 20 | "!**/.DS_Store" 21 | ], 22 | "scripts": { 23 | "test": "jest", 24 | "build": "tsc && esbuild ./src/index.ts --bundle --external:react --external:react-native --external:react --outdir=./dist --platform=node --format=esm --allow-overwrite --target=es2017", 25 | "typescript": "tsc --noEmit", 26 | "lint": "eslint \"**/*.{js,ts,tsx}\"", 27 | "docs": "typedoc" 28 | }, 29 | "keywords": [ 30 | "react-native", 31 | "android", 32 | "smartcard", 33 | "nfc", 34 | "hce" 35 | ], 36 | "repository": "https://github.com/appidea/react-native-hce", 37 | "author": "Mateusz Falkowski (https://www.appidea.pl)", 38 | "license": "MIT", 39 | "bugs": { 40 | "url": "https://github.com/appidea/react-native-hce/issues" 41 | }, 42 | "homepage": "https://github.com/appidea/react-native-hce#readme", 43 | "dependencies": { 44 | "@babel/core": "^7.18.13", 45 | "@babel/preset-env": "^7.1.6", 46 | "@types/jest": "^29.5.12", 47 | "jest": "^29.7.0" 48 | }, 49 | "devDependencies": { 50 | "@react-native/eslint-config": "0.74.87", 51 | "@types/react": "^18.3.23", 52 | "esbuild": "^0.25.8", 53 | "eslint": "^8.0.1", 54 | "eslint-config-prettier": "^6.11.0", 55 | "eslint-plugin-prettier": "^3.1.3", 56 | "prettier": "^2.0.5", 57 | "react": "18.2.0", 58 | "react-native": "0.74.5", 59 | "typescript": "5.0.4" 60 | }, 61 | "peerDependencies": { 62 | "react": "*", 63 | "react-native": "*" 64 | }, 65 | "jest": { 66 | "preset": "react-native", 67 | "modulePathIgnorePatterns": [ 68 | "/example/node_modules", 69 | "/dist/" 70 | ] 71 | }, 72 | "eslintConfig": { 73 | "extends": [ 74 | "@react-native-community", 75 | "prettier" 76 | ], 77 | "rules": { 78 | "prettier/prettier": [ 79 | "error", 80 | { 81 | "quoteProps": "consistent", 82 | "singleQuote": true, 83 | "tabWidth": 2, 84 | "trailingComma": "es5", 85 | "useTabs": false 86 | } 87 | ] 88 | } 89 | }, 90 | "eslintIgnore": [ 91 | "node_modules/", 92 | "dist/", 93 | "docs/" 94 | ], 95 | "prettier": { 96 | "quoteProps": "consistent", 97 | "singleQuote": true, 98 | "tabWidth": 2, 99 | "trailingComma": "es5", 100 | "useTabs": false 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /example/src/SetupView.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import React from 'react'; 8 | import { Image, StyleSheet, Switch, Text, TextInput, View } from 'react-native'; 9 | import { Picker } from '@react-native-picker/picker'; 10 | import { NFCTagType4NDEFContentType, NFCTagType4 } from 'react-native-hce'; 11 | import FormRow from './Controls/FormRow'; 12 | import type { DataLayer } from './DataLayerTypes'; 13 | 14 | const logo = require('../../logo.png'); 15 | 16 | const HCEPickerItem: any = Picker.Item; 17 | const HCEPicker: any = Picker; 18 | 19 | const App = ({ nfcTagProps, updateProp }: DataLayer) => ( 20 | 21 | 22 | 23 | 24 | NFC Type4 Tag Emulator - Example Application 25 | 26 | 27 | 28 | 29 | updateProp('type', itemValue)} 33 | > 34 | 41 | 48 | 49 | 50 | 51 | 52 | updateProp('content', text)} 54 | autoCapitalize="none" 55 | spellCheck={false} 56 | value={nfcTagProps.content} 57 | style={styles.fieldContent} 58 | placeholder="Put the content here." 59 | /> 60 | 61 | 62 | 63 | updateProp('writable', !nfcTagProps.writable)} 65 | value={nfcTagProps.writable} 66 | style={styles.fieldWritable} 67 | /> 68 | 69 | 70 | ); 71 | 72 | const styles = StyleSheet.create({ 73 | container: { 74 | flex: 1, 75 | alignItems: 'center', 76 | justifyContent: 'center', 77 | }, 78 | header: { 79 | alignItems: 'center', 80 | marginBottom: 40, 81 | }, 82 | headerLogo: { 83 | height: 160, 84 | aspectRatio: 1.516, 85 | }, 86 | headerText: { 87 | fontWeight: 'bold', 88 | marginTop: 10, 89 | }, 90 | fieldWritable: { 91 | width: 50, 92 | marginVertical: 10, 93 | marginHorizontal: 4, 94 | }, 95 | fieldContent: { 96 | paddingHorizontal: 16, 97 | }, 98 | typePicker: { 99 | height: 50, 100 | }, 101 | }); 102 | 103 | export default App; 104 | -------------------------------------------------------------------------------- /example/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /src/NFCTagType4/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import type { HCEApplication } from '../HCEApplication'; 8 | 9 | /** 10 | * The supported NDEF record types. 11 | */ 12 | export enum NFCTagType4NDEFContentType { 13 | /** Text record represented by ``tnf = TNF_WELL_KNOWN`` and ``rtd = RTD_TEXT`` */ 14 | Text = 'text', 15 | /** URL record represented by ``tnf = TNF_WELL_KNOWN`` and ``rtd = RTD_URI`` */ 16 | URL = 'url', 17 | } 18 | 19 | /** 20 | * Abstraction for the internal NDEF record. 21 | * 22 | * __NOTE__: Not all the NDEF record types specified by NFC Forum are supported for now. 23 | * Find out the currently supported types {@link NFCTagType4NDEFContentType here}. 24 | */ 25 | export interface NFCTagType4NDEFRecord { 26 | /** 27 | * The NDEF type: text or url. 28 | * 29 | * Use the values from {@link NFCTagType4NDEFContentType}. 30 | */ 31 | type: NFCTagType4NDEFContentType; 32 | /** 33 | * The content of a message. 34 | * 35 | * Related to declared type. 36 | * - when ``type === NFCTagType4NDEFContentType.Text``, it should be a plain text (language declared in en)\ 37 | * Example: ``Hello NFC World``. 38 | * - when ``type === NFCTagType4NDEFContentType.URL``, it should be the URL (remember that URL address is such address, which should include the protocol).\ 39 | * Example: ``https://appidea.pl``. 40 | */ 41 | content: string; 42 | /** 43 | * Defines if the tag is writable. 44 | * 45 | * If true, it can be overwritten by calling the adequate APDUs by the card reader. The {@link HCESession.application} property of 46 | * the current session can change in any time. For notification purposes, session will receive 47 | * the specific events (that events of course will not fire, when application is in the background or the main 48 | * activity is not running at all). 49 | */ 50 | writable: boolean; 51 | } 52 | 53 | /** 54 | * Represents the NFC Tag Type 4 application. 55 | * 56 | * You can create the instance by calling the constructor. 57 | */ 58 | export class NFCTagType4 implements HCEApplication { 59 | /** 60 | * Creates a new instance of NFCTagType4 containing an NDEF message. 61 | * @param props Props of the tag 62 | * 63 | * @example 64 | * ``` 65 | * const tag = new NFCTagType4({ 66 | * type: NFCTagType4NDEFContentType.Text, 67 | * content: "Hello NFC World!", 68 | * writable: false 69 | * }); 70 | * ... 71 | * hceSession.setApplication(tag); 72 | * ``` 73 | */ 74 | constructor(props: NFCTagType4NDEFRecord) { 75 | this.type = 'NFCTag'; 76 | this.content = { ...props }; 77 | } 78 | 79 | /** 80 | * The NDEF record - a content of application. 81 | */ 82 | content: NFCTagType4NDEFRecord; 83 | 84 | /** 85 | * Internal unique identifier of application type. 86 | * 87 | * @internal 88 | * @private 89 | */ 90 | type: string; 91 | 92 | /** 93 | * Maps the string to {@link NFCTagType4NDEFContentType}. 94 | * 95 | * @param type 96 | */ 97 | static contentTypeFromString(type: string): NFCTagType4NDEFContentType { 98 | switch (type) { 99 | case 'text': 100 | return NFCTagType4NDEFContentType.Text; 101 | case 'url': 102 | return NFCTagType4NDEFContentType.URL; 103 | default: 104 | throw new Error('Unknown type'); 105 | } 106 | } 107 | 108 | /** 109 | * Maps the {@link NFCTagType4NDEFContentType} to string. 110 | * 111 | * @param type 112 | */ 113 | static stringFromContentType(type: NFCTagType4NDEFContentType): string { 114 | switch (type) { 115 | case NFCTagType4NDEFContentType.URL: 116 | return 'url'; 117 | case NFCTagType4NDEFContentType.Text: 118 | return 'text'; 119 | default: 120 | throw new Error('Unknown type'); 121 | } 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | // Buildscript is evaluated before everything else so we can't use getExtOrDefault 3 | def kotlin_version = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : project.properties['Hce_kotlinVersion'] 4 | 5 | repositories { 6 | google() 7 | jcenter() 8 | } 9 | 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:3.5.4' 12 | // noinspection DifferentKotlinGradleVersion 13 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 14 | } 15 | } 16 | 17 | apply plugin: 'com.android.library' 18 | apply plugin: 'kotlin-android' 19 | 20 | def getExtOrDefault(name) { 21 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['Hce_' + name] 22 | } 23 | 24 | def getExtOrIntegerDefault(name) { 25 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties['Hce_' + name]).toInteger() 26 | } 27 | 28 | android { 29 | compileSdkVersion getExtOrIntegerDefault('compileSdkVersion') 30 | buildToolsVersion getExtOrDefault('buildToolsVersion') 31 | defaultConfig { 32 | minSdkVersion 23 33 | targetSdkVersion getExtOrIntegerDefault('targetSdkVersion') 34 | versionCode 1 35 | versionName "1.0" 36 | 37 | } 38 | 39 | buildTypes { 40 | release { 41 | minifyEnabled false 42 | } 43 | } 44 | lintOptions { 45 | disable 'GradleCompatible' 46 | } 47 | compileOptions { 48 | sourceCompatibility JavaVersion.VERSION_1_8 49 | targetCompatibility JavaVersion.VERSION_1_8 50 | } 51 | } 52 | 53 | repositories { 54 | mavenCentral() 55 | jcenter() 56 | google() 57 | 58 | def found = false 59 | def defaultDir = null 60 | def androidSourcesName = 'React Native sources' 61 | 62 | if (rootProject.ext.has('reactNativeAndroidRoot')) { 63 | defaultDir = rootProject.ext.get('reactNativeAndroidRoot') 64 | } else { 65 | defaultDir = new File( 66 | projectDir, 67 | '/../../../node_modules/react-native/android' 68 | ) 69 | } 70 | 71 | if (defaultDir.exists()) { 72 | maven { 73 | url defaultDir.toString() 74 | name androidSourcesName 75 | } 76 | 77 | logger.info(":${project.name}:reactNativeAndroidRoot ${defaultDir.canonicalPath}") 78 | found = true 79 | } else { 80 | def parentDir = rootProject.projectDir 81 | 82 | 1.upto(5, { 83 | if (found) return true 84 | parentDir = parentDir.parentFile 85 | 86 | def androidSourcesDir = new File( 87 | parentDir, 88 | 'node_modules/react-native' 89 | ) 90 | 91 | def androidPrebuiltBinaryDir = new File( 92 | parentDir, 93 | 'node_modules/react-native/android' 94 | ) 95 | 96 | if (androidPrebuiltBinaryDir.exists()) { 97 | maven { 98 | url androidPrebuiltBinaryDir.toString() 99 | name androidSourcesName 100 | } 101 | 102 | logger.info(":${project.name}:reactNativeAndroidRoot ${androidPrebuiltBinaryDir.canonicalPath}") 103 | found = true 104 | } else if (androidSourcesDir.exists()) { 105 | maven { 106 | url androidSourcesDir.toString() 107 | name androidSourcesName 108 | } 109 | 110 | logger.info(":${project.name}:reactNativeAndroidRoot ${androidSourcesDir.canonicalPath}") 111 | found = true 112 | } 113 | }) 114 | } 115 | 116 | if (!found) { 117 | throw new GradleException( 118 | "${project.name}: unable to locate React Native android sources. " + 119 | "Ensure you have you installed React Native as a dependency in your project and try again." 120 | ) 121 | } 122 | } 123 | 124 | def kotlin_version = getExtOrDefault('kotlinVersion') 125 | 126 | dependencies { 127 | def lifecycle_version = "2.4.0" 128 | 129 | // noinspection GradleDynamicVersion 130 | api 'com.facebook.react:react-native:+' 131 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 132 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" 133 | implementation "androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycle_version" 134 | } 135 | -------------------------------------------------------------------------------- /example/src/useDataLayer.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import { useCallback, useContext, useEffect, useRef, useState } from 'react'; 8 | import { 9 | HCESessionContext, 10 | HCESession, 11 | NFCTagType4NDEFContentType, 12 | NFCTagType4, 13 | } from 'react-native-hce'; 14 | import type { 15 | DataLayer, 16 | NFCTagReactStateProps, 17 | LogEntry, 18 | } from './DataLayerTypes'; 19 | 20 | const defaultProps: NFCTagReactStateProps = { 21 | content: '', 22 | type: NFCTagType4.stringFromContentType(NFCTagType4NDEFContentType.Text), 23 | writable: false, 24 | _pristine: true, 25 | }; 26 | 27 | const createLogEntry = (eventName: string): LogEntry => ({ 28 | time: new Date().toISOString(), 29 | message: eventName, 30 | }); 31 | 32 | /** 33 | * The hook encapsulating the data management layer. 34 | */ 35 | const useDataLayer = (): DataLayer => { 36 | const { session } = useContext(HCESessionContext); 37 | const [loading, setLoading] = useState(false); 38 | 39 | // ** Following section of code is responsible for: ** 40 | // Management of "Enabled" field state in the application 41 | const [enabled, setEnabled] = useState(false); 42 | 43 | const switchSession = useCallback( 44 | async (enable) => { 45 | setLoading(true); 46 | await session.setEnabled(enable); 47 | setEnabled(enable); 48 | setLoading(false); 49 | }, 50 | [setLoading, session, setEnabled] 51 | ); 52 | 53 | // ** Following section of code is responsible for: ** 54 | // Management of "HCE Application" - related fields state in the application 55 | const [nfcTagProps, setNfcTagProps] = 56 | useState(defaultProps); 57 | 58 | const updateProp = useCallback( 59 | (prop: string, value: any) => { 60 | setNfcTagProps((state: any) => ({ 61 | ...state, 62 | [prop]: value, 63 | _pristine: false, 64 | })); 65 | }, 66 | [setNfcTagProps] 67 | ); 68 | 69 | // ** Following section of code is responsible for: ** 70 | // Synchronization of state: APPLICATION ---> LIBRARY. 71 | const timeout = useRef>(); 72 | 73 | const updateTag = useCallback( 74 | async (localNfcTagProps) => { 75 | setLoading(true); 76 | 77 | const tag = new NFCTagType4({ 78 | type: NFCTagType4.contentTypeFromString(localNfcTagProps.type), 79 | content: localNfcTagProps.content, 80 | writable: localNfcTagProps.writable, 81 | }); 82 | await session.setApplication(tag); 83 | 84 | setLoading(false); 85 | }, 86 | [setLoading, session] 87 | ); 88 | 89 | useEffect(() => { 90 | if (!nfcTagProps._pristine) { 91 | const boundUpdateTag = updateTag.bind(null, nfcTagProps); 92 | timeout.current = setTimeout(boundUpdateTag, 600); 93 | } 94 | 95 | return () => clearTimeout(timeout.current); 96 | }, [nfcTagProps, updateTag]); 97 | 98 | // ** Following section of code is responsible for: ** 99 | // Synchronization of state: LIBRARY ---> APPLICATION. 100 | const updateApp = useCallback(() => { 101 | const application = session.application; 102 | 103 | if (application === null) { 104 | return; 105 | } 106 | 107 | setNfcTagProps({ 108 | type: application.content.type, 109 | content: application.content.content, 110 | writable: application.content.writable, 111 | _pristine: true, 112 | }); 113 | 114 | setEnabled(session.enabled); 115 | }, [session, setNfcTagProps, setEnabled]); 116 | 117 | useEffect(() => { 118 | const cancelSubscription = session.on( 119 | HCESession.Events.HCE_STATE_WRITE_FULL, 120 | updateApp 121 | ); 122 | updateApp(); 123 | 124 | return () => cancelSubscription(); 125 | }, [session, setNfcTagProps, setEnabled, updateApp]); 126 | 127 | // ** Following section of code is responsible for: ** 128 | // Logging the events to preview in "Events" pane. 129 | const [log, setLog] = useState>([]); 130 | 131 | const logger = useCallback( 132 | (eventData) => { 133 | setLog((msg) => [...msg, createLogEntry(eventData)]); 134 | }, 135 | [setLog] 136 | ); 137 | 138 | useEffect(() => { 139 | const cancelSubscription = session.on(null, logger); 140 | return () => cancelSubscription(); 141 | }, [session, logger]); 142 | 143 | // ** Following section of code is responsible for: ** 144 | // Returning the hook result. 145 | return { nfcTagProps, updateProp, switchSession, log, enabled, loading }; 146 | }; 147 | 148 | export default useDataLayer; 149 | -------------------------------------------------------------------------------- /example/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.application" 2 | apply plugin: "org.jetbrains.kotlin.android" 3 | apply plugin: "com.facebook.react" 4 | 5 | /** 6 | * This is the configuration block to customize your React Native Android app. 7 | * By default you don't need to apply any configuration, just uncomment the lines you need. 8 | */ 9 | react { 10 | /* Folders */ 11 | // The root of your project, i.e. where "package.json" lives. Default is '..' 12 | // root = file("../") 13 | // The folder where the react-native NPM package is. Default is ../node_modules/react-native 14 | // reactNativeDir = file("../node_modules/react-native") 15 | // The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen 16 | // codegenDir = file("../node_modules/@react-native/codegen") 17 | // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js 18 | // cliFile = file("../node_modules/react-native/cli.js") 19 | 20 | /* Variants */ 21 | // The list of variants to that are debuggable. For those we're going to 22 | // skip the bundling of the JS bundle and the assets. By default is just 'debug'. 23 | // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. 24 | // debuggableVariants = ["liteDebug", "prodDebug"] 25 | 26 | /* Bundling */ 27 | // A list containing the node command and its flags. Default is just 'node'. 28 | // nodeExecutableAndArgs = ["node"] 29 | // 30 | // The command to run when bundling. By default is 'bundle' 31 | // bundleCommand = "ram-bundle" 32 | // 33 | // The path to the CLI configuration file. Default is empty. 34 | // bundleConfig = file(../rn-cli.config.js) 35 | // 36 | // The name of the generated asset file containing your JS bundle 37 | // bundleAssetName = "MyApplication.android.bundle" 38 | // 39 | // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' 40 | // entryFile = file("../js/MyApplication.android.js") 41 | // 42 | // A list of extra flags to pass to the 'bundle' commands. 43 | // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle 44 | // extraPackagerArgs = [] 45 | 46 | /* Hermes Commands */ 47 | // The hermes compiler command to run. By default it is 'hermesc' 48 | // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" 49 | // 50 | // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" 51 | // hermesFlags = ["-O", "-output-source-map"] 52 | } 53 | 54 | /** 55 | * Set this to true to Run Proguard on Release builds to minify the Java bytecode. 56 | */ 57 | def enableProguardInReleaseBuilds = false 58 | 59 | /** 60 | * The preferred build flavor of JavaScriptCore (JSC) 61 | * 62 | * For example, to use the international variant, you can use: 63 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` 64 | * 65 | * The international variant includes ICU i18n library and necessary data 66 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that 67 | * give correct results when using with locales other than en-US. Note that 68 | * this variant is about 6MiB larger per architecture than default. 69 | */ 70 | def jscFlavor = 'org.webkit:android-jsc:+' 71 | 72 | android { 73 | ndkVersion rootProject.ext.ndkVersion 74 | buildToolsVersion rootProject.ext.buildToolsVersion 75 | compileSdk rootProject.ext.compileSdkVersion 76 | 77 | buildFeatures { 78 | aidl true 79 | } 80 | 81 | namespace "com.example.reactnativehce" 82 | defaultConfig { 83 | applicationId "com.example.reactnativehce" 84 | minSdkVersion rootProject.ext.minSdkVersion 85 | targetSdkVersion rootProject.ext.targetSdkVersion 86 | versionCode 8 87 | versionName "1.7" 88 | 89 | javaCompileOptions { 90 | annotationProcessorOptions { 91 | arguments += ["room.schemaLocation": "$projectDir/schemas".toString()] 92 | } 93 | } 94 | } 95 | signingConfigs { 96 | debug { 97 | storeFile file('debug.keystore') 98 | storePassword 'android' 99 | keyAlias 'androiddebugkey' 100 | keyPassword 'android' 101 | } 102 | } 103 | buildTypes { 104 | debug { 105 | signingConfig signingConfigs.debug 106 | } 107 | release { 108 | signingConfig signingConfigs.debug 109 | } 110 | } 111 | } 112 | 113 | dependencies { 114 | // The version of react-native is set by the React Native Gradle Plugin 115 | implementation("com.facebook.react:react-android") 116 | implementation project(':react-native-hce') 117 | 118 | if (hermesEnabled.toBoolean()) { 119 | implementation("com.facebook.react:hermes-android") 120 | } else { 121 | implementation jscFlavor 122 | } 123 | 124 | } 125 | 126 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) 127 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/HceModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce; 8 | 9 | import android.content.ComponentName; 10 | import android.content.pm.PackageManager; 11 | 12 | import com.facebook.react.bridge.Arguments; 13 | import com.facebook.react.bridge.ReactApplicationContext; 14 | import com.facebook.react.bridge.ReactContextBaseJavaModule; 15 | import com.facebook.react.bridge.ReactMethod; 16 | import com.facebook.react.bridge.Promise; 17 | import com.facebook.react.bridge.ReadableMap; 18 | import com.facebook.react.bridge.WritableMap; 19 | import com.reactnativehce.managers.EventManager; 20 | import com.reactnativehce.managers.HceViewModel; 21 | import com.reactnativehce.managers.PrefManager; 22 | import com.reactnativehce.services.CardService; 23 | 24 | import androidx.annotation.NonNull; 25 | 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | 29 | public class HceModule extends ReactContextBaseJavaModule { 30 | private static ReactApplicationContext reactContext; 31 | private final EventManager eventManager; 32 | private final PrefManager prefManager; 33 | private final HceViewModel hceModel; 34 | 35 | HceModule(ReactApplicationContext context) { 36 | super(context); 37 | reactContext = context; 38 | eventManager = EventManager.getInstance(context); 39 | prefManager = PrefManager.getInstance(context.getApplicationContext()); 40 | hceModel = HceViewModel.getInstance(context.getApplicationContext()); 41 | 42 | if (prefManager.exists()) { 43 | this.enableHceService(prefManager.getEnabled()); 44 | } 45 | } 46 | 47 | @NonNull 48 | @Override 49 | public String getName() { 50 | return "Hce"; 51 | } 52 | 53 | @Override 54 | public Map getConstants() { 55 | final Map constants = new HashMap<>(); 56 | constants.put("HCE_STATE_CONNECTED", HceViewModel.HCE_STATE_CONNECTED); 57 | constants.put("HCE_STATE_DISCONNECTED", HceViewModel.HCE_STATE_DISCONNECTED); 58 | constants.put("HCE_STATE_ENABLED", HceViewModel.HCE_STATE_ENABLED); 59 | constants.put("HCE_STATE_DISABLED", HceViewModel.HCE_STATE_DISABLED); 60 | constants.put("HCE_STATE_READ", HceViewModel.HCE_STATE_READ); 61 | constants.put("HCE_STATE_WRITE_FULL", HceViewModel.HCE_STATE_WRITE_FULL); 62 | constants.put("HCE_STATE_WRITE_PARTIAL", HceViewModel.HCE_STATE_WRITE_PARTIAL); 63 | constants.put("HCE_STATE_UPDATE_APPLICATION", HceViewModel.HCE_STATE_UPDATE_APPLICATION); 64 | return constants; 65 | } 66 | 67 | @ReactMethod 68 | @SuppressWarnings("unused") 69 | public void addListener(String eventName) throws Exception { 70 | if (!eventName.equals(EventManager.EVENT_STATE)) { 71 | throw new Exception("Event not supported: " + eventName); 72 | } 73 | 74 | this.eventManager.addListener(EventManager.EVENT_STATE); 75 | } 76 | 77 | @ReactMethod 78 | @SuppressWarnings("unused") 79 | public void removeListeners(Integer count) { 80 | this.eventManager.clear(); 81 | } 82 | 83 | @ReactMethod 84 | @SuppressWarnings("unused") 85 | public void setContent(ReadableMap properties, Promise promise) { 86 | prefManager.setType(properties.getString("type")); 87 | prefManager.setContent(properties.getString("content")); 88 | prefManager.setWritable(properties.getBoolean("writable")); 89 | this.hceModel.getLastState() 90 | .postValue(HceViewModel.HCE_STATE_UPDATE_APPLICATION); 91 | 92 | promise.resolve(null); 93 | } 94 | 95 | @ReactMethod 96 | @SuppressWarnings("unused") 97 | public void getContent(Promise promise) { 98 | if (!prefManager.exists()) { 99 | promise.resolve(null); 100 | return; 101 | } 102 | 103 | WritableMap properties = Arguments.createMap(); 104 | properties.putString("type", prefManager.getType()); 105 | properties.putString("content", prefManager.getContent()); 106 | properties.putBoolean("writable", prefManager.getWritable()); 107 | 108 | promise.resolve(properties); 109 | } 110 | 111 | private void enableHceService(Boolean enabled) { 112 | reactContext.getApplicationContext().getPackageManager() 113 | .setComponentEnabledSetting( 114 | new ComponentName(reactContext.getApplicationContext(), CardService.class), 115 | enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 116 | PackageManager.DONT_KILL_APP 117 | ); 118 | 119 | this.hceModel.getLastState() 120 | .postValue(enabled ? HceViewModel.HCE_STATE_ENABLED : HceViewModel.HCE_STATE_DISABLED); 121 | } 122 | 123 | @ReactMethod 124 | @SuppressWarnings("unused") 125 | public void getEnabled(Promise promise) { 126 | promise.resolve(prefManager.getEnabled()); 127 | } 128 | 129 | @ReactMethod 130 | @SuppressWarnings("unused") 131 | public void setEnabled(Boolean enabled, Promise promise) { 132 | this.prefManager.setEnabled(enabled); 133 | this.enableHceService(enabled); 134 | promise.resolve(enabled); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/apps/nfc/NFCTagType4.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | package com.reactnativehce.apps.nfc; 8 | 9 | import android.util.Log; 10 | 11 | import com.reactnativehce.utils.ApduHelper; 12 | import com.reactnativehce.managers.HceViewModel; 13 | import com.reactnativehce.managers.PrefManager; 14 | import com.reactnativehce.utils.BinaryUtils; 15 | import com.reactnativehce.IHCEApplication; 16 | 17 | import java.util.Arrays; 18 | 19 | public class NFCTagType4 implements IHCEApplication { 20 | private static final String TAG = "NFCTag"; 21 | private static final byte[] C_APDU_SELECT = BinaryUtils.HexStringToByteArray("00A4040007D276000085010100"); 22 | private static final byte[] FILENAME_CC = BinaryUtils.HexStringToByteArray("E103"); 23 | private static final byte[] FILENAME_NDEF = BinaryUtils.HexStringToByteArray("E104"); 24 | private static final byte[] CC_HEADER = BinaryUtils.HexStringToByteArray("000F20010000FF"); 25 | private final PrefManager prefManager; 26 | private final HceViewModel hceModel; 27 | 28 | private SelectedFile selectedFile = null; 29 | public final byte[] ndefDataBuffer = new byte[0x7FFF]; 30 | public final byte[] ccDataBuffer = new byte[0x000F]; 31 | 32 | private enum SelectedFile { 33 | FILENAME_CC, 34 | FILENAME_NDEF 35 | } 36 | 37 | public NFCTagType4(PrefManager prefManager, HceViewModel model) { 38 | this.prefManager = prefManager; 39 | this.hceModel = model; 40 | 41 | this.setUpNdefContent(); 42 | this.setUpCapabilityContainerContent(); 43 | } 44 | 45 | private void setUpNdefContent() { 46 | byte[] ndef = (new NdefEntity(prefManager.getType(), prefManager.getContent())).getNdefContent(); 47 | System.arraycopy(ndef,0, this.ndefDataBuffer,0,ndef.length ); 48 | } 49 | 50 | private void setUpCapabilityContainerContent() { 51 | System.arraycopy(CC_HEADER, 0, this.ccDataBuffer, 0, CC_HEADER.length); 52 | byte[] controlTlv = BinaryUtils.HexStringToByteArray("0406E1047FFF00" + (prefManager.getWritable() ? "00":"FF")); 53 | System.arraycopy(controlTlv, 0, this.ccDataBuffer, CC_HEADER.length, controlTlv.length); 54 | } 55 | 56 | private byte[] getFullResponseByFile() { 57 | switch (selectedFile) { 58 | case FILENAME_CC: 59 | return this.ccDataBuffer; 60 | case FILENAME_NDEF: 61 | return this.ndefDataBuffer; 62 | default: 63 | throw new Error("Unknown file"); 64 | } 65 | } 66 | 67 | public boolean assertSelectCommand(byte[] command) { 68 | Boolean result = ApduHelper.commandByRangeEquals(command, 0, 13, C_APDU_SELECT); 69 | 70 | if (result) { 71 | this.hceModel.getLastState().setValue(HceViewModel.HCE_STATE_CONNECTED); 72 | } 73 | 74 | return result; 75 | } 76 | 77 | private byte[] respondSelectFile(byte[] command) { 78 | byte[] file = Arrays.copyOfRange(command, 5, 7); 79 | 80 | if (Arrays.equals(file, FILENAME_CC)) { 81 | this.selectedFile = SelectedFile.FILENAME_CC; 82 | } else if (Arrays.equals(file, FILENAME_NDEF)) { 83 | this.selectedFile = SelectedFile.FILENAME_NDEF; 84 | } 85 | 86 | if (this.selectedFile != null) { 87 | return ApduHelper.R_APDU_OK; 88 | } 89 | 90 | return ApduHelper.R_APDU_ERROR; 91 | } 92 | 93 | private byte[] respondRead(byte[] command) { 94 | if (this.selectedFile == null) { 95 | return ApduHelper.R_APDU_ERROR; 96 | } 97 | 98 | int offset = Integer.parseInt(BinaryUtils.ByteArrayToHexString(Arrays.copyOfRange(command, 2, 4)), 16); 99 | int length = Integer.parseInt(BinaryUtils.ByteArrayToHexString(Arrays.copyOfRange(command, 4, 5)), 16); 100 | 101 | byte[] fullResponse = getFullResponseByFile(); 102 | byte[] slicedResponse = Arrays.copyOfRange(fullResponse, offset, fullResponse.length); 103 | 104 | int realLength = Math.min(slicedResponse.length, length); 105 | byte[] response = new byte[realLength + ApduHelper.R_APDU_OK.length]; 106 | 107 | System.arraycopy(slicedResponse, 0, response, 0, realLength); 108 | System.arraycopy(ApduHelper.R_APDU_OK, 0, response, realLength, ApduHelper.R_APDU_OK.length); 109 | 110 | this.hceModel.getLastState() 111 | .setValue(HceViewModel.HCE_STATE_READ); 112 | 113 | return response; 114 | } 115 | 116 | private NdefEntity tryHandleSavedTag() { 117 | NdefEntity nm; 118 | 119 | try { 120 | int nlen = Integer.parseInt(BinaryUtils.ByteArrayToHexString(Arrays.copyOfRange(this.ndefDataBuffer, 0, 2)), 16); 121 | nm = NdefEntity.fromBytes(Arrays.copyOfRange(this.ndefDataBuffer, 2, 2 + nlen)); 122 | } catch (Exception e) { 123 | return null; 124 | } 125 | 126 | return nm; 127 | } 128 | 129 | private byte[] respondWrite(byte[] command) { 130 | if (this.selectedFile != SelectedFile.FILENAME_NDEF) { 131 | return ApduHelper.R_APDU_ERROR; 132 | } 133 | 134 | int offset = Integer.parseInt(BinaryUtils.ByteArrayToHexString(Arrays.copyOfRange(command, 2, 4)), 16); 135 | int length = Integer.parseInt(BinaryUtils.ByteArrayToHexString(Arrays.copyOfRange(command, 4, 5)), 16); 136 | 137 | byte[] data = Arrays.copyOfRange(command, 5, 5 + length); 138 | System.arraycopy(data, 0, ndefDataBuffer, offset, length); 139 | 140 | NdefEntity nm = this.tryHandleSavedTag(); 141 | 142 | if (nm != null) { 143 | this.prefManager.setContent(nm.getContent()); 144 | this.prefManager.setType(nm.getType()); 145 | this.hceModel.getLastState() 146 | .setValue(HceViewModel.HCE_STATE_WRITE_FULL); 147 | this.hceModel.getLastState() 148 | .setValue(HceViewModel.HCE_STATE_UPDATE_APPLICATION); 149 | } else { 150 | this.hceModel.getLastState() 151 | .setValue(HceViewModel.HCE_STATE_WRITE_PARTIAL); 152 | } 153 | 154 | return ApduHelper.R_APDU_OK; 155 | } 156 | 157 | public byte[] processCommand(byte[] command) { 158 | if (ApduHelper.commandByRangeEquals(command, 0, 5, ApduHelper.C_APDU_SELECT_FILE)) { 159 | return this.respondSelectFile(command); 160 | } 161 | 162 | if (ApduHelper.commandByRangeEquals(command, 0, 2, ApduHelper.C_APDU_READ)) { 163 | return this.respondRead(command); 164 | } 165 | 166 | if (ApduHelper.commandByRangeEquals(command, 0, 2, ApduHelper.C_APDU_WRITE)) { 167 | return this.respondWrite(command); 168 | } 169 | 170 | Log.i(TAG, "Unknown command."); 171 | 172 | return ApduHelper.R_APDU_ERROR; 173 | } 174 | 175 | @Override 176 | public void onDestroy(int reason) { 177 | this.hceModel.getLastState() 178 | .setValue(HceViewModel.HCE_STATE_DISCONNECTED); 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/HCESession.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-2022 Mateusz Falkowski (appidea.pl) and contributors. All rights reserved. 3 | * This file is part of "react-native-hce" library: https://github.com/appidea/react-native-hce 4 | * Licensed under the MIT license. See LICENSE file in the project root for details. 5 | */ 6 | 7 | import { NativeEventEmitter, NativeModules, Platform } from 'react-native'; 8 | import type { HCEApplication } from './HCEApplication'; 9 | import { NFCTagType4 } from './NFCTagType4'; 10 | 11 | const { Hce: NativeHce } = NativeModules; 12 | const eventEmitter = new NativeEventEmitter(NativeHce); 13 | 14 | let instance: HCESession | null = null; 15 | 16 | const checkPlatform = (): void => { 17 | if (Platform.OS !== 'android') { 18 | throw new Error('react-native-hce does not support this platform'); 19 | } 20 | }; 21 | 22 | /** 23 | * This interface defines a HCESession constants container object describing a state changes in the emulation. 24 | * The object itself can be accessed in ``HCESession.Events`` static property. 25 | * 26 | * @enum 27 | */ 28 | export interface HCESessionEvents { 29 | /** When HCE transaction is routed to the application. */ 30 | HCE_STATE_CONNECTED: string; 31 | /** When HCE transaction is terminated */ 32 | HCE_STATE_DISCONNECTED: string; 33 | /** When HCE service has been made available to the OS */ 34 | HCE_STATE_ENABLED: string; 35 | /** When HCE service has been made unavailable to the OS */ 36 | HCE_STATE_DISABLED: string; 37 | /** When a NFC Tag has been read by the reader */ 38 | HCE_STATE_READ: string; 39 | /** When a NFC Tag has been written and contains a valid NDEF record */ 40 | HCE_STATE_WRITE_FULL: string; 41 | /** When a NFC Tag writing is in progress but it's not yet correctly finalized (does not contain valid NDEF record yet). */ 42 | HCE_STATE_WRITE_PARTIAL: string; 43 | /** When a NFC Tag NDEF record has been changed, due to write or just request of content change in the library. */ 44 | HCE_STATE_UPDATE_APPLICATION: string; 45 | } 46 | 47 | /** 48 | * The HCESession listener. Parameter for {@link HCESession.on} method. 49 | */ 50 | export type HCESessionEventListener = (eventData?: string) => void; 51 | 52 | /** 53 | * The HCESession listener cancellation method. Used as a return valu of {@link HCESession.on} method. 54 | */ 55 | export type HCESessionEventListenerCancel = () => void; 56 | 57 | /** 58 | * @internal 59 | */ 60 | interface HCESessionListenerDescription { 61 | event: string | null; 62 | listener: HCESessionEventListener; 63 | } 64 | 65 | /** 66 | * Class for the session state management. 67 | * 68 | * HCESession is an entry point for the react-native-hce library. 69 | * This class manages the entire connection with native counterparts managing the HCE emulation. 70 | * 71 | * __You should use only one instance__ of the class should be used per application. That's why we created it with the intention 72 | * of use as a singleton. __To get the instance, use the {@link getInstance} static method__ that will get a current instance and will do the synchronization with native for You. 73 | */ 74 | export class HCESession { 75 | /** 76 | * The current subject application to emulate in HCE. 77 | * 78 | * __NOTE__: Do not set the current application by assigning to this property. 79 | * Use the {@link setApplication} instead. 80 | */ 81 | application: HCEApplication | null; 82 | 83 | /** 84 | * Is the HCE Service currently enabled and visible to OS. 85 | * 86 | * __NOTE__: Do not set the current state by assigning to this property. 87 | * Use the {@link setEnabled} instead. 88 | */ 89 | enabled: boolean; 90 | 91 | /** 92 | * Container for class' event listeners. 93 | * 94 | * @internal 95 | * @private 96 | */ 97 | stateListeners: (HCESessionListenerDescription | null)[]; 98 | 99 | /** 100 | * Object that contains the events that the application can listen to using ``HCESession.on(...)``. 101 | * 102 | * Check the {@link HCESessionEvents} interface to get the listing of availble events. 103 | * 104 | * @example Usage of the property in event listener: 105 | * ``` 106 | * hceSession.on(HCESession.Events.HCE_CONNECTED) 107 | * ``` 108 | */ 109 | static Events: HCESessionEvents = NativeHce.getConstants(); 110 | 111 | /** 112 | * Creates the instance of HCE Session class. 113 | * 114 | * __NOTE!!!: Do not use this constructor directly. Use {@link getInstance} to get the appropriate and synchronized instance.__ 115 | */ 116 | constructor() { 117 | this.enabled = false; 118 | this.application = null; 119 | this.stateListeners = []; 120 | 121 | this.addListener('hceState', this.handleStateUpdate.bind(this)); 122 | } 123 | 124 | /** 125 | * Gets the instance of HCE Session. 126 | * 127 | * As there is only one HCE Session per application available, 128 | * use this function to get the instance instead of using the constructor. 129 | */ 130 | static async getInstance(): Promise { 131 | checkPlatform(); 132 | 133 | if (instance !== null) { 134 | return instance; 135 | } 136 | 137 | instance = new HCESession(); 138 | await instance.syncApplication(); 139 | 140 | return instance; 141 | } 142 | 143 | /** 144 | * Internal method for synchronization with native module. 145 | * 146 | * @internal 147 | * @private 148 | * @param incomingEvent Native module event parameter 149 | */ 150 | async handleStateUpdate(incomingEvent: string) { 151 | if (incomingEvent === HCESession.Events.HCE_STATE_WRITE_FULL) { 152 | await this.syncApplication(); 153 | } 154 | 155 | this.stateListeners 156 | .filter((i): i is HCESessionListenerDescription => i !== null) 157 | .forEach(({ event, listener }) => { 158 | if (event === null || event === incomingEvent) { 159 | listener(); 160 | } 161 | }); 162 | } 163 | 164 | /** 165 | * Adds event listener to the HCE Session. 166 | * 167 | * @param event The event that application should listen to. You should pass the constant from static {@link HCESession.Events} property. 168 | * If null, the listener will respond to all events - that can be usable for logging purposes. 169 | * @param listener The event listener. 170 | * @return Returns the reference to "stop listening" method. To stop listening the event, just call it. 171 | * 172 | * @example 173 | * ``` 174 | * import { ToastAndroid } from "react-native" 175 | * import { HCESession } from "react-native-hce" 176 | * ... 177 | * const instance = await HCESession.getInstance(); 178 | * const removeListener = instance.on(HCESession.Events.HCE_STATE_READ, () => { 179 | * ToastAndroid.show("The tag has been read! Thank You.", ToastAndroid.LONG); 180 | * removeListener(); 181 | * }; 182 | * ``` 183 | */ 184 | on( 185 | event: string | null, 186 | listener: HCESessionEventListener 187 | ): HCESessionEventListenerCancel { 188 | const index = this.stateListeners.push({ event, listener }); 189 | return () => { 190 | this.stateListeners[index] = null; 191 | }; 192 | } 193 | 194 | /** 195 | * Adds the listener to an event. 196 | * 197 | * @internal 198 | */ 199 | addListener = (eventName: string, callback: (eventData: any) => any) => { 200 | return eventEmitter.addListener(eventName, (eventProp) => { 201 | callback(eventProp); 202 | }); 203 | }; 204 | 205 | /** 206 | * Synchronize the class with current native state. 207 | * 208 | * __NOTE__: You should not use this function normally. 209 | * Internal implementation will call it for You, if needed. 210 | */ 211 | async syncApplication(): Promise { 212 | const content = await NativeHce.getContent(); 213 | 214 | if (!content) { 215 | return; 216 | } 217 | 218 | const enabled = await NativeHce.getEnabled(); 219 | 220 | this.application = new NFCTagType4({ 221 | type: NFCTagType4.contentTypeFromString(content.type), 222 | content: content.content, 223 | writable: content.writable, 224 | }); 225 | 226 | this.enabled = enabled; 227 | } 228 | 229 | /** 230 | * Update the subject application to emulate in HCE. 231 | * 232 | * @param application The application to set, must be instance of HCEApplication. 233 | */ 234 | async setApplication(application: HCEApplication): Promise { 235 | await NativeHce.setContent(application.content); 236 | this.application = application; 237 | } 238 | 239 | /** 240 | * Toggle the state of HCE service. 241 | * 242 | * This function allows to enable or disable the native component of HCE Service. 243 | * If enabled, the native HostApduService will be recognizable by platform's HCE router. 244 | * If not, service won't be recognized, thus all the interactions between HCE and reader won't be available. 245 | * 246 | * __NOTE:__ Before switching the service on, use the {@link setApplication} 247 | * first to register the content that You want to emulate using HCE. 248 | * 249 | * @param enable True to enable the service, false to disable. 250 | */ 251 | setEnabled = async (enable: boolean): Promise => { 252 | if (!this.application && enable) { 253 | throw new Error('No application set!'); 254 | } 255 | 256 | await NativeHce.setEnabled(enable); 257 | this.enabled = enable; 258 | }; 259 | } 260 | -------------------------------------------------------------------------------- /example/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | React Native HCE 3 |

4 |

react-native-hce

5 |

6 | 7 | Adds Host card emulation (HCE) capabilities to React Native 8 | 9 |

10 |

11 | react-native-hce.appidea.pl 12 |

13 | 14 |
15 | We’d love your support! 🚀 16 | 17 | Enjoying this project or using it in your tech stack?
18 | Consider becoming a sponsor 💖 and help us keep building cool stuff. Every bit helps - thanks, friend! 🤓 19 |
20 | 21 | --- 22 | 23 | ![Tag](https://img.shields.io/github/v/tag/appidea/react-native-hce) 24 | [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/appidea/react-native-hce/graphs/commit-activity) 25 | [![Last commit](https://img.shields.io/github/last-commit/appidea/react-native-hce)](https://github.com/appidea/react-native-hce/graphs/commit-activity) 26 | 27 | **Host Card Emulation** is the technology in Android Devices, that let the device act as a host in the NFC communication. This technology can be used, e.g. to simulate the passive smart cards or NFC tags. 28 | This package allows the `react-native` application to use the adventages of this technology. 29 | 30 | For now, the only out-of-the-box solution provided by this package is: 31 | 32 | - NFC Type 4 tag emulation _(Text and URI record types supported)_ 33 | 34 | anyways, the module's architecture is ready to engage also the new, other usages. 35 | 36 | ## Architectural overview 37 | 38 | Core part of the library (on the native side) is a Service which implements [`HostApduService`](https://developer.android.com/reference/android/nfc/cardemulation/HostApduService) Android interface. 39 | The key difference between usual Android services and `HostApduService` is the initializer entity. 40 | `HostApduService` is initiated by OS - when phone taps the NFC reader. Thus, the Service (and - in the big 41 | picture - the entire library) has been prepared to the case, when the React 42 | Activity is in the background or even not available at the time in time of card data transfer. 43 | 44 | Because of this special behavior of `HostApduService`, we have chosen 45 | the _"declarativeness over interactivity"_ approach in the architecture design. 46 | To make the transactions stable and reliable, library stores the state 47 | on the Native side (in Android, the data are stored in `SharedPreferences`). The application can specify 48 | the available data in advance, to store it to native memory right away and 49 | pass it efficiently to the Service, if needed. Also, the Service can pass the data to a storage 50 | without considering the presence of JS thread. React app can grab the saved data later on. 51 | 52 | Of course, all of this synchronization operations are handled in the React part of the library, 53 | so the end user can control the entire HCE session with convenient abstraction - the `HCEService` class. 54 | The library also provides the convenient wrapper that binds the HCEService with React application lifecycle using the 55 | "Contexts" feature of React.js. 56 | 57 | ## Important notes 58 | 59 | - Currenlty supported **only on the Android platform**, as there is no official support for HCE in Apple platform. 60 | - Required minimum SDK version is **API 21** 61 | - Be careful **when using this library for transmission of any sensitive data**. This library does not provide 62 | any built-it cryptographic layer, the data are transmitted in plain form. Ensure that You know, what You are doing and take care about any needed ensafements on Your own. 63 | 64 | ## Installation 65 | 66 | ```sh 67 | npm install react-native-hce --save 68 | ``` 69 | 70 | or 71 | 72 | ```sh 73 | yarn add react-native-hce 74 | ``` 75 | 76 | ...up to Your preferences and project configuration. Autolinking will take care about the rest. 77 | 78 | ## Post-installation steps 79 | 80 | After the installation, following changes must be made inside the `/android`: 81 | 82 | ### aid_list.xml 83 | 84 | Create new file `aid_list.xml` in `/android/app/src/main/res/xml` directory. Create the directory, if it does not exist yet. 85 | 86 | - Put the following content to the file: 87 | 88 | ```xml 89 | 92 | 94 | 95 | 96 | 97 | 98 | 99 | ``` 100 | 101 | ### AndroidManifest.xml 102 | 103 | Open the app's manifest (`/android/app/src/main/AndroidManifest.xml`): 104 | 105 | - Add permission to use NFC in the application, and add the declaration of usage the HCE feature: 106 | 107 | ```xml 108 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | ... 117 | 118 | 119 | ``` 120 | 121 | - HCE emulation on the Android platform works as a service. `react-native-hce` module communicating with this service, so that's why we need to place the reference in AndroidManifest. 122 | 123 | ```xml 124 | 131 | 132 | 133 | 134 | 135 | 140 | 141 | 142 | 143 | 144 | 145 | 148 | 149 | 150 | 151 | ``` 152 | 153 | That's it. 154 | 155 | ## Usage 156 | 157 | ### API documentation 158 | 159 | You can find the generated documentation on the [project's website](https://react-native-hce.appidea.pl). 160 | 161 | ### Example application 162 | 163 | You can try out the [example react-native app](example), which presents the usage of this package in practice. The instructions regarding starting up the example application are provided in [Contribution guide](CONTRIBUTING.md). 164 | 165 | ### NFC Type 4 tag emulation feature 166 | 167 | Inspired by [underwindfall's](https://github.com/underwindfall) NFC Type 4 tag communication handling used in [NFCAndroid](https://github.com/underwindfall/NFCAndroid). 168 | 169 | **Note! If You want to use this feature, make sure that You added the proper aid to Your `aid_list.xml`. Otherwise, the app will not handle any signal of NFC reader related with NFC Tags v4.** 170 | 171 | This is how to enable the NFC Tag emulation: 172 | 173 | ```js 174 | import { 175 | HCESession, 176 | NFCTagType4NDEFContentType, 177 | NFCTagType4, 178 | } from 'react-native-hce'; 179 | 180 | let session; 181 | 182 | const startSession = async () => { 183 | const tag = new NFCTagType4({ 184 | type: NFCTagType4NDEFContentType.Text, 185 | content: 'Hello world', 186 | writable: false, 187 | }); 188 | 189 | session = await HCESession.getInstance(); 190 | session.setApplication(tag); 191 | await session.setEnabled(true); 192 | }; 193 | 194 | startSession(); 195 | ``` 196 | 197 | stops this way: 198 | 199 | ```js 200 | const stopSession = async () => { 201 | await session.setEnabled(false); 202 | }; 203 | 204 | stopSimulation(); 205 | ``` 206 | 207 | It is possible to listen for events during the emulation: 208 | 209 | ```js 210 | const listen = async () => { 211 | const removeListener = session.on(HCESession.Events.HCE_STATE_READ, () => { 212 | ToastAndroid.show('The tag has been read! Thank You.', ToastAndroid.LONG); 213 | }); 214 | 215 | // to remove the listener: 216 | removeListener(); 217 | }; 218 | 219 | listen(); 220 | ``` 221 | 222 | Example application shows also the usage of writable tag feature. 223 | 224 | ### Other features 225 | 226 | This project is opened for Your ideas. You can contribute to the library and add the other functionalities, if You eager. 227 | 228 | ## Troubleshooting 229 | 230 | - Ensure, that there is no AID conflict with other HCE-enabled apps. Try to disable all HCE-enabled apps except the Your one. You can do this in Android Settings. [See more details...](https://github.com/appidea/react-native-hce/issues/2#issuecomment-1221538916) 231 | - If You experience the issues when trying to start up the example application, ensure, that You follow the steps described in [contribution guide](CONTRIBUTING.md). 232 | 233 | ## Development roadmap 234 | 235 | - support for more types of NDEF Messages 236 | - support for writable NFC Tags 237 | - support for development of custom applications 238 | 239 | ## Contributing 240 | 241 | This project has been bootstrapped with [Bob](https://github.com/react-native-community/bob.git). 242 | 243 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. 244 | 245 | ## License 246 | 247 | MIT 248 | -------------------------------------------------------------------------------- /ios/Hce.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 11 | 12 | F4FF95D7245B92E800C19C63 /* Hce.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4FF95D6245B92E800C19C63 /* Hce.swift */; }; 13 | 14 | 5E555C0D2413F4C50049A1A2 /* Hce.mm in Sources */ = {isa = PBXBuildFile; fileRef = B3E7B5891CC2AC0600A0062D /* Hce.mm */; }; 15 | /* End PBXBuildFile section */ 16 | 17 | /* Begin PBXCopyFilesBuildPhase section */ 18 | 58B511D91A9E6C8500147676 /* CopyFiles */ = { 19 | isa = PBXCopyFilesBuildPhase; 20 | buildActionMask = 2147483647; 21 | dstPath = "include/$(PRODUCT_NAME)"; 22 | dstSubfolderSpec = 16; 23 | files = ( 24 | ); 25 | runOnlyForDeploymentPostprocessing = 0; 26 | }; 27 | /* End PBXCopyFilesBuildPhase section */ 28 | 29 | /* Begin PBXFileReference section */ 30 | 134814201AA4EA6300B7C361 /* libHce.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libHce.a; sourceTree = BUILT_PRODUCTS_DIR; }; 31 | 32 | 33 | B3E7B5891CC2AC0600A0062D /* Hce.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Hce.m; sourceTree = ""; }; 34 | F4FF95D5245B92E700C19C63 /* Hce-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Hce-Bridging-Header.h"; sourceTree = ""; }; 35 | F4FF95D6245B92E800C19C63 /* Hce.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Hce.swift; sourceTree = ""; }; 36 | 37 | /* End PBXFileReference section */ 38 | 39 | /* Begin PBXFrameworksBuildPhase section */ 40 | 58B511D81A9E6C8500147676 /* Frameworks */ = { 41 | isa = PBXFrameworksBuildPhase; 42 | buildActionMask = 2147483647; 43 | files = ( 44 | ); 45 | runOnlyForDeploymentPostprocessing = 0; 46 | }; 47 | /* End PBXFrameworksBuildPhase section */ 48 | 49 | /* Begin PBXGroup section */ 50 | 134814211AA4EA7D00B7C361 /* Products */ = { 51 | isa = PBXGroup; 52 | children = ( 53 | 134814201AA4EA6300B7C361 /* libHce.a */, 54 | ); 55 | name = Products; 56 | sourceTree = ""; 57 | }; 58 | 58B511D21A9E6C8500147676 = { 59 | isa = PBXGroup; 60 | children = ( 61 | 62 | 63 | F4FF95D6245B92E800C19C63 /* Hce.swift */, 64 | B3E7B5891CC2AC0600A0062D /* Hce.m */, 65 | F4FF95D5245B92E700C19C63 /* Hce-Bridging-Header.h */, 66 | 67 | 134814211AA4EA7D00B7C361 /* Products */, 68 | ); 69 | sourceTree = ""; 70 | }; 71 | /* End PBXGroup section */ 72 | 73 | /* Begin PBXNativeTarget section */ 74 | 58B511DA1A9E6C8500147676 /* Hce */ = { 75 | isa = PBXNativeTarget; 76 | buildConfigurationList = 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "Hce" */; 77 | buildPhases = ( 78 | 58B511D71A9E6C8500147676 /* Sources */, 79 | 58B511D81A9E6C8500147676 /* Frameworks */, 80 | 58B511D91A9E6C8500147676 /* CopyFiles */, 81 | ); 82 | buildRules = ( 83 | ); 84 | dependencies = ( 85 | ); 86 | name = Hce; 87 | productName = RCTDataManager; 88 | productReference = 134814201AA4EA6300B7C361 /* libHce.a */; 89 | productType = "com.apple.product-type.library.static"; 90 | }; 91 | /* End PBXNativeTarget section */ 92 | 93 | /* Begin PBXProject section */ 94 | 58B511D31A9E6C8500147676 /* Project object */ = { 95 | isa = PBXProject; 96 | attributes = { 97 | LastUpgradeCheck = 0920; 98 | ORGANIZATIONNAME = Facebook; 99 | TargetAttributes = { 100 | 58B511DA1A9E6C8500147676 = { 101 | CreatedOnToolsVersion = 6.1.1; 102 | }; 103 | }; 104 | }; 105 | buildConfigurationList = 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "Hce" */; 106 | compatibilityVersion = "Xcode 3.2"; 107 | developmentRegion = English; 108 | hasScannedForEncodings = 0; 109 | knownRegions = ( 110 | English, 111 | en, 112 | ); 113 | mainGroup = 58B511D21A9E6C8500147676; 114 | productRefGroup = 58B511D21A9E6C8500147676; 115 | projectDirPath = ""; 116 | projectRoot = ""; 117 | targets = ( 118 | 58B511DA1A9E6C8500147676 /* Hce */, 119 | ); 120 | }; 121 | /* End PBXProject section */ 122 | 123 | /* Begin PBXSourcesBuildPhase section */ 124 | 58B511D71A9E6C8500147676 /* Sources */ = { 125 | isa = PBXSourcesBuildPhase; 126 | buildActionMask = 2147483647; 127 | files = ( 128 | 129 | 130 | F4FF95D7245B92E800C19C63 /* Hce.swift in Sources */, 131 | B3E7B58A1CC2AC0600A0062D /* Hce.m in Sources */, 132 | 133 | ); 134 | runOnlyForDeploymentPostprocessing = 0; 135 | }; 136 | /* End PBXSourcesBuildPhase section */ 137 | 138 | /* Begin XCBuildConfiguration section */ 139 | 58B511ED1A9E6C8500147676 /* Debug */ = { 140 | isa = XCBuildConfiguration; 141 | buildSettings = { 142 | ALWAYS_SEARCH_USER_PATHS = NO; 143 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 144 | CLANG_CXX_LIBRARY = "libc++"; 145 | CLANG_ENABLE_MODULES = YES; 146 | CLANG_ENABLE_OBJC_ARC = YES; 147 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 148 | CLANG_WARN_BOOL_CONVERSION = YES; 149 | CLANG_WARN_COMMA = YES; 150 | CLANG_WARN_CONSTANT_CONVERSION = YES; 151 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 152 | CLANG_WARN_EMPTY_BODY = YES; 153 | CLANG_WARN_ENUM_CONVERSION = YES; 154 | CLANG_WARN_INFINITE_RECURSION = YES; 155 | CLANG_WARN_INT_CONVERSION = YES; 156 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 157 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 158 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 159 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 160 | CLANG_WARN_STRICT_PROTOTYPES = YES; 161 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 162 | CLANG_WARN_UNREACHABLE_CODE = YES; 163 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 164 | COPY_PHASE_STRIP = NO; 165 | ENABLE_STRICT_OBJC_MSGSEND = YES; 166 | ENABLE_TESTABILITY = YES; 167 | GCC_C_LANGUAGE_STANDARD = gnu99; 168 | GCC_DYNAMIC_NO_PIC = NO; 169 | GCC_NO_COMMON_BLOCKS = YES; 170 | GCC_OPTIMIZATION_LEVEL = 0; 171 | GCC_PREPROCESSOR_DEFINITIONS = ( 172 | "DEBUG=1", 173 | "$(inherited)", 174 | ); 175 | GCC_SYMBOLS_PRIVATE_EXTERN = NO; 176 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 177 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 178 | GCC_WARN_UNDECLARED_SELECTOR = YES; 179 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 180 | GCC_WARN_UNUSED_FUNCTION = YES; 181 | GCC_WARN_UNUSED_VARIABLE = YES; 182 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 183 | MTL_ENABLE_DEBUG_INFO = YES; 184 | ONLY_ACTIVE_ARCH = YES; 185 | SDKROOT = iphoneos; 186 | }; 187 | name = Debug; 188 | }; 189 | 58B511EE1A9E6C8500147676 /* Release */ = { 190 | isa = XCBuildConfiguration; 191 | buildSettings = { 192 | ALWAYS_SEARCH_USER_PATHS = NO; 193 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 194 | CLANG_CXX_LIBRARY = "libc++"; 195 | CLANG_ENABLE_MODULES = YES; 196 | CLANG_ENABLE_OBJC_ARC = YES; 197 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 198 | CLANG_WARN_BOOL_CONVERSION = YES; 199 | CLANG_WARN_COMMA = YES; 200 | CLANG_WARN_CONSTANT_CONVERSION = YES; 201 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 202 | CLANG_WARN_EMPTY_BODY = YES; 203 | CLANG_WARN_ENUM_CONVERSION = YES; 204 | CLANG_WARN_INFINITE_RECURSION = YES; 205 | CLANG_WARN_INT_CONVERSION = YES; 206 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 207 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 208 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 209 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 210 | CLANG_WARN_STRICT_PROTOTYPES = YES; 211 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 212 | CLANG_WARN_UNREACHABLE_CODE = YES; 213 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 214 | COPY_PHASE_STRIP = YES; 215 | ENABLE_NS_ASSERTIONS = NO; 216 | ENABLE_STRICT_OBJC_MSGSEND = YES; 217 | GCC_C_LANGUAGE_STANDARD = gnu99; 218 | GCC_NO_COMMON_BLOCKS = YES; 219 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 220 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 221 | GCC_WARN_UNDECLARED_SELECTOR = YES; 222 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 223 | GCC_WARN_UNUSED_FUNCTION = YES; 224 | GCC_WARN_UNUSED_VARIABLE = YES; 225 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 226 | MTL_ENABLE_DEBUG_INFO = NO; 227 | SDKROOT = iphoneos; 228 | VALIDATE_PRODUCT = YES; 229 | }; 230 | name = Release; 231 | }; 232 | 58B511F01A9E6C8500147676 /* Debug */ = { 233 | isa = XCBuildConfiguration; 234 | buildSettings = { 235 | HEADER_SEARCH_PATHS = ( 236 | "$(inherited)", 237 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, 238 | "$(SRCROOT)/../../../React/**", 239 | "$(SRCROOT)/../../react-native/React/**", 240 | ); 241 | LIBRARY_SEARCH_PATHS = "$(inherited)"; 242 | OTHER_LDFLAGS = "-ObjC"; 243 | PRODUCT_NAME = Hce; 244 | SKIP_INSTALL = YES; 245 | 246 | SWIFT_OBJC_BRIDGING_HEADER = "Hce-Bridging-Header.h"; 247 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 248 | SWIFT_VERSION = 5.0; 249 | 250 | }; 251 | name = Debug; 252 | }; 253 | 58B511F11A9E6C8500147676 /* Release */ = { 254 | isa = XCBuildConfiguration; 255 | buildSettings = { 256 | HEADER_SEARCH_PATHS = ( 257 | "$(inherited)", 258 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, 259 | "$(SRCROOT)/../../../React/**", 260 | "$(SRCROOT)/../../react-native/React/**", 261 | ); 262 | LIBRARY_SEARCH_PATHS = "$(inherited)"; 263 | OTHER_LDFLAGS = "-ObjC"; 264 | PRODUCT_NAME = Hce; 265 | SKIP_INSTALL = YES; 266 | 267 | SWIFT_OBJC_BRIDGING_HEADER = "Hce-Bridging-Header.h"; 268 | SWIFT_VERSION = 5.0; 269 | 270 | }; 271 | name = Release; 272 | }; 273 | /* End XCBuildConfiguration section */ 274 | 275 | /* Begin XCConfigurationList section */ 276 | 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "Hce" */ = { 277 | isa = XCConfigurationList; 278 | buildConfigurations = ( 279 | 58B511ED1A9E6C8500147676 /* Debug */, 280 | 58B511EE1A9E6C8500147676 /* Release */, 281 | ); 282 | defaultConfigurationIsVisible = 0; 283 | defaultConfigurationName = Release; 284 | }; 285 | 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "Hce" */ = { 286 | isa = XCConfigurationList; 287 | buildConfigurations = ( 288 | 58B511F01A9E6C8500147676 /* Debug */, 289 | 58B511F11A9E6C8500147676 /* Release */, 290 | ); 291 | defaultConfigurationIsVisible = 0; 292 | defaultConfigurationName = Release; 293 | }; 294 | /* End XCConfigurationList section */ 295 | }; 296 | rootObject = 58B511D31A9E6C8500147676 /* Project object */; 297 | } 298 | -------------------------------------------------------------------------------- /android/src/main/java/com/reactnativehce/utils/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | -------------- 3 | 4 | Version 2.0, January 2004 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following 183 | boilerplate notice, with the fields enclosed by brackets "{}" 184 | replaced with your own identifying information. (Don't include 185 | the brackets!) The text should be enclosed in the appropriate 186 | comment syntax for the file format. We also recommend that a 187 | file or class name and description of purpose be included on the 188 | same "printed page" as the copyright notice for easier 189 | identification within third-party archives. 190 | 191 | Copyright {yyyy} {name of copyright owner} 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | --------------------------------------------------------------------------------