Use ring buffer for packet decoding in frame parser tool

This commit is contained in:
Maurizio Porrato 2018-12-14 10:13:06 +00:00
parent 867e953036
commit 0ce5c0c206
2 changed files with 46 additions and 18 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*~
*%
*.swp
*.py[co]

View File

@ -10,7 +10,6 @@ struct packet_s {
char status; char status;
char options[4]; char options[4];
char eol[2]; char eol[2];
char eos;
}; };
enum unit_e { enum unit_e {
@ -91,26 +90,51 @@ int parse_packet(struct packet_s *packet) {
return 0; return 0;
} }
int read_packet(struct packet_s *packet) { void log_packet(struct packet_s *packet) {
char *r;
int i; int i;
int valid; char *c = (char *)packet;
while (1) { for (i=0; i<sizeof(*packet); i++)
r = fgets((char *)packet, sizeof(*packet), stdin); putc(c[i], stderr);
if (r == NULL) }
int read_packet(struct packet_s *packet) {
char ring[sizeof(*packet)];
char *p;
int ring_pos;
char c;
int ch;
int shift;
p = (char *)packet;
ring_pos = 0;
shift = sizeof(*packet);
for (;;) {
ch = getc(stdin);
if (ch == EOF)
return 0; return 0;
// Sanity checks c = (char) ch;
// Packet must end with CR+LF ring[ring_pos] = c;
if (packet->eol[0] != '\r' || packet->eol[1] != '\n') ring_pos = (ring_pos + 1) % sizeof(*packet);
continue; if (((c & 0xf0) != 0x30) && (c != '\r') && (c != '\n')) {
// All fields must be encoded as 0x3X shift = sizeof(*packet);
for (valid=1, i=0; i<sizeof(*packet)-4; i++) } else {
if ((r[i] & 0xf0) != 0x30) if ((c == '\r') && (shift != 2)) {
valid = 0; shift = sizeof(*packet);
// Should also check for valid BCD values for digits continue;
if (valid) }
return 1; if (c == '\n') {
if (shift == 1) {
for (int i=0; i<sizeof(ring); i++)
p[i] = ring[(ring_pos + i) % sizeof(*packet)];
log_packet(packet);
return 1;
}
shift = sizeof(*packet);
continue;
}
shift = (shift > 0) ? shift - 1 : 0;
}
} }
} }