66 lines
2.0 KiB
TypeScript
66 lines
2.0 KiB
TypeScript
import PCSC, { Tag, Reader } from "@tockawa/nfc-pcsc";
|
|
|
|
export type NfcEvent =
|
|
| { type: "tag"; uid: string }
|
|
| { type: "removed"; uid: string }
|
|
| { type: "error"; message: string };
|
|
|
|
export class NfcService {
|
|
private nfc: PCSC;
|
|
private onEvent?: (event: NfcEvent) => void;
|
|
|
|
constructor(onEvent?: (event: NfcEvent) => void) {
|
|
this.nfc = new PCSC.default();
|
|
this.onEvent = onEvent;
|
|
this.init();
|
|
}
|
|
|
|
private init(): void {
|
|
this.nfc.on("reader", (reader: Reader) => {
|
|
console.log(`Lector detectado: ${reader.name}`);
|
|
|
|
reader.on("card", async (card: Tag) => {
|
|
console.log(`Tarjeta detectada! UID: ${card.uid}`);
|
|
if (this.onEvent) {
|
|
this.onEvent({ type: "tag", uid: card.uid });
|
|
}
|
|
});
|
|
|
|
reader.on("card.off", async (card: Tag) => {
|
|
console.log(`Tarjeta retirada: ${card.uid}`);
|
|
if (this.onEvent) {
|
|
this.onEvent({ type: "removed", uid: card.uid });
|
|
}
|
|
});
|
|
|
|
reader.on("error", (err: Error) => {
|
|
console.error(`Error en el lector ${reader.name}:`, err);
|
|
if (this.onEvent) {
|
|
this.onEvent({
|
|
type: "error",
|
|
message: err.message || String(err),
|
|
});
|
|
}
|
|
});
|
|
|
|
reader.on("end", () => {
|
|
console.log(`Lector desconectado: ${reader.name}`);
|
|
});
|
|
});
|
|
|
|
this.nfc.on("error", (err: Error) => {
|
|
console.error("Error general de NFC:", err);
|
|
if (this.onEvent) {
|
|
this.onEvent({
|
|
type: "error",
|
|
message: err.message || String(err),
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
public stop(): void {
|
|
// La mayoría de los lectores se cierran solos al cerrar la app
|
|
}
|
|
}
|