bin_recv.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* Simple binary receiver: size (4 bytes BE) + data + checksum (1 byte).
  2. Returns bytes received, or -1 on error/timeout.
  3. Prints '.' via io_putchar for each 512-byte chunk received. */
  4. #include "bin_recv.h"
  5. #include "serial.h"
  6. #include "io.h"
  7. #include "timer.h"
  8. #include "idle.h"
  9. #define TIMEOUT_MS 5000
  10. static int wait_byte(unsigned int port, unsigned char *out, unsigned int timeout_ms)
  11. {
  12. (void)port;
  13. return serial_ring_wait(timeout_ms, out);
  14. }
  15. int bin_recv(unsigned int port, void *buf, unsigned int max_size)
  16. {
  17. unsigned char *p = (unsigned char *)buf;
  18. unsigned int total = 0;
  19. unsigned char c;
  20. unsigned int i;
  21. unsigned int size = 0;
  22. unsigned char checksum = 0;
  23. unsigned char recv_sum = 0;
  24. /* Send 'R' to signal ready, wait for sender to start. */
  25. serial_putc(port, 'R');
  26. /* Read 4-byte size (big-endian). */
  27. for (i = 0; i < 4; i++) {
  28. if (!wait_byte(port, &c, TIMEOUT_MS)) {
  29. io_putstr("timeout reading size\n");
  30. return -1;
  31. }
  32. size = (size << 8) | c;
  33. }
  34. if (size == 0 || size > max_size) {
  35. io_putstr("bad size\n");
  36. return -1;
  37. }
  38. /* Read data bytes. */
  39. for (i = 0; i < size; i++) {
  40. if (!wait_byte(port, &c, TIMEOUT_MS)) {
  41. io_putstr("timeout at byte ");
  42. serial_putdec(port, i);
  43. io_putstr("\n");
  44. return -1;
  45. }
  46. p[i] = c;
  47. checksum += c;
  48. total++;
  49. if ((i + 1) % 512 == 0)
  50. io_putchar('.');
  51. }
  52. io_putchar('.');
  53. /* Read checksum byte. */
  54. if (!wait_byte(port, &recv_sum, TIMEOUT_MS)) {
  55. io_putstr("timeout reading checksum\n");
  56. return -1;
  57. }
  58. if (checksum != recv_sum) {
  59. io_putstr("checksum mismatch\n");
  60. return -1;
  61. }
  62. io_putchar('\n');
  63. return (int)total;
  64. }