-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnfc.c
More file actions
116 lines (99 loc) · 3.43 KB
/
nfc.c
File metadata and controls
116 lines (99 loc) · 3.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <nfc/nfc.h>
#define ATS_MAX_LEN 64
#define CHECK_INTERVAL_uSEC 500000 // 500000 마이크로초 = 0.5초
int count = 0;
// 바이트 배열을 HEX 문자열로 변환
void bytes_to_hexstr(const uint8_t *bytes, size_t len, char *str, size_t str_size) {
size_t i;
if (str_size < (len * 2 + 1)) {
fprintf(stderr, "Buffer too small for hex string\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < len; i++) {
sprintf(&str[i*2], "%02X", bytes[i]);
}
str[len*2] = '\0';
}
int main(void) {
nfc_device *pnd = NULL;
nfc_context *context;
nfc_target nt;
nfc_init(&context);
if (context == NULL) {
fprintf(stderr, "Unable to init libnfc\n");
return EXIT_FAILURE;
}
// PN532 I2C 접속
pnd = nfc_open(context, NULL);
if (pnd == NULL) {
fprintf(stderr, "Unable to open NFC device.\n");
nfc_exit(context);
return EXIT_FAILURE;
}
if (nfc_initiator_init(pnd) < 0) {
nfc_perror(pnd, "nfc_initiator_init");
nfc_close(pnd);
nfc_exit(context);
return EXIT_FAILURE;
}
printf("PN532 NFC reader initialized.\n");
FILE *ats_file = NULL;
while (1) {
// NFC 카드 감지 시도
const nfc_modulation nmModulations[1] = {
{ .nmt = NMT_ISO14443A, .nbr = NBR_106 },
};
const size_t szModulations = 1;
int res = nfc_initiator_poll_target(pnd, nmModulations, szModulations, 1, 2, &nt);
if (res > 0) {
// ATS 정보 추출 (타겟 정보에서 ATS는 abtAts에 있음)
if (nt.nti.nai.szAtsLen > 0) {
char ats_hex[ATS_MAX_LEN*2 + 1];
bytes_to_hexstr(nt.nti.nai.abtAts, nt.nti.nai.szAtsLen, ats_hex, sizeof(ats_hex));
printf("Detected ATS: %s\n", ats_hex);
// ATS 값이 있을 경우
ats_file = fopen("uid.txt", "w+");
if (ats_file == NULL) {
perror("파일 열기 실패");
} else {
fprintf(ats_file, "%s\n", ats_hex);
fclose(ats_file);
count++;
printf("ATS 값을 파일에 저장했습니다. %d\n\n", count);
}
} else {
printf("ATS 값이 없습니다.\n");
// ATS 값이 없을 경우
ats_file = fopen("uid.txt", "w+");
if (ats_file == NULL){
perror("파일 열기 실패");
} else {
fprintf(ats_file, "NO ATS\n");
fclose(ats_file);
count++;
printf("'NO ATS'를 파일에 저장했습니다. %d\n\n", count);
}
}
} else {
printf("NFC 태그 미감지...\n");
// NFC 태그가 인식되지 않은 경우
ats_file = fopen("uid.txt", "w+");
if (ats_file == NULL){
perror("파일 열기 실패");
} else {
fprintf(ats_file, "NO TAG\n");
fclose(ats_file);
count++;
printf("'NO TAG'를 파일에 저장했습니다. %d\n\n", count);
}
}
usleep(CHECK_INTERVAL_uSEC);
}
nfc_close(pnd);
nfc_exit(context);
return 0;
}