#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>

#define SERIAL_DEVICE "/dev/ttyS7"
#define BAUDRATE B460800

int main() {
    int fd = open(SERIAL_DEVICE, O_RDWR | O_NOCTTY);
    if (fd < 0) {
        perror("open serial");
        return -1;
    }

    struct termios tty;
    if (tcgetattr(fd, &tty) != 0) {
        perror("tcgetattr");
        close(fd);
        return -1;
    }

    // 配置串口
    cfsetospeed(&tty, BAUDRATE);
    cfsetispeed(&tty, BAUDRATE);

    tty.c_cflag |= (CLOCAL | CREAD);    // 本地连接，接收使能
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;                 // 8位数据
    tty.c_cflag &= ~PARENB;             // 无奇偶校验
    tty.c_cflag &= ~CSTOPB;             // 1停止位
    tty.c_cflag &= ~CRTSCTS;            // 无硬件流控

    tty.c_iflag = 0;
    tty.c_oflag = 0;
    tty.c_lflag = 0;

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

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

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

    // 循环读取数据
    while (1) {
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(fd, &readfds);

        struct timeval timeout;
        timeout.tv_sec = 3;
        timeout.tv_usec = 0;

        int ret = select(fd+1, &readfds, NULL, NULL, &timeout);
        if (ret < 0) {
            perror("select");
            break;
        } else if (ret == 0) {
            // 超时
            printf("等待 MCU 数据超时...\n");
            continue;
        }

        if (FD_ISSET(fd, &readfds)) {
            unsigned char buf[256];
            int n = read(fd, buf, sizeof(buf));
            if (n < 0) {
                perror("read");
                break;
            } else if (n == 0) {
                // 串口关闭
                printf("串口关闭\n");
                break;
            } else {
                printf("收到 %d 字节数据: ", n);
                for (int i=0;i<n;i++) {
                    printf("%02X ", buf[i]);
                }
                printf("\n");
            }
        }
    }

    close(fd);
    return 0;
}