This repository has been archived on 2023-10-10. You can view files and clone it, but cannot push or open issues/pull-requests.
hackfridge/terminal/nfc.c

93 lines
2.1 KiB
C

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <nfc/nfc.h>
#include <nfc/nfc-types.h>
#include "tts.h"
#include "ldap.h"
#include "base64.h"
#include "config.h"
#define E_BAD_CARD 1
#define E_NO_SUCH_USER 2
#define E_FUCKUP 3
#define E_TIMEOUT 4
static nfc_device_t *g_NFCDevice = NULL;
const nfc_modulation_t g_NFCModulations[5] = {
{ .nmt = NMT_ISO14443A, .nbr = NBR_106 },
{ .nmt = NMT_ISO14443B, .nbr = NBR_106 },
{ .nmt = NMT_FELICA, .nbr = NBR_212 },
{ .nmt = NMT_FELICA, .nbr = NBR_424 },
{ .nmt = NMT_JEWEL, .nbr = NBR_106 },
};
const size_t g_NFCModulationCount = 5;
int nfc_read(char *MifareOut)
{
nfc_target_t Target;
bool Result = nfc_initiator_poll_target(g_NFCDevice, g_NFCModulations, g_NFCModulationCount, 20, 2, &Target);
if (Result)
{
if (Target.nm.nmt != NMT_ISO14443A)
return E_BAD_CARD;
if (Target.nti.nai.szUidLen != 4)
return E_BAD_CARD;
printf("Scanned Mifare %x.\n", *(int *)Target.nti.nai.abtUid);
sprintf(MifareOut, "%02x%02x%02x%02x", Target.nti.nai.abtUid[0], Target.nti.nai.abtUid[1], Target.nti.nai.abtUid[2], Target.nti.nai.abtUid[3]);
return 0;
}
return E_TIMEOUT;
}
int nfc_initialize(void)
{
#ifdef NFC_AUTOPROBE
nfc_device_desc_t *Devices;
size_t NumDevices;
Devices = (nfc_device_desc_t *) malloc(10 * sizeof(*Devices));
nfc_list_devices(Devices, 10, &NumDevices);
if (NumDevices == 0)
{
fprintf(stderr, "Error: No NFC device found.\n");
return 1;
}
if (NumDevices > 1)
{
fprintf(stderr, "Error: More than one NFC device found.\n");
return 1;
}
g_NFCDevice = nfc_connect(&Devices[0]);
#else
char pcPort[] = NFC_PORT;
nfc_device_desc_t dev = {
.pcDriver = "PN532_UART",
.uiSpeed = 115200,
};
strcpy(dev.acPort, pcPort);
g_NFCDevice = nfc_connect(&dev);
#endif
if (g_NFCDevice == NULL)
{
fprintf(stderr, "Error: Could not connect to NFC device.\n");
return 1;
}
nfc_initiator_init(g_NFCDevice);
printf("Connected to NFC device.\n");
return 0;
}