Confirmed users
153
edits
Line 155: | Line 155: | ||
break; | break; | ||
} | } | ||
== NDEF Utilitiy function == | |||
MozNdefRecord is a binary format, and the data is packed into Uint8Array fields. In the following examples, we'll just refer to this helper function to convert javascript strings to Uint8Array buffers. | |||
var NfcUtil = { | |||
fromUTF8: function nu_fromUTF8(str) { | |||
var buf = new Uint8Array(str.length); | |||
for (var i = 0; i < str.length; i++) { | |||
buf[i] = str.charCodeAt(i); | |||
} | |||
return buf; | |||
} | |||
} | |||
== NDEF Connect Example == | == NDEF Connect Example == | ||
Line 211: | Line 225: | ||
records.forEach(function (record) { | records.forEach(function (record) { | ||
console.log("Found a " + record.tnf + " record" + | console.log("Found a " + record.tnf + " record" + | ||
" of type " + record.type + | " of type " + NfcUtil.fromUTF8(record.type) + | ||
" with ID " + record.id + | " with ID " + NfcUtil.fromUTF8(record.id) + | ||
" and payload " + record.payload); | " and payload " + NfcUtil.fromUTF8(record.payload)); | ||
}); | }); | ||
}; | }; | ||
Line 219: | Line 233: | ||
== NDEF Write Tag Example == | == NDEF Write Tag Example == | ||
var | var tnf = 1; // NFC Forum Well Known type | ||
var type = new Uint8Array(NfcUtil.fromUTF8("U")); // URL type | |||
var id = new Uint8Array(NfcUtil.fromUTF8("")); // id | |||
var payload = new Uint8Array(NfcUtil.fromUTF8("\u0000http://mozilla.org")); // URL data | |||
var ndefRecords = new MozNdefRecord(tnf, type, id, payload); | |||
var writereq = nfctag.writeNDEF(ndefRecords); | var writereq = nfctag.writeNDEF(ndefRecords); | ||
Line 232: | Line 251: | ||
Peer to Peer communications to another NFC enabled device does not need a connect, as it will automatically connect implicitly. It also only supports NDEF, which is a common standard data format across different NFC devices. | Peer to Peer communications to another NFC enabled device does not need a connect, as it will automatically connect implicitly. It also only supports NDEF, which is a common standard data format across different NFC devices. | ||
var | var tnf = 1; // NFC Forum Well Known type | ||
var type = new Uint8Array(NfcUtil.fromUTF8("U")); // URL type | |||
var id = new Uint8Array(NfcUtil.fromUTF8("")); // id | |||
var payload = new Uint8Array(NfcUtil.fromUTF8("\u0000http://mozilla.org")); // URL data | |||
var ndefRecords = new MozNdefRecord(tnf, type, id, payload); | |||
window.navigator.onpeerfound = function(nfcpeer) { | window.navigator.onpeerfound = function(nfcpeer) { | ||
var peerreq = nfcpeer.pushNDEF(ndefRecords); | var peerreq = nfcpeer.pushNDEF(ndefRecords); // push NDEF message to other NFC device. | ||
peerreq.onsuccess = function(e) { | peerreq.onsuccess = function(e) { | ||
console.log("Successfully pushed P2P message"); | console.log("Successfully pushed P2P message"); |