uart_set_all.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #define _DEFAULT_SOURCE
  2. #include <errno.h>
  3. #include <fcntl.h>
  4. #include <stdint.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <sys/select.h>
  9. #include <termios.h>
  10. #include <unistd.h>
  11. static uint16_t crc16(const uint8_t *data, size_t length) {
  12. uint16_t crc = 0xFFFF;
  13. for (size_t i = 0; i < length; ++i) {
  14. crc ^= (uint16_t)data[i] << 8;
  15. for (int bit = 0; bit < 8; ++bit)
  16. crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1);
  17. }
  18. return crc;
  19. }
  20. static size_t make_channel4(uint8_t *out, size_t capacity) {
  21. if (capacity < 38) return 0;
  22. uint8_t payload[32] = {0};
  23. for (int i = 18; i < 24; ++i) payload[i] = 100;
  24. for (int i = 24; i < 32; ++i) payload[i] = 20;
  25. payload[27] = 30;
  26. payload[31] = 10;
  27. out[0] = 0xA5; out[1] = 0x5A; out[2] = 0x01; out[3] = 0x20;
  28. memcpy(out + 4, payload, sizeof(payload));
  29. uint16_t crc = crc16(out + 2, 34);
  30. out[36] = (uint8_t)(crc & 0xFF);
  31. out[37] = (uint8_t)(crc >> 8);
  32. return 38;
  33. }
  34. static void dump_hex(const uint8_t *data, size_t length) {
  35. for (size_t i = 0; i < length; ++i) printf("%02X%s", data[i], i + 1 == length ? "\n" : " ");
  36. }
  37. int main(int argc, char **argv) {
  38. uint8_t frame[64];
  39. size_t frame_length = make_channel4(frame, sizeof(frame));
  40. if (frame_length == 0) return 2;
  41. if (argc == 1) {
  42. printf("TX "); dump_hex(frame, frame_length);
  43. return 0;
  44. }
  45. int fd = open(argv[1], O_RDWR | O_NOCTTY | O_NONBLOCK);
  46. if (fd < 0) { perror("open"); return 2; }
  47. struct termios tio;
  48. if (tcgetattr(fd, &tio) != 0) { perror("tcgetattr"); close(fd); return 2; }
  49. cfmakeraw(&tio);
  50. cfsetispeed(&tio, B921600);
  51. cfsetospeed(&tio, B921600);
  52. tio.c_cflag |= CLOCAL | CREAD;
  53. tio.c_cflag &= (tcflag_t)~CRTSCTS;
  54. if (tcsetattr(fd, TCSANOW, &tio) != 0) { perror("tcsetattr"); close(fd); return 2; }
  55. ssize_t sent = 0;
  56. while ((size_t)sent < frame_length) {
  57. ssize_t n = write(fd, frame + sent, frame_length - (size_t)sent);
  58. if (n > 0) sent += n;
  59. else if (errno != EAGAIN && errno != EINTR) { perror("write"); close(fd); return 2; }
  60. }
  61. printf("TX "); dump_hex(frame, frame_length);
  62. uint8_t rx[256]; size_t used = 0; fd_set set; struct timeval timeout = {5, 0};
  63. FD_ZERO(&set); FD_SET(fd, &set);
  64. if (select(fd + 1, &set, NULL, NULL, &timeout) > 0) {
  65. ssize_t n = read(fd, rx, sizeof(rx));
  66. if (n > 0) { used = (size_t)n; printf("RX "); dump_hex(rx, used); }
  67. } else {
  68. puts("RX timeout/no complete response");
  69. }
  70. close(fd);
  71. return used ? 0 : 1;
  72. }