juegos

Juegos de terminal de Pancho: Catan (TUI, GUI, web, servidor, PicoCalc), ajedrez, calculadora y minijuegos
git clone https://git.lu3dhn.xyz/juegos.git
Log | Files | Refs

link.c (1522B)


      1 /* link.c - lineas con checksum sobre hal_link_read/hal_link_write. */
      2 #include <string.h>
      3 #include "hal.h"
      4 #include "link.h"
      5 
      6 static const char HEX[] = "0123456789ABCDEF";
      7 static char lin[640];
      8 static int linlen;
      9 
     10 void link_send(const char *line)
     11 {
     12     static char buf[600];
     13     int n = 0;
     14     uint8_t x = 0;
     15     for (const char *p = line; *p && n < 590; p++) { buf[n++] = *p; x ^= (uint8_t)*p; }
     16     buf[n++] = ' '; buf[n++] = '*'; buf[n++] = HEX[x >> 4]; buf[n++] = HEX[x & 15]; buf[n++] = '\n';
     17     hal_link_write(buf, n);
     18 }
     19 
     20 void link_send2(const char *a, const char *b)
     21 {
     22     char buf[600];
     23     int p = str_put(buf, sizeof buf, 0, a);
     24     if (p >= 0) str_put(buf, sizeof buf, p, b);
     25     link_send(buf);
     26 }
     27 
     28 int link_line(char *out, int n)
     29 {
     30     int got = hal_link_read(lin + linlen, (int)sizeof lin - 1 - linlen);
     31     if (got > 0) linlen += got;
     32     char *nl = memchr(lin, '\n', (size_t)linlen);
     33     if (!nl) {
     34         if (linlen >= (int)sizeof lin - 1) { linlen = 0; return -1; }
     35         return 0;
     36     }
     37     int l = (int)(nl - lin);
     38     int ok = 0;
     39     if (l >= 4 && l < n + 4 && lin[l - 4] == ' ' && lin[l - 3] == '*') {
     40         uint8_t x = 0;
     41         for (int i = 0; i < l - 4; i++) x ^= (uint8_t)lin[i];
     42         if (HEX[x >> 4] == lin[l - 2] && HEX[x & 15] == lin[l - 1]) {
     43             memcpy(out, lin, (size_t)(l - 4));
     44             out[l - 4] = 0;
     45             ok = 1;
     46         }
     47     }
     48     linlen -= l + 1;
     49     memmove(lin, nl + 1, (size_t)linlen);
     50     return ok ? 1 : -1;
     51 }
     52 
     53 void link_reset(void) { linlen = 0; }