#include "CSerialPort/SerialPortInfo.h"

#include <dirent.h>
#include <cstring>
#include <string>

namespace itas109 {

std::vector<SerialPortInfo> CSerialPortInfo::availablePortInfos() {
    std::vector<SerialPortInfo> result;

    // 扫描 /dev 目录，找 ttyUSB / ttyCH341USB / ttyACM / ttyS 等设备
    DIR* dir = opendir("/dev");
    if (!dir) return result;

    struct dirent* entry;
    while ((entry = readdir(dir)) != nullptr) {
        const char* name = entry->d_name;
        if (std::strstr(name, "ttyUSB") != nullptr  ||
            std::strstr(name, "ttyCH341") != nullptr ||
            std::strstr(name, "ttyACM") != nullptr)
        {
            SerialPortInfo info;
            std::string fullPath = std::string("/dev/") + name;
            std::strncpy(info.portName, fullPath.c_str(), sizeof(info.portName) - 1);
            std::strncpy(info.description, name, sizeof(info.description) - 1);
            result.push_back(info);
        }
    }
    closedir(dir);

    return result;
}

} // namespace itas109
