]> git.sesse.net Git - ultimatescore/blob - client/bodet.cpp
Start some BT6000 data decoding.
[ultimatescore] / client / bodet.cpp
1 // Bodet BT-6000 decoder.
2
3 #include <stdio.h>
4 #include <unistd.h>
5
6 #include <string>
7 #include <vector>
8
9 using namespace std;
10
11 void process(const string &buf)
12 {
13         unsigned char checksum = 0;
14         for (size_t i = 1; i <= buf.size() - 2; ++i) {
15                 checksum ^= buf[i];
16         }
17         checksum &= 0x7f;
18         if (checksum < 0x20) {
19                 checksum += 0x20;
20         }
21         if (checksum != buf.back()) {
22         //      fprintf(stderr, "discarding message with broken checksum: [%s] [%x vs. %x]\n", buf.c_str(), checksum, buf.back());
23         } else {
24                 string realmsg = buf.substr(3, buf.size() - 5);
25                 fprintf(stderr, "msg: [%s]\n", realmsg.c_str());
26         }
27 }
28
29 int main(int argc, char **argv)
30 {
31         // TODO: open serial port
32
33         string buf;
34
35         for ( ;; ) {
36                 char ch;
37                 int ret = read(0, &ch, 1);
38                 if (ret == -1) {
39                         perror("read");
40                         exit(1);
41                 }
42                 if (ret == 0) {
43                         fprintf(stderr, "short read\n");
44                         exit(1);
45                 }
46
47                 if (ch == 1) {  // SOH
48                         buf = ch;
49                         continue;
50                 } 
51                 if (buf.size() == 1) {
52                         // Address
53                         buf.push_back(ch);
54                         continue;
55                 }
56                 if (ch == 2) {  // STX
57                         if (buf.size() == 2) {
58                                 buf.push_back(ch);
59                         } else {
60                                 buf.clear();  // STX out-of-order
61                         }
62                         continue;
63                 }
64
65                 if (!buf.empty() && buf.back() == 3) {  // Last was ETX, so this is LTC.
66                         buf.push_back(ch);
67                         process(buf);
68                         buf.clear();
69                         continue;
70                 }
71
72                 if (ch == 3) {  // ETX
73                         if (buf.size() >= 4) {
74                                 buf.push_back(ch);
75                         } else {
76                                 buf.clear();  // ETX out-of-order
77                         }
78                         continue;
79                 }
80                 buf.push_back(ch);
81         }
82 }