| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- #define _DEFAULT_SOURCE
- #include <errno.h>
- #include <fcntl.h>
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/select.h>
- #include <termios.h>
- #include <unistd.h>
- static uint16_t crc16(const uint8_t *data, size_t length) {
- uint16_t crc = 0xFFFF;
- for (size_t i = 0; i < length; ++i) {
- crc ^= (uint16_t)data[i] << 8;
- for (int bit = 0; bit < 8; ++bit)
- crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1);
- }
- return crc;
- }
- static size_t make_channel4(uint8_t *out, size_t capacity) {
- if (capacity < 38) return 0;
- uint8_t payload[32] = {0};
- for (int i = 18; i < 24; ++i) payload[i] = 100;
- for (int i = 24; i < 32; ++i) payload[i] = 20;
- payload[27] = 30;
- payload[31] = 10;
- out[0] = 0xA5; out[1] = 0x5A; out[2] = 0x01; out[3] = 0x20;
- memcpy(out + 4, payload, sizeof(payload));
- uint16_t crc = crc16(out + 2, 34);
- out[36] = (uint8_t)(crc & 0xFF);
- out[37] = (uint8_t)(crc >> 8);
- return 38;
- }
- static void dump_hex(const uint8_t *data, size_t length) {
- for (size_t i = 0; i < length; ++i) printf("%02X%s", data[i], i + 1 == length ? "\n" : " ");
- }
- int main(int argc, char **argv) {
- uint8_t frame[64];
- size_t frame_length = make_channel4(frame, sizeof(frame));
- if (frame_length == 0) return 2;
- if (argc == 1) {
- printf("TX "); dump_hex(frame, frame_length);
- return 0;
- }
- int fd = open(argv[1], O_RDWR | O_NOCTTY | O_NONBLOCK);
- if (fd < 0) { perror("open"); return 2; }
- struct termios tio;
- if (tcgetattr(fd, &tio) != 0) { perror("tcgetattr"); close(fd); return 2; }
- cfmakeraw(&tio);
- cfsetispeed(&tio, B921600);
- cfsetospeed(&tio, B921600);
- tio.c_cflag |= CLOCAL | CREAD;
- tio.c_cflag &= (tcflag_t)~CRTSCTS;
- if (tcsetattr(fd, TCSANOW, &tio) != 0) { perror("tcsetattr"); close(fd); return 2; }
- ssize_t sent = 0;
- while ((size_t)sent < frame_length) {
- ssize_t n = write(fd, frame + sent, frame_length - (size_t)sent);
- if (n > 0) sent += n;
- else if (errno != EAGAIN && errno != EINTR) { perror("write"); close(fd); return 2; }
- }
- printf("TX "); dump_hex(frame, frame_length);
- uint8_t rx[256]; size_t used = 0; fd_set set; struct timeval timeout = {5, 0};
- FD_ZERO(&set); FD_SET(fd, &set);
- if (select(fd + 1, &set, NULL, NULL, &timeout) > 0) {
- ssize_t n = read(fd, rx, sizeof(rx));
- if (n > 0) { used = (size_t)n; printf("RX "); dump_hex(rx, used); }
- } else {
- puts("RX timeout/no complete response");
- }
- close(fd);
- return used ? 0 : 1;
- }
|