#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <string.h>
#include <errno.h>
#include <sys/select.h>

int main() {
    int fd;
    struct termios tty;

    // 打开串口
    fd = open("/dev/ttyS7", O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd < 0) {
        perror("open");
        return 1;
    }

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

    // 配置波特率 460800, 8N1
    cfsetospeed(&tty, B460800);
    cfsetispeed(&tty, B460800);

    tty.c_cflag &= ~PARENB; // 无校验
    tty.c_cflag &= ~CSTOPB; // 1 停止位
    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 cmd[] = {0xFF, 0xAA, 0x00, 0x07, 0x01, 0x01, 0xF6};
    if (write(fd, cmd, sizeof(cmd)) != sizeof(cmd)) {
        perror("write");
        close(fd);
        return 1;
    }
    printf("建链帧已发送，等待 MCU 返回数据...\n");

    // 使用 select 非阻塞读取
    fd_set readfds;
    unsigned char buffer[256];
    int n;

    while (1) {
        FD_ZERO(&readfds);
        FD_SET(fd, &readfds);

        struct timeval timeout;
        timeout.tv_sec = 2;  // 超时时间 2 秒
        timeout.tv_usec = 0;

        int ret = select(fd + 1, &readfds, NULL, NULL, &timeout);
        if (ret > 0 && FD_ISSET(fd, &readfds)) {
            n = read(fd, buffer, sizeof(buffer));
            if (n > 0) {
                printf("收到 %d 字节: ", n);
                for (int i = 0; i < n; i++)
                    printf("%02X ", buffer[i]);
                printf("\n");
            }
        } else if (ret == 0) {
            printf("等待 MCU 数据超时...\n");
            // 可以选择继续等待或退出
        } else {
            perror("select");
            break;
        }
        usleep(100000); // 100ms
    }

    close(fd);
    return 0;
}