From c1c9c0136625fdf262735abbb8712b8a629207b5 Mon Sep 17 00:00:00 2001 From: Martin Mares Date: Wed, 19 Feb 2020 22:58:34 +0100 Subject: [PATCH] BSB: Provisional parser and generator of packets --- test-bsb/gen.c | 41 +++++++++++++++++++++++ test-bsb/parse.c | 86 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 test-bsb/gen.c create mode 100644 test-bsb/parse.c diff --git a/test-bsb/gen.c b/test-bsb/gen.c new file mode 100644 index 0000000..fb4fdbf --- /dev/null +++ b/test-bsb/gen.c @@ -0,0 +1,41 @@ +#include +#include + +typedef unsigned char byte; +typedef unsigned int uint; +typedef uint16_t u16; + +u16 crc_update(u16 crc, byte data) +{ + crc = crc ^ (data << 8); + for (uint i=0; i<8; i++) { + if (crc & 0x8000) + crc = (crc << 1) ^ 0x1021; + else + crc <<= 1; + } + return crc; +} + +byte msg[] = { + 0xdc, // sync + 0x80 | 0x42, // src + 0x00, // dest + 0x00, // length (will be filled) + 0x06, // command + 0x3d, 0x2e, 0x11, 0x25, +}; + +int main(void) +{ + msg[3] = sizeof(msg) + 2; + + u16 crc = 0; + for (uint i=0; i < sizeof(msg); i++) { + printf("%02x ", msg[i]); + crc = crc_update(crc, msg[i]); + } + printf("%02x %02x\n", crc >> 8, crc & 0xff); + + return 0; +} diff --git a/test-bsb/parse.c b/test-bsb/parse.c new file mode 100644 index 0000000..bec15a1 --- /dev/null +++ b/test-bsb/parse.c @@ -0,0 +1,86 @@ +#include +#include +#include + +typedef unsigned char byte; +typedef unsigned int uint; +typedef uint16_t u16; + +uint rd(void) +{ + uint x; + if (scanf("%x", &x) == 1) + return x; + else { + puts("EOF"); + exit(1); + } +} + +u16 crc_update(u16 crc, byte data) +{ + crc = crc ^ (data << 8); + for (uint i=0; i<8; i++) { + if (crc & 0x8000) + crc = (crc << 1) ^ 0x1021; + else + crc <<= 1; + } + return crc; +} + +int main(void) +{ + byte pkt[256]; + + for (;;) { + pkt[0] = rd(); + if (pkt[0] != 0xdc) { + printf("# Bad sync: %02x\n", pkt[0]); + continue; + } + + int len = 1; + while (len < 4 || len < pkt[3]) { + pkt[len++] = rd(); + } + + for (int i=0; i %02x: ", pkt[1], pkt[2]); + switch (pkt[4]) { + case 2: + printf("INFO %04x:%04x =", (pkt[5]<<8) | pkt[6], (pkt[7]<<8) | pkt[8]); + for (int i=9; i