Project

General

Profile

Statistics
| Branch: | Revision:

root / toolbox / rfid.c @ 6fbe093f

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 seek_cmd[] = {0xFF, 0x00, 0x01, 0x82, 0x83};
8

    
9
#define FRAME_SIZE(data_size) ((data_size)+4)
10
#define MAX_FRAME_SIZE FRAME_SIZE(RFID_SERNO_SIZE+2)
11

    
12
#define RESP_START    0
13
#define RESP_RESERVED 1
14
#define RESP_LENGTH   2
15
#define RESP_CMD      3
16
#define RESP_DATA     4
17
static uint8_t response[MAX_FRAME_SIZE];
18
static uint8_t resp_idx;
19

    
20
static uint8_t serno[RFID_SERNO_SIZE];
21

    
22
static void zero_serno() {
23
  int i;
24
  for (i = 0; i < RFID_SERNO_SIZE; i++) {
25
    serno[i] = 0;
26
  }
27
}
28

    
29
void rfid_init() {
30
  serial_init();
31
}
32

    
33
void rfid_start_read() {
34
  resp_idx = 0;
35
  serial_flush();
36
  serial_write(seek_cmd, sizeof(seek_cmd));
37
}
38

    
39
char parse_response() {
40
  uint8_t sum;
41
  int resp_csum, i;
42

    
43
  if (response[RESP_LENGTH] != RFID_SERNO_SIZE+2
44
      || response[RESP_CMD] != 0x82) {
45
    zero_serno();
46
    return 0;
47
  }
48

    
49
  resp_csum = response[RESP_LENGTH] + RESP_CMD;
50
  sum = 0;
51
  for (i = RESP_LENGTH; i < resp_csum; i++) {
52
    sum += response[i];
53
  }
54
  if (response[resp_csum] != sum) {
55
    //return 0; TODO
56
  }
57

    
58
  memcpy(serno, &response[RESP_DATA+1], RFID_SERNO_SIZE);
59
  return 1;
60
}
61

    
62
char rfid_poll() {
63
  int c;
64

    
65
  while ((c = serial_read()) >= 0) {
66

    
67
    if (resp_idx < sizeof(response)) {
68
      response[resp_idx] = c;
69
    }
70
    resp_idx++;
71

    
72
    if (resp_idx == 1) {
73

    
74
      // restart if the frame start is invalid
75
      if (response[RESP_START] != 0xFF) {
76
        resp_idx = 0;
77
      }
78

    
79
    } else if (resp_idx > RESP_LENGTH) {
80

    
81
      // check if we're done with current packet
82
      if (resp_idx >= FRAME_SIZE(response[RESP_LENGTH])) {
83
        resp_idx = 0;
84
        serial_write(seek_cmd, sizeof(seek_cmd));
85
        if (parse_response()) {
86
          return 1;
87
        }
88
      }
89

    
90
    }
91
  }
92

    
93
  return 0;
94
}
95

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