bin_recv.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. #define TIMEOUT_MS 5000
  9. static int wait_byte(unsigned int port, unsigned char *out, unsigned int timeout_ms)
  10. {
  11. unsigned int start = get_ticks_ms();
  12. while (get_ticks_ms() - start < timeout_ms) {
  13. if (serial_has_data(port)) {
  14. *out = (unsigned char)serial_getc_nb(port);
  15. return 1;
  16. }
  17. }
  18. return 0;
  19. }
  20. int bin_recv(unsigned int port, void *buf, unsigned int max_size)
  21. {
  22. unsigned char *p = (unsigned char *)buf;
  23. unsigned int total = 0;
  24. unsigned char c;
  25. unsigned int i;
  26. unsigned int size = 0;
  27. unsigned char checksum = 0;
  28. unsigned char recv_sum = 0;
  29. /* Send 'R' to signal ready, wait for sender to start. */
  30. serial_putc(port, 'R');
  31. /* Read 4-byte size (big-endian). */
  32. for (i = 0; i < 4; i++) {
  33. if (!wait_byte(port, &c, TIMEOUT_MS)) {
  34. io_putstr("timeout reading size\n");
  35. return -1;
  36. }
  37. size = (size << 8) | c;
  38. }
  39. if (size == 0 || size > max_size) {
  40. io_putstr("bad size\n");
  41. return -1;
  42. }
  43. /* Read data bytes. */
  44. for (i = 0; i < size; i++) {
  45. if (!wait_byte(port, &c, TIMEOUT_MS)) {
  46. io_putstr("timeout at byte ");
  47. serial_putdec(port, i);
  48. io_putstr("\n");
  49. return -1;
  50. }
  51. p[i] = c;
  52. checksum += c;
  53. total++;
  54. if ((i + 1) % 512 == 0)
  55. io_putchar('.');
  56. }
  57. io_putchar('.');
  58. /* Read checksum byte. */
  59. if (!wait_byte(port, &recv_sum, TIMEOUT_MS)) {
  60. io_putstr("timeout reading checksum\n");
  61. return -1;
  62. }
  63. if (checksum != recv_sum) {
  64. io_putstr("checksum mismatch\n");
  65. return -1;
  66. }
  67. io_putchar('\n');
  68. return (int)total;
  69. }