#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <windows.h>
class SerialPortAllocator {
public:
// 构造函数,可以指定最大检测的COM端口号
SerialPortAllocator(int maxPort = 20) : maxPortNumber(maxPort) {}
// 获取第一个可用的串口号
char* getFirstAvailablePort()
{
std::vector<std::string> availablePorts = getAvailablePorts();
if (!availablePorts.empty())
{
// 返回第一个可用端口
strncpy_s(portBuffer, availablePorts[0].c_str(), sizeof(portBuffer) - 1);
return portBuffer;
}
// 没有可用端口
return nullptr;
}
// 获取所有可用串口列表
std::vector<std::string> getAvailablePorts() {
std::vector<std::string> availablePorts;
for (int i = 6; i <= maxPortNumber; ++i) {
std::string portName = "COM" + std::to_string(i);
if (isPortAvailable(portName)) {
availablePorts.push_back(portName);
}
}
return availablePorts;
}
private:
int maxPortNumber;
char portBuffer[10]; // 足够存储"COMxxx"
// 修正后的端口可用性检查函数
bool isPortAvailable(const std::string& portName) {
HANDLE hPort = CreateFileA(portName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr);
if (hPort == INVALID_HANDLE_VALUE)
{
// 检查具体错误代码
const DWORD error = GetLastError();
// 如果端口不存在,说明可以创建
if (error == ERROR_FILE_NOT_FOUND)
{
return true;
}
// 其他错误代码表示端口被占用
return false;
}
// 成功打开表示端口已被占用
CloseHandle(hPort);
return false;
}
};
串口自动分配
最新推荐文章于 2025-12-14 16:27:39 发布
2659

被折叠的 条评论
为什么被折叠?



