NFC接口读取ndf数据,写入数据解析参数示例
/**
*
* [@param](/user/param) {*stringToBuffer} str
* 将字符串转成 buffer 参数
*/
const stringToBuffer = function (str) {
// 首先将字符串转为16进制
if (!str) {
return new Uint8Array().buffer;
}
let val = ""
for (let i = 0; i < str.length; i++) {
if (val === '') {
val = str.charCodeAt(i).toString(16)
} else {
val += ',' + str.charCodeAt(i).toString(16)
}
}
// 将16进制转化为ArrayBuffer
return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
})).buffer
}
let records = [{
id: stringToBuffer(params.id),
payload: stringToBuffer(params.payload + ""),
type: stringToBuffer(params.type),
tnf: params.tnf || 1
}];
/**
*
* [@param](/user/param) {*} arr
* 将读取的数据转换成字符串
*/
function byteToString(arr) {
if (typeof arr === 'string') {
return arr;
}
var str = '',
_arr = arr;
for (var i = 0; i < _arr.length; i++) {
var one = _arr[i].toString(2),
v = one.match(/^1+?(?=0)/);
if (v && one.length == 8) {
var bytesLength = v[0].length;
var store = _arr[i].toString(2).slice(7 - bytesLength);
for (var st = 1; st < bytesLength; st++) {
store += _arr[st + i].toString(2).slice(2);
}
str += String.fromCharCode(parseInt(store, 2));
i += bytesLength - 1;
} else {
str += String.fromCharCode(_arr[i]);
}
}
return str;
}
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
NFCAdapter.onDiscovered((res) => {
console.log("onDiscovered res=>", res);
if (!res.techs.includes(NFCAdapter.tech.ndef)) {
return
}
let aid = parseInt(ab2hex(res.id), 16);
// {id: ArrayBuffer(4), techs: Array(3)}
if (res.messages) {
let cordsArray = res.messages[0].records;
cordsArray.find((item) => {
let payload = byteToString(new Uint8Array(item.payload))
let id = byteToString(new Uint8Array(item.id))
let type = byteToString(new Uint8Array(item.type))
})
}
});
https://developers.weixin.qq.com/miniprogram/dev/framework/device/nfc.html