Statistics
| Branch: | Revision:

root / toolbox / rfid.c @ 532ba0bd

History | View | Annotate | Download (1.85 KB)

1
#include <string.h>
2
#include <util/delay.h>
3
#include "rfid.h"
4
#include "serial.h"
5

    
6
static char read_cmd[] = {'!', 'R', 'W', 1, 32};
7

    
8
static int serno_idx;
9
static char serno[RFID_SERNO_SIZE];
10

    
11
static void zero_serno() {
12
  int i;
13
  for (i = 0; i < RFID_SERNO_SIZE; i++) {
14
    serno[i] = 0;
15
  }
16
}
17

    
18
static void read_serno() {
19
  int i;
20
  for (i = 0; i < RFID_SERNO_SIZE; i++) {
21
    serno[i] = serial_read_blocking();
22
  }
23
}
24

    
25
static char check_serno() {
26
  int i;
27
  for (i = 0; i < RFID_SERNO_SIZE; i++) {
28
    if (serno[i] != serial_read_blocking()) {
29
      return 0;
30
    }
31
  }
32
  return 1;
33
}
34

    
35
void rfid_init() {
36
  serial_init();
37
}
38

    
39
void rfid_read_safe() {
40
  char n_err = 0, n_ok = 0;
41
  while (1) {
42
    serial_write(read_cmd, sizeof(read_cmd));
43
    if (serial_read_blocking() == RFID_OK) {
44
      if (n_ok == 0) {
45
        read_serno();
46
      } else if (!check_serno()) {
47
        zero_serno();
48
        return;
49
      }
50
      n_ok++;
51
      if (n_ok >= RFID_MIN_OK) {
52
        return;
53
      }
54
    } else {
55
      n_err++;
56
      if (n_err >= RFID_MAX_ERRS) {
57
        zero_serno();
58
        return;
59
      }
60
    }
61
    _delay_ms(10);
62
  }
63
}
64

    
65
void rfid_start_read() {
66
  serno_idx = -1;
67
  zero_serno(); // TODO temporary
68
  serial_flush();
69
  serial_write(read_cmd, sizeof(read_cmd));
70
}
71

    
72
char rfid_poll() {
73
  int c;
74

    
75
  c = serial_read();
76
  while (c >= 0) {
77

    
78
    if (serno_idx < 0) {
79
      if (c != RFID_OK) {
80
        zero_serno();
81
        return 1;
82
      }
83
    } else {
84
      serno[serno_idx] = c;
85
    }
86

    
87
    serno_idx++;
88
    if (serno_idx >= RFID_SERNO_SIZE) {
89
      return 1;
90
    }
91

    
92
    c = serial_read();
93
  }
94

    
95
  return 0;
96
}
97

    
98
void rfid_get_serno(char *buf) {
99
  memcpy(buf, serno, sizeof(serno));
100
}
101

    
102
char rfid_check_serno(char *buf) {
103
  return memcmp(buf, serno, sizeof(serno)) == 0;
104
}
105

    
106
char rfid_nonzero() {
107
  int i;
108
  for (i = 0; i < sizeof(serno); i++) {
109
    if (serno[i]) {
110
      return 1;
111
    }
112
  }
113
  return 0;
114
}