chore: fix warnings

This commit is contained in:
Richie 2021-02-06 20:48:13 +08:00
parent a4b4a0dd46
commit 4c94b1554b
22 changed files with 1192 additions and 861 deletions

View File

@ -3,3 +3,4 @@ coverage/
dist/
lib/
example/
index.d.ts

View File

@ -1,3 +1,6 @@
module.exports = {
extends: ['@react-native-community'],
rules: {
'no-bitwise': 0,
},
};

View File

@ -7,12 +7,11 @@ const Platform = {
return _os;
},
setOS: os => {
setOS: (os) => {
_os = os;
}
}
},
};
ReactNative.Platform = Platform;
module.exports = ReactNative;
module.exports = ReactNative;

View File

@ -1,19 +1,149 @@
import ByteParser from '../src/ByteParser';
test('parse byteToHexString', () => {
let payload = [104, 116, 116, 112, 115, 58, 47, 47, 103, 105, 116, 104, 117, 98, 46, 99, 111, 109, 47, 119, 104, 105, 116, 101, 100, 111, 103, 103, 49, 51, 47, 114, 101, 97, 99, 116, 45, 110, 97, 116, 105, 118, 101, 45, 110, 102, 99, 45, 109, 97, 110, 97, 103, 101, 114, 35, 114, 101, 97, 100, 109, 101];
expect(ByteParser.byteToHexString(payload)).toBe("68747470733a2f2f6769746875622e636f6d2f7768697465646f676731332f72656163742d6e61746976652d6e66632d6d616e6167657223726561646d65");
test('parse byteToHexString', () => {
let payload = [
104,
116,
116,
112,
115,
58,
47,
47,
103,
105,
116,
104,
117,
98,
46,
99,
111,
109,
47,
119,
104,
105,
116,
101,
100,
111,
103,
103,
49,
51,
47,
114,
101,
97,
99,
116,
45,
110,
97,
116,
105,
118,
101,
45,
110,
102,
99,
45,
109,
97,
110,
97,
103,
101,
114,
35,
114,
101,
97,
100,
109,
101,
];
expect(ByteParser.byteToHexString(payload)).toBe(
'68747470733a2f2f6769746875622e636f6d2f7768697465646f676731332f72656163742d6e61746976652d6e66632d6d616e6167657223726561646d65',
);
});
test('parse byteToHexString should return empty', () => {
expect(ByteParser.byteToHexString({something: "wrong"})).toBe("");
test('parse byteToHexString should return empty', () => {
expect(ByteParser.byteToHexString({something: 'wrong'})).toBe('');
});
test('parse byteToString', () => {
let payload = [104, 116, 116, 112, 115, 58, 47, 47, 103, 105, 116, 104, 117, 98, 46, 99, 111, 109, 47, 119, 104, 105, 116, 101, 100, 111, 103, 103, 49, 51, 47, 114, 101, 97, 99, 116, 45, 110, 97, 116, 105, 118, 101, 45, 110, 102, 99, 45, 109, 97, 110, 97, 103, 101, 114, 35, 114, 101, 97, 100, 109, 101];
expect(ByteParser.byteToString(payload)).toBe("https://github.com/whitedogg13/react-native-nfc-manager#readme");
test('parse byteToString', () => {
let payload = [
104,
116,
116,
112,
115,
58,
47,
47,
103,
105,
116,
104,
117,
98,
46,
99,
111,
109,
47,
119,
104,
105,
116,
101,
100,
111,
103,
103,
49,
51,
47,
114,
101,
97,
99,
116,
45,
110,
97,
116,
105,
118,
101,
45,
110,
102,
99,
45,
109,
97,
110,
97,
103,
101,
114,
35,
114,
101,
97,
100,
109,
101,
];
expect(ByteParser.byteToString(payload)).toBe(
'https://github.com/whitedogg13/react-native-nfc-manager#readme',
);
});
test('parse byteToString should return empty', () => {
expect(ByteParser.byteToString({something: "wrong"})).toBe("");
test('parse byteToString should return empty', () => {
expect(ByteParser.byteToString({something: 'wrong'})).toBe('');
});

View File

@ -6,13 +6,27 @@ test('parse RTD_TEXT', () => {
tnf: 1,
type: RTD_TEXT_TYPE,
payload: [
0x02, 0x65, 0x6e, 0x68, 0x65, 0x6c, 0x6c, 0x6f,
0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21,
]
0x02,
0x65,
0x6e,
0x68,
0x65,
0x6c,
0x6c,
0x6f,
0x2c,
0x20,
0x77,
0x6f,
0x72,
0x6c,
0x64,
0x21,
],
};
let result = NdefParser.parseText(record);
let answer = "hello, world!";
let answer = 'hello, world!';
expect(result).toBe(answer);
});
@ -22,14 +36,11 @@ test('parse RTD_URI', () => {
let record = {
tnf: 1,
type: RTD_URI_TYPE,
payload: [
0x01, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e,
0x63, 0x6f, 0x6d,
]
payload: [0x01, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d],
};
let {uri: result} = NdefParser.parseUri(record);
let answer = "http://www.google.com";
let answer = 'http://www.google.com';
expect(result).toBe(answer);
});

View File

@ -1,16 +1,15 @@
jest.mock('../src/NativeNfcManager');
import {
Platform
} from 'react-native'
import {NativeNfcManager, NfcManagerEmitter, callNative} from '../src/NativeNfcManager'
import {Platform} from 'react-native';
import {NfcManagerEmitter, callNative} from '../src/NativeNfcManager';
describe('NfcManager (ios)', () => {
Platform.setOS('ios');
const NfcManagerModule = require('../src/index.js');
const NfcManager = NfcManagerModule.default;
const {NfcEvents} = NfcManagerModule;
const lastNativeCall = () => callNative.mock.calls[callNative.mock.calls.length - 1];
const lastNativeCall = () =>
callNative.mock.calls[callNative.mock.calls.length - 1];
test('constructor', () => {
expect(Platform.OS).toBe('ios');
@ -30,7 +29,7 @@ describe('NfcManager (ios)', () => {
if (!hit) {
// this native event is not registered, treat as error
exect(true).toBe(false);
expect(true).toBe(false);
}
}
});
@ -66,16 +65,16 @@ describe('NfcManager (ios)', () => {
expect(true).toBe(true);
}
// can receive DiscoverTag event
// can receive DiscoverTag event
const tag1 = {id: '3939889'};
let tag2 = null;
NfcManager.setEventListener(NfcEvents.DiscoverTag, tag => {
NfcManager.setEventListener(NfcEvents.DiscoverTag, (tag) => {
tag2 = tag;
});
NfcManagerEmitter._testTriggerCallback(NfcEvents.DiscoverTag, tag1);
expect(tag2).toEqual(tag1);
// can receive SessionClosed event
// can receive SessionClosed event
let sessionClosed = false;
NfcManager.setEventListener(NfcEvents.SessionClosed, () => {
sessionClosed = true;
@ -92,5 +91,4 @@ describe('NfcManager (ios)', () => {
expect(options.alertMessage).toEqual('Please tap NFC tags');
expect(options.invalidateAfterFirstRead).toBe(false);
});
});

View File

@ -1,64 +1,164 @@
const ndef = require("../ndef-lib");
const textHelper = require("../ndef-lib/ndef-text");
const ndef = require('../ndef-lib');
const textHelper = require('../ndef-lib/ndef-text');
const textMessageHelloWorld = [ 209, 1, 15, 84, 2, 101, 110, 104, 101, 108, 108, 111,
44, 32, 119, 111, 114, 108, 100 ];
const textMessageHelloWorld = [
209,
1,
15,
84,
2,
101,
110,
104,
101,
108,
108,
111,
44,
32,
119,
111,
114,
108,
100,
];
const urlMessageNodeJSorg = [ 209, 1, 11, 85, 3, 110, 111, 100, 101, 106, 115, 46,
111, 114, 103 ];
const urlMessageNodeJSorg = [
209,
1,
11,
85,
3,
110,
111,
100,
101,
106,
115,
46,
111,
114,
103,
];
const multipleRecordMessage = [ 145, 1, 15, 84, 2, 101, 110, 104, 101, 108, 108, 111,
44, 32, 119, 111, 114, 108, 100, 17, 1, 11, 85, 3, 110, 111, 100, 101,
106, 115, 46, 111, 114, 103, 82, 9, 27, 116, 101, 120, 116, 47, 106, 115,
111, 110, 123, 34, 109, 101, 115, 115, 97, 103, 101, 34, 58, 32, 34, 104,
101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 34, 125 ];
const multipleRecordMessage = [
145,
1,
15,
84,
2,
101,
110,
104,
101,
108,
108,
111,
44,
32,
119,
111,
114,
108,
100,
17,
1,
11,
85,
3,
110,
111,
100,
101,
106,
115,
46,
111,
114,
103,
82,
9,
27,
116,
101,
120,
116,
47,
106,
115,
111,
110,
123,
34,
109,
101,
115,
115,
97,
103,
101,
34,
58,
32,
34,
104,
101,
108,
108,
111,
44,
32,
119,
111,
114,
108,
100,
34,
125,
];
test('build and parse text', () => {
const text = "hello, world";
let message = [
ndef.textRecord(text)
];
const text = 'hello, world';
let message = [ndef.textRecord(text)];
let encoded = ndef.encodeMessage(message);
expect(encoded).toEqual(textMessageHelloWorld);
let encoded = ndef.encodeMessage(message);
expect(encoded).toEqual(textMessageHelloWorld);
let decodedMessage = ndef.decodeMessage(encoded);
expect(message[0]).toEqual(decodedMessage[0]);
expect(textHelper.decodePayload(message[0].payload)).toEqual(text);
let decodedMessage = ndef.decodeMessage(encoded);
expect(message[0]).toEqual(decodedMessage[0]);
expect(textHelper.decodePayload(message[0].payload)).toEqual(text);
});
test('build and parse uri', () => {
let message = [
ndef.uriRecord("http://nodejs.org")
];
let message = [ndef.uriRecord('http://nodejs.org')];
let encoded = ndef.encodeMessage(message);
expect(encoded).toEqual(urlMessageNodeJSorg);
let encoded = ndef.encodeMessage(message);
expect(encoded).toEqual(urlMessageNodeJSorg);
let decodedMessage = ndef.decodeMessage(encoded);
expect(message[0]).toEqual(decodedMessage[0]);
let decodedMessage = ndef.decodeMessage(encoded);
expect(message[0]).toEqual(decodedMessage[0]);
});
test('build and parse multiple records', () => {
var message = [
ndef.textRecord("hello, world"),
ndef.uriRecord("http://nodejs.org"),
ndef.mimeMediaRecord("text/json", '{"message": "hello, world"}')
];
var message = [
ndef.textRecord('hello, world'),
ndef.uriRecord('http://nodejs.org'),
ndef.mimeMediaRecord('text/json', '{"message": "hello, world"}'),
];
let encoded = ndef.encodeMessage(message);
expect(encoded).toEqual(multipleRecordMessage);
let encoded = ndef.encodeMessage(message);
expect(encoded).toEqual(multipleRecordMessage);
let decodedMessage = ndef.decodeMessage(encoded);
expect(message[0]).toEqual(decodedMessage[0]);
expect(message[1]).toEqual(decodedMessage[1]);
expect(message[2]).toEqual(decodedMessage[2]);
let decodedMessage = ndef.decodeMessage(encoded);
expect(message[0]).toEqual(decodedMessage[0]);
expect(message[1]).toEqual(decodedMessage[1]);
expect(message[2]).toEqual(decodedMessage[2]);
});
test('build and parse wifi simple payload', () => {
const wifiCredentials = {
ssid: 'my-wifi-ap',
networkKey: 'Abcabc123'
networkKey: 'Abcabc123',
};
const payload = ndef.wifiSimple.encodePayload(wifiCredentials);
@ -68,6 +168,3 @@ test('build and parse wifi simple payload', () => {
expect(parsed.networkKey).toEqual(wifiCredentials.networkKey);
expect(parsed.authType).toEqual(ndef.wifiSimple.authTypes.WPA2_PSK);
});

88
index.d.ts vendored
View File

@ -30,12 +30,12 @@ declare module 'react-native-nfc-manager' {
/** [iOS ONLY] */
export enum Nfc15693RequestFlagIOS {
DualSubCarriers = (1 << 0),
HighDataRate = (1 << 1),
ProtocolExtension = (1 << 3),
Select = (1 << 4),
Address = (1 << 5),
Option = (1 << 6),
DualSubCarriers = 1 << 0,
HighDataRate = 1 << 1,
ProtocolExtension = 1 << 3,
Select = 1 << 4,
Address = 1 << 5,
Option = 1 << 6,
}
/** [ANDROID ONLY] */
@ -90,22 +90,53 @@ declare module 'react-native-nfc-manager' {
interface Iso15693HandlerIOS {
getSystemInfo: (
requestFloags: number,
) => Promise<{ dsfid: number, afi: number, blockSize: number, blockCount: number, icReference: number}>;
readSingleBlock: (params: {flags: number, blockNumber: number}) => Promise<number[]>;
readMultipleBlocks: (params: {flags: number, blockNumber: number, blockCount: number}) => Promise<number[][]>;
writeSingleBlock: (params: {flags: number, blockNumber: number, dataBlock: number[]}) => Promise<void>;
lockBlock: (params: {flags: number, blockNumber: number}) => Promise<void>;
writeAFI: (params: {flags: number, afi: number}) => Promise<void>;
lockAFI: (params: {flags: number}) => Promise<void>;
writeDSFID: (params: {flags: number, dsfid: number}) => Promise<void>;
lockDSFID: (params: {flags: number}) => Promise<void>;
resetToReady: (params: {flags: number}) => Promise<void>;
select: (params: {flags: number}) => Promise<void>;
stayQuite: () => Promise<void>;
customCommand: (params: {flags: number, customCommandCode: number, customRequestParameters: number[]}) => Promise<number[]>;
extendedReadSingleBlock: (params: {flags: number, blockNumber: number}) => Promise<number[]>;
extendedWriteSingleBlock: (params: {flags: number, blockNumber: number, dataBlock: number[]}) => Promise<void>;
extendedLockBlock: (params: {flags: number, blockNumber: number}) => Promise<void>;
) => Promise<{
dsfid: number;
afi: number;
blockSize: number;
blockCount: number;
icReference: number;
}>;
readSingleBlock: (params: {
flags: number;
blockNumber: number;
}) => Promise<number[]>;
readMultipleBlocks: (params: {
flags: number;
blockNumber: number;
blockCount: number;
}) => Promise<number[][]>;
writeSingleBlock: (params: {
flags: number;
blockNumber: number;
dataBlock: number[];
}) => Promise<void>;
lockBlock: (params: {flags: number; blockNumber: number}) => Promise<void>;
writeAFI: (params: {flags: number; afi: number}) => Promise<void>;
lockAFI: (params: {flags: number}) => Promise<void>;
writeDSFID: (params: {flags: number; dsfid: number}) => Promise<void>;
lockDSFID: (params: {flags: number}) => Promise<void>;
resetToReady: (params: {flags: number}) => Promise<void>;
select: (params: {flags: number}) => Promise<void>;
stayQuite: () => Promise<void>;
customCommand: (params: {
flags: number;
customCommandCode: number;
customRequestParameters: number[];
}) => Promise<number[]>;
extendedReadSingleBlock: (params: {
flags: number;
blockNumber: number;
}) => Promise<number[]>;
extendedWriteSingleBlock: (params: {
flags: number;
blockNumber: number;
dataBlock: number[];
}) => Promise<void>;
extendedLockBlock: (params: {
flags: number;
blockNumber: number;
}) => Promise<void>;
}
interface NfcManager {
@ -121,7 +152,7 @@ declare module 'react-native-nfc-manager' {
requestTechnology(
tech: NfcTech | NfcTech[],
options?: RegisterTagEventOpts
options?: RegisterTagEventOpts,
): Promise<NfcTech>;
cancelTechnologyRequest: () => Promise<void>;
@ -197,7 +228,7 @@ declare module 'react-native-nfc-manager' {
type ISOLangCode = 'en' | string;
type URI = string;
type TNF = 0x0 | 0x01 | 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07
type TNF = 0x0 | 0x01 | 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07;
export interface WifiSimpleCredentials {
ssid: string;
@ -223,7 +254,7 @@ declare module 'react-native-nfc-manager' {
RTD_HANDOVER_REQUEST: 'Hr'; // [0x48, 0x72]
RTD_HANDOVER_SELECT: 'Hs'; // [0x48, 0x73]
MIME_WFA_WSC: "application/vnd.wfa.wsc";
MIME_WFA_WSC: 'application/vnd.wfa.wsc';
text: {
encodePayload: (
@ -256,7 +287,12 @@ declare module 'react-native-nfc-manager' {
uriRecord(uri: URI, id?: any): NdefRecord;
wifiSimpleRecord(credentials: WifiSimpleCredentials, id?: any): NdefRecord;
androidApplicationRecord(pkgName: string): NdefRecord;
record(tnf: TNF, type: string, id: string | any[], payload: string | any[]): NdefRecord
record(
tnf: TNF,
type: string,
id: string | any[],
payload: string | any[],
): NdefRecord;
};
}

File diff suppressed because it is too large Load Diff

View File

@ -3,31 +3,31 @@ var util = require('./ndef-util');
// decode text bytes from ndef record payload
// @returns a string
function decode(data) {
var languageCodeLength = data[0] & 0x3f; // 6 LSBs
// languageCode = data.slice(1, 1 + languageCodeLength),
// utf16 = (data[0] & 0x80) !== 0; // assuming UTF-16BE
var languageCodeLength = (data[0] & 0x3F), // 6 LSBs
languageCode = data.slice(1, 1 + languageCodeLength),
utf16 = (data[0] & 0x80) !== 0; // assuming UTF-16BE
// TODO need to deal with UTF in the future
// console.log("lang " + languageCode + (utf16 ? " utf16" : " utf8"));
// TODO need to deal with UTF in the future
// console.log("lang " + languageCode + (utf16 ? " utf16" : " utf8"));
return util.bytesToString(data.slice(languageCodeLength + 1));
return util.bytesToString(data.slice(languageCodeLength + 1));
}
// encode text payload
// @returns an array of bytes
function encode(text, lang, encoding) {
// ISO/IANA language code, but we're not enforcing
if (!lang) {
lang = 'en';
}
// ISO/IANA language code, but we're not enforcing
if (!lang) { lang = 'en'; }
var encoded = util.stringToBytes(lang + text);
encoded.unshift(lang.length);
var encoded = util.stringToBytes(lang + text);
encoded.unshift(lang.length);
return encoded;
return encoded;
}
module.exports = {
encodePayload: encode,
decodePayload: decode
}
encodePayload: encode,
decodePayload: decode,
};

View File

@ -2,48 +2,83 @@ var util = require('./ndef-util');
// URI identifier codes from URI Record Type Definition NFCForum-TS-RTD_URI_1.0 2006-07-24
// index in array matches code in the spec
var protocols = [ "", "http://www.", "https://www.", "http://", "https://", "tel:", "mailto:", "ftp://anonymous:anonymous@", "ftp://ftp.", "ftps://", "sftp://", "smb://", "nfs://", "ftp://", "dav://", "news:", "telnet://", "imap:", "rtsp://", "urn:", "pop:", "sip:", "sips:", "tftp:", "btspp://", "btl2cap://", "btgoep://", "tcpobex://", "irdaobex://", "file://", "urn:epc:id:", "urn:epc:tag:", "urn:epc:pat:", "urn:epc:raw:", "urn:epc:", "urn:nfc:" ]
var protocols = [
'',
'http://www.',
'https://www.',
'http://',
'https://',
'tel:',
'mailto:',
'ftp://anonymous:anonymous@',
'ftp://ftp.',
'ftps://',
'sftp://',
'smb://',
'nfs://',
'ftp://',
'dav://',
'news:',
'telnet://',
'imap:',
'rtsp://',
'urn:',
'pop:',
'sip:',
'sips:',
'tftp:',
'btspp://',
'btl2cap://',
'btgoep://',
'tcpobex://',
'irdaobex://',
'file://',
'urn:epc:id:',
'urn:epc:tag:',
'urn:epc:pat:',
'urn:epc:raw:',
'urn:epc:',
'urn:nfc:',
];
// decode a URI payload bytes
// @returns a string
function decode(data) {
var prefix = protocols[data[0]];
if (!prefix) { // 36 to 255 should be ""
prefix = "";
}
return prefix + util.bytesToString(data.slice(1));
}
var prefix = protocols[data[0]];
if (!prefix) {
// 36 to 255 should be ""
prefix = '';
}
return prefix + util.bytesToString(data.slice(1));
}
// shorten a URI with standard prefix
// @returns an array of bytes
function encode(uri) {
var prefix,
protocolCode,
encoded;
var prefix, protocolCode, encoded;
// check each protocol, unless we've found a match
// "urn:" is the one exception where we need to keep checking
// slice so we don't check ""
protocols.slice(1).forEach(function(protocol) {
if ((!prefix || prefix === "urn:") && uri.indexOf(protocol) === 0) {
prefix = protocol;
}
});
if (!prefix) {
prefix = "";
// check each protocol, unless we've found a match
// "urn:" is the one exception where we need to keep checking
// slice so we don't check ""
protocols.slice(1).forEach(function (protocol) {
if ((!prefix || prefix === 'urn:') && uri.indexOf(protocol) === 0) {
prefix = protocol;
}
encoded = util.stringToBytes(uri.slice(prefix.length));
protocolCode = protocols.indexOf(prefix);
// prepend protocol code
encoded.unshift(protocolCode);
return encoded;
});
if (!prefix) {
prefix = '';
}
encoded = util.stringToBytes(uri.slice(prefix.length));
protocolCode = protocols.indexOf(prefix);
// prepend protocol code
encoded.unshift(protocolCode);
return encoded;
}
module.exports = {
encodePayload: encode,
decodePayload: decode
}
encodePayload: encode,
decodePayload: decode,
};

View File

@ -4,36 +4,39 @@
// https://weblog.rogueamoeba.com/2017/02/27/javascript-correctly-converting-a-byte-array-to-a-utf-8-string/
function _utf8ArrayToStr(data) {
const extraByteMap = [1, 1, 1, 1, 2, 2, 3, 0];
var count = data.length;
var str = "";
const extraByteMap = [1, 1, 1, 1, 2, 2, 3, 0];
var count = data.length;
var str = '';
for (var index = 0; index < count;) {
var ch = data[index++];
if (ch & 0x80) {
var extra = extraByteMap[(ch >> 3) & 0x07];
if (!(ch & 0x40) || !extra || ((index + extra) > count))
return null;
for (var index = 0; index < count; ) {
var ch = data[index++];
if (ch & 0x80) {
var extra = extraByteMap[(ch >> 3) & 0x07];
if (!(ch & 0x40) || !extra || index + extra > count) {
return null;
}
ch = ch & (0x3F >> extra);
for (; extra > 0; extra -= 1) {
var chx = data[index++];
if ((chx & 0xC0) != 0x80)
return null;
ch = (ch << 6) | (chx & 0x3F);
}
ch = ch & (0x3f >> extra);
for (; extra > 0; extra -= 1) {
var chx = data[index++];
if ((chx & 0xc0) !== 0x80) {
return null;
}
str += String.fromCharCode(ch);
ch = (ch << 6) | (chx & 0x3f);
}
}
return str;
str += String.fromCharCode(ch);
}
return str;
}
// https://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array
function _toUTF8Array(str) {
var out = [], p = 0;
var out = [],
p = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
if (c < 128) {
@ -42,10 +45,12 @@ function _toUTF8Array(str) {
out[p++] = (c >> 6) | 192;
out[p++] = (c & 63) | 128;
} else if (
((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&
((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {
(c & 0xfc00) === 0xd800 &&
i + 1 < str.length &&
(str.charCodeAt(i + 1) & 0xfc00) === 0xdc00
) {
// Surrogate Pair
c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
out[p++] = (c >> 18) | 240;
out[p++] = ((c >> 12) & 63) | 128;
out[p++] = ((c >> 6) & 63) | 128;
@ -57,76 +62,78 @@ function _toUTF8Array(str) {
}
}
return out;
};
}
function stringToBytes(string) {
return _toUTF8Array(string);
// var bytes = Buffer(string).toJSON();
// if (bytes.hasOwnProperty('data')) {
// // Node 0.12.x
// return bytes.data;
// } else {
// // Node 0.10.x
// return bytes;
// }
return _toUTF8Array(string);
// var bytes = Buffer(string).toJSON();
// if (bytes.hasOwnProperty('data')) {
// // Node 0.12.x
// return bytes.data;
// } else {
// // Node 0.10.x
// return bytes;
// }
}
function bytesToString(bytes) {
if (typeof(bytes) === 'string') {
return bytes;
}
if (typeof bytes === 'string') {
return bytes;
}
return _utf8ArrayToStr(bytes);
// return Buffer(bytes).toString();
return _utf8ArrayToStr(bytes);
// return Buffer(bytes).toString();
}
// useful for readable version of Tag UID
function bytesToHexString(bytes) {
var dec, hexstring, bytesAsHexString = "";
for (var i = 0; i < bytes.length; i++) {
if (bytes[i] >= 0) {
dec = bytes[i];
} else {
dec = 256 + bytes[i];
}
hexstring = dec.toString(16);
// zero padding
if (hexstring.length == 1) {
hexstring = "0" + hexstring;
}
bytesAsHexString += hexstring;
var dec,
hexstring,
bytesAsHexString = '';
for (var i = 0; i < bytes.length; i++) {
if (bytes[i] >= 0) {
dec = bytes[i];
} else {
dec = 256 + bytes[i];
}
return bytesAsHexString;
hexstring = dec.toString(16);
// zero padding
if (hexstring.length === 1) {
hexstring = '0' + hexstring;
}
bytesAsHexString += hexstring;
}
return bytesAsHexString;
}
// i must be <= 256
function toHex(i) {
var hex;
var hex;
if (i < 0) {
i += 256;
}
hex = i.toString(16);
if (i < 0) {
i += 256;
}
hex = i.toString(16);
// zero padding
if (hex.length == 1) {
hex = "0" + hex;
}
return hex;
// zero padding
if (hex.length === 1) {
hex = '0' + hex;
}
return hex;
}
function toPrintable(i) {
if (i >= 0x20 & i <= 0x7F) {
return String.fromCharCode(i);
} else {
return '.';
}
if ((i >= 0x20) & (i <= 0x7f)) {
return String.fromCharCode(i);
} else {
return '.';
}
}
module.exports = {
stringToBytes: stringToBytes,
bytesToString: bytesToString,
bytesToHexString: bytesToHexString,
toHex: toHex,
toPrintable: toPrintable
stringToBytes: stringToBytes,
bytesToString: bytesToString,
bytesToHexString: bytesToHexString,
toHex: toHex,
toPrintable: toPrintable,
};

View File

@ -1,7 +1,7 @@
var util = require('./ndef-util');
const CREDENTIAL_FIELD_ID = [0x10, 0x0e];
const SSID_FIELD_ID = [0x10, 0x45];
const SSID_FIELD_ID = [0x10, 0x45];
const AUTH_TYPE_FIELD_ID = [0x10, 0x03];
const NETWORK_KEY_FIELD_ID = [0x10, 0x27];
@ -12,7 +12,7 @@ const AUTH_TYPES = {
function _getLengthBytes(valueBytes) {
if (valueBytes.length > 255) {
return [Math.floor(valueBytes.length / 256), valueBytes.length % 256 ];
return [Math.floor(valueBytes.length / 256), valueBytes.length % 256];
}
return [0x0, valueBytes.length];
}
@ -24,7 +24,7 @@ function _arrayEqual(arr1, arr2) {
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false
return false;
}
}
@ -33,16 +33,18 @@ function _arrayEqual(arr1, arr2) {
function _getNextTLV(bytes) {
const type = bytes.slice(0, 2);
const length = bytes.slice(2, 4);
const length = bytes.slice(2, 4);
const value = bytes.slice(4, 4 + (length[0] * 256 + length[1]));
return {
type, length, value
}
type,
length,
value,
};
}
// @returns an string of wifi credentials
function decode(bytes) {
let result = {}
let result = {};
while (bytes.length > 0) {
let {type, value} = _getNextTLV(bytes);
@ -71,27 +73,37 @@ function decode(bytes) {
// encode wifi object payload
// @returns an array of bytes
function encode({ssid, networkKey, authType=AUTH_TYPES.WPA2_PSK}) {
function encode({ssid, networkKey, authType = AUTH_TYPES.WPA2_PSK}) {
if (typeof ssid !== 'string' || typeof networkKey !== 'string') {
throw new Error('')
throw new Error('');
}
ssid = util.stringToBytes(ssid);
networkKey = util.stringToBytes(networkKey);
// build seperated TLV
const authTypeTLV = [...AUTH_TYPE_FIELD_ID, 0x0, authType.length, ...authType];
const authTypeTLV = [
...AUTH_TYPE_FIELD_ID,
0x0,
authType.length,
...authType,
];
const ssidTLV = [...SSID_FIELD_ID, 0x0, ssid.length, ...ssid];
const networkKeyTLV = [...NETWORK_KEY_FIELD_ID, 0x0, networkKey.length, ...networkKey];
const networkKeyTLV = [
...NETWORK_KEY_FIELD_ID,
0x0,
networkKey.length,
...networkKey,
];
// build credential TLV
const credentialValue = [...authTypeTLV, ...ssidTLV, ...networkKeyTLV];
const credentialTLV = [
...CREDENTIAL_FIELD_ID,
..._getLengthBytes(credentialValue),
...credentialValue
];
...CREDENTIAL_FIELD_ID,
..._getLengthBytes(credentialValue),
...credentialValue,
];
return credentialTLV;
}
@ -99,4 +111,4 @@ module.exports = {
encodePayload: encode,
decodePayload: decode,
authTypes: AUTH_TYPES,
};
};

View File

@ -1,5 +1,7 @@
function byteToHexString(bytes) {
if (!Array.isArray(bytes) || !bytes.length) return '';
if (!Array.isArray(bytes) || !bytes.length) {
return '';
}
let result = '';
for (let i = 0; i < bytes.length; i++) {
@ -9,7 +11,9 @@ function byteToHexString(bytes) {
}
function byteToString(bytes) {
if (!Array.isArray(bytes) || !bytes.length) return '';
if (!Array.isArray(bytes) || !bytes.length) {
return '';
}
let result = '';
for (let i = 0; i < bytes.length; i++) {
@ -19,6 +23,6 @@ function byteToString(bytes) {
}
export default {
byteToHexString,
byteToString,
}
byteToHexString,
byteToString,
};

View File

@ -1,13 +1,10 @@
'use strict';
import {
NativeModules,
NativeEventEmitter,
} from 'react-native'
import {NativeModules, NativeEventEmitter} from 'react-native';
const NativeNfcManager = NativeModules.NfcManager;
const NfcManagerEmitter = new NativeEventEmitter(NativeNfcManager);
function callNative(name, params=[]) {
function callNative(name, params = []) {
const nativeMethod = NativeNfcManager[name];
if (!nativeMethod) {
@ -15,7 +12,7 @@ function callNative(name, params=[]) {
}
if (!Array.isArray(params)) {
throw new Error(`params must be an array`);
throw new Error('params must be an array');
}
const createCallback = (resolve, reject) => (err, result) => {
@ -33,8 +30,4 @@ function callNative(name, params=[]) {
});
}
export {
NativeNfcManager,
NfcManagerEmitter,
callNative,
}
export {NativeNfcManager, NfcManagerEmitter, callNative};

View File

@ -1,38 +1,40 @@
const textHelper = require("../ndef-lib/ndef-text");
const uriHelper = require("../ndef-lib/ndef-uri");
const arrayEqual = (a, b) => a && b && a.length === b.length && a.every((v, i) => v === b[i]);
const textHelper = require('../ndef-lib/ndef-text');
const uriHelper = require('../ndef-lib/ndef-uri');
const arrayEqual = (a, b) =>
a && b && a.length === b.length && a.every((v, i) => v === b[i]);
function parseText(record) {
const RTD_TEXT_TYPE = [0x54];
if (record && record.tnf === 1) {
if (record.type && arrayEqual(RTD_TEXT_TYPE, record.type)) {
try { // only handle utf8 for now
return textHelper.decodePayload(record.payload);
} catch (ex) {
return null;
}
}
const RTD_TEXT_TYPE = [0x54];
if (record && record.tnf === 1) {
if (record.type && arrayEqual(RTD_TEXT_TYPE, record.type)) {
try {
// only handle utf8 for now
return textHelper.decodePayload(record.payload);
} catch (ex) {
return null;
}
}
return null;
}
return null;
}
function parseUri(record) {
const RTD_URI_TYPE = [0x55];
if (record && record.tnf === 1) {
if (record.type && arrayEqual(RTD_URI_TYPE, record.type)) {
try {
return {
uri: uriHelper.decodePayload(record.payload)
}
} catch (err) {
return null;
}
}
const RTD_URI_TYPE = [0x55];
if (record && record.tnf === 1) {
if (record.type && arrayEqual(RTD_URI_TYPE, record.type)) {
try {
return {
uri: uriHelper.decodePayload(record.payload),
};
} catch (err) {
return null;
}
}
return null;
}
return null;
}
export default {
parseUri,
parseText,
}
parseUri,
parseText,
};

View File

@ -1,11 +1,5 @@
'use strict';
import {Platform} from 'react-native';
import {
NativeNfcManager,
NfcManagerEmitter,
callNative,
} from './NativeNfcManager';
import {NfcEvents, NfcManagerBase} from './NfcManager';
import {callNative} from './NativeNfcManager';
import {NfcManagerBase} from './NfcManager';
import {MifareClassicHandlerAndroid} from './NfcTech/MifareClassicHandlerAndroid';
import {MifareUltralightHandlerAndroid} from './NfcTech/MifareUltralightHandlerAndroid';

View File

@ -1,13 +1,8 @@
'use strict';
import {Platform} from 'react-native';
import {
NativeNfcManager,
NfcManagerEmitter,
callNative,
} from './NativeNfcManager';
import {NativeNfcManager, callNative} from './NativeNfcManager';
import {
NfcTech,
NfcEvents,
NfcManagerBase,
DEFAULT_REGISTER_TAG_EVENT_OPTIONS,
} from './NfcManager';
@ -36,12 +31,13 @@ class NfcManagerIOS extends NfcManagerBase {
}
}
const optionsWithDefault = {
...DEFAULT_REGISTER_TAG_EVENT_OPTIONS,
...options,
};
return callNative('requestTechnology', [techList, options]);
return callNative('requestTechnology', [
techList,
{
...DEFAULT_REGISTER_TAG_EVENT_OPTIONS,
...options,
},
]);
} catch (ex) {
throw ex;
}

View File

@ -1,5 +1,5 @@
import {Platform} from 'react-native';
import {callNative} from '../NativeNfcManager';
import {callNative, NativeNfcManager} from '../NativeNfcManager';
class IsoDepHandler {
async transceive(bytes) {

View File

@ -1,4 +1,3 @@
import {Platform} from 'react-native';
import {callNative} from '../NativeNfcManager';
class MifareClassicHandlerAndroid {

View File

@ -1,4 +1,3 @@
import {Platform} from 'react-native';
import {callNative} from '../NativeNfcManager';
class MifareUltralightHandlerAndroid {

View File

@ -1,6 +1,4 @@
const NativeNfcManager = {
}
const NativeNfcManager = {};
const NfcManagerEmitterListener = {};
const NfcManagerEmitter = {
@ -11,12 +9,8 @@ const NfcManagerEmitter = {
_testTriggerCallback: (name, data) => {
NfcManagerEmitterListener[name](data);
},
}
};
const callNative = jest.fn();
export {
NativeNfcManager,
NfcManagerEmitter,
callNative,
}
export {NativeNfcManager, NfcManagerEmitter, callNative};