#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <string.h>
#include <errno.h>

int main() {
    const char *serial_path = "/dev/ttyS7";
    int fd = open(serial_path, O_RDWR | O_NOCTTY);
    if (fd < 0) {
        perror("open");
        return 1;
    }

    // 配置串口
    struct termios tty;
    if (tcgetattr(fd, &tty) != 0) {
        perror("tcgetattr");
        close(fd);
        return 1;
    }

    cfsetospeed(&tty, B460800);
    cfsetispeed(&tty, B460800);

    tty.c_cflag &= ~PARENB;    // 无奇偶校验
    tty.c_cflag &= ~CSTOPB;    // 1 stop bit
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;        // 8位
    tty.c_cflag |= CREAD | CLOCAL; // 开启接收
    tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // 原始模式
    tty.c_iflag &= ~(IXON | IXOFF | IXANY); // 关闭软件流控
    tty.c_oflag &= ~OPOST;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        perror("tcsetattr");
        close(fd);
        return 1;
    }

    // 建链帧
    unsigned char setup_frame[] = {0xFF, 0xAA, 0x00, 0x07, 0x01, 0x01, 0xF6};

    // 发送建链帧
    int w = write(fd, setup_frame, sizeof(setup_frame));
    if (w != sizeof(setup_frame)) {
        perror("write");
        close(fd);
        return 1;
    }
    printf("建链帧已发送，等待 MCU 返回数据...\n");

    // 循环读取 MCU 数据
    unsigned char buf[256];
    while (1) {
        int n = read(fd, buf, sizeof(buf));
        if (n > 0) {
            printf("接收 %d 字节: ", n);
            for (int i = 0; i < n; i++) {
                printf("%02X ", buf[i]);
            }
            printf("\n");
        } else if (n < 0) {
            perror("read");
            break;
        }
        usleep(100000); // 0.1秒避免 CPU 占满
    }

    close(fd);
    return 0;
}