libnfc/examples/doc/quick_start_example2.c

84 lines
2.5 KiB
C
Raw Normal View History

/**
* @file quick_start_example2.c
* @brief Quick start example that presents how to use libnfc
*/
// This is same example as quick_start_example1.c but using
// some helper functions existing in libnfc.
// Those functions are not available yet in a library
// so binary object must be linked statically:
// $ gcc -o quick_start_example2 -lnfc -I../.. quick_start_example2.c ../../utils/nfc-utils.o
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif // HAVE_CONFIG_H
#include <stdlib.h>
#include <nfc/nfc.h>
#include "utils/nfc-utils.h"
int
main(int argc, const char *argv[])
{
nfc_device *pnd;
nfc_target nt;
2012-12-05 02:02:24 +01:00
// Allocate only a pointer to nfc_context
nfc_context *context;
// Initialize libnfc and set the nfc_context
nfc_init(&context);
if (context == NULL) {
ERR("Unable to init libnfc (malloc)");
exit(EXIT_FAILURE);
}
// Display libnfc version
const char *acLibnfcVersion = nfc_version();
(void)argc;
printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
2012-12-05 02:02:24 +01:00
// Open, using the first available NFC device which can be in order of selection:
// - default device specified using environment variable or
// - first specified device in libnfc.conf (/etc/nfc) or
// - first specified device in device-configuration directory (/etc/nfc/devices.d) or
// - first auto-detected (if feature is not disabled in libnfc.conf) device
pnd = nfc_open(context, NULL);
if (pnd == NULL) {
ERR("%s", "Unable to open NFC device.");
exit(EXIT_FAILURE);
}
// Set opened NFC device to initiator mode
if (nfc_initiator_init(pnd) < 0) {
nfc_perror(pnd, "nfc_initiator_init");
exit(EXIT_FAILURE);
}
printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
// Poll for a ISO14443A (MIFARE) tag
const nfc_modulation nmMifare = {
.nmt = NMT_ISO14443A,
.nbr = NBR_106,
};
if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
printf("The following (NFC) ISO14443A tag was found:\n");
printf(" ATQA (SENS_RES): ");
print_hex(nt.nti.nai.abtAtqa, 2);
printf(" UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1'));
print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
printf(" SAK (SEL_RES): ");
print_hex(&nt.nti.nai.btSak, 1);
if (nt.nti.nai.szAtsLen) {
printf(" ATS (ATR): ");
print_hex(nt.nti.nai.abtAts, nt.nti.nai.szAtsLen);
}
}
// Close NFC device
nfc_close(pnd);
2012-12-05 02:02:24 +01:00
// Release the context
nfc_exit(context);
exit(EXIT_SUCCESS);
}