Statistics
| Branch: | Revision:

root / toolbox / rfid.c @ 6ca98a3f

History | View | Annotate | Download (1.85 KB)

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

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

    
9
static int serno_idx;
10
static uint8_t serno[RFID_SERNO_SIZE];
11

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

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

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

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

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

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

    
73
char rfid_poll() {
74
  int c;
75

    
76
  while ((c = serial_read()) >= 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
  }
93

    
94
  return 0;
95
}
96

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

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

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