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

JNIEXPORT jstring JNICALL
Java_com_example_serialtest_MainActivity_readSerial(JNIEnv *env, jobject thiz) {
    int fd = open("/dev/ttyS7", O_RDWR | O_NOCTTY);
    if (fd < 0) {
        return (*env)->NewStringUTF(env, "Failed to open /dev/ttyS7");
    }

    struct termios tty;
    tcgetattr(fd, &tty);
    cfsetospeed(&tty, B460800);
    cfsetispeed(&tty, B460800);
    tcsetattr(fd, TCSANOW, &tty);

    // 建链帧
    unsigned char cmd[] = {0xFF, 0xAA, 0x00, 0x07, 0x01, 0x01, 0xF6};
    write(fd, cmd, sizeof(cmd));

    // 读取数据
    unsigned char buf[128];
    int n = read(fd, buf, sizeof(buf));
    close(fd);

    if (n <= 0) {
        return (*env)->NewStringUTF(env, "No data received");
    }

    char str[256];
    snprintf(str, sizeof(str), "Received %d bytes", n);
    return (*env)->NewStringUTF(env, str);
}