#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <windows.h>
class SerialPortAllocator {
public:
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];
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;
}
};