Project

General

Profile

Statistics
| Branch: | Revision:

root / rfid-web / main.c @ master

History | View | Annotate | Download (1.62 KB)

1 f3599378 Tom Mullins
#include <sys/types.h>
2
#include <sys/stat.h>
3
#include <fcntl.h>
4
#include <termios.h>
5
#include <unistd.h>
6
#include <stdio.h>
7
#include <stdarg.h>
8
#include <stdlib.h>
9
#include <string.h>
10
11
#define RFID_OK 1
12
static char read_cmd[] = {'!', 'R', 'W', 1, 32};
13
static int serno;
14
15
void init_tty(int fd) {
16
  struct termios ios;
17
  bzero(&ios, sizeof(ios));
18
  ios.c_cflag = B9600 | CS8 | CREAD;
19
  tcsetattr(fd, TCSAFLUSH, &ios);
20
}
21
22
int bswap(int x) {
23
  return ((x&0xff) << 24) | ((x&0xff00) << 8)
24
    | ((x>>8) & 0xff00) | ((x>>24) & 0xff);
25
}
26
27
void read_all(int fd, void *buf, int n) {
28
  int nread;
29
  while (n > 0) {
30
    nread = read(fd, buf, n);
31
    buf += nread;
32
    n -= nread;
33
    usleep(10000);
34
  }
35
}
36
37
void write_all(int fd, void *buf, int n) {
38
  int nwritten;
39
  while (n > 0) {
40
    nwritten = write(fd, buf, n);
41
    buf += nwritten;
42
    n -= nwritten;
43
    usleep(10000);
44
  }
45
}
46
47
void fail_error(const char *error, ...) {
48
  va_list args;
49
  va_start(args, error);
50
  printf("Status: 500 Internal Server Error\n");
51
  printf("Content-type: text/plain\n\n");
52
  vprintf(error, args);
53
  va_end(args);
54
  exit(0);
55
}
56
57
int main(int argc, char **argv) {
58
  int fd;
59
  char status;
60
61
  fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);
62
  if (fd < 0)
63
    fail_error("Could not open /dev/ttyUSB0\n");
64
65
  init_tty(fd);
66
  tcflush(fd, TCIFLUSH);
67
  write_all(fd, read_cmd, sizeof(read_cmd));
68
69
  read_all(fd, &status, 1);
70
  if (status == RFID_OK) {
71
    read_all(fd, &serno, 4);
72
    serno = bswap(serno);
73
    printf("Content-type: text/plain\n\n");
74
    printf("%08x\n", serno);
75
  } else {
76
    fail_error("Reader gave error %d\n", (int)(unsigned char)status);
77
  }
78
79
  close(fd);
80
  return 0;
81
}