Loading page
Result page
// src/index.js
// ...
io.on('connection', (socket) => {
socket.on('require-scan', () => {
const nfc = new NFC();
nfc.on('reader', (reader) => {
const pageNumber = 4;
const bufferLength = 48;
reader.on('card', async (card) => {
try {
const data = await reader.read(pageNumber, bufferLength);
const extractedPayload = data.toString().split('/')[1];
socket.emit('nfc-tag-scanned', extractedPayload);
} catch (err) {
// boilerplate code to handle the error
}
});
});
});
});
// src/pages/home/components/HomeContainer.jsx
// ...
const HomeContainer = () => {
const [socket, setSocket] = useState();
const [readTag, setReadTag] = useState();
useEffect(() => {
setSocket(SocketIO.connect(APILocalSocketUrl));
}, [APILocalSocketUrl]);
useEffect(() => {
if (!socket) {
return () => {};
}
socket.emit("require-scan");
socket.on("nfc-tag-scanned", payload => {
setReadTag(payload);
});
return () => socket.close();
}, [socket]);
return <Home readTag={readTag} />;
};
export default HomeContainer;
How to do it with web technologies? 🤔
Build cross platform desktop apps with JavaScript, HTML, and CSS
const HomeContainer = () => {
const nfc = new NFC();
const [readTag, setReadTag] = useState(undefined);
nfc.on("reader", reader => {
const pageNumber = 4;
const bufferLength = 48;
reader.on("card", card => {
reader.read(pageNumber, bufferLength).then(data => {
const extractedPayload = data.toString().split("/")[1];
setReadTag(extractedPayload);
});
});
});
return <Home readTag={readTag} />;
};
// NFC Reading libraries
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
// WebUSB library
#include <WebUSB.h>
// Web origin
#define PROTOCOL_HTTP 0 /* http:// */
WebUSB WebUSBSerial(PROTOCOL_HTTP, "localhost:3000");
// NFC Shield configuration
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#define BAUD_RATE 9600
void loop() {
if (nfc.tagPresent()){
NfcTag tag = nfc.read();
if (tag.hasNdefMessage()) { // If your tag has a message
NdefMessage message = tag.getNdefMessage();
// If you have more than 1 record then it will cycle through them
int recordCount = message.getRecordCount();
for (int i = 0; i < recordCount; i++) {
NdefRecord record = message.getRecord(i);
int payloadLength = record.getPayloadLength();
byte payload[payloadLength];
record.getPayload(payload);
String payloadAsString = ""; // Processes the message as a string vs as a HEX value
for (int c = 0; c < payloadLength; c++) {
payloadAsString += (char)payload[c];
}
WebUSBSerial.write(payloadAsString.c_str());
}
}
};
WebUSBSerial.flush();
delay(250);
}