The serial ports the system exposes, sorted by name.
Linux: /dev/ttyACM* and /dev/ttyUSB*. macOS: /dev/cu.*. Windows: the ports in the SERIALCOMM registry key, such as COM3. A system that exposes none gives an empty list, and a port can always be opened by typing its path.
40{
41 std::vector<SerialPortEntry> ports;
42
43#if defined(MAYAFLUX_PLATFORM_WINDOWS)
44 HKEY key {};
45 if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_READ, &key) == ERROR_SUCCESS) {
46 for (DWORD index = 0;; ++index) {
47 char value_name[256] {};
48 DWORD value_name_size = sizeof(value_name);
49 char data[256] {};
50 DWORD data_size = sizeof(data);
51 DWORD type = 0;
52 const LONG status = RegEnumValueA(key, index, value_name, &value_name_size, nullptr, &type,
53 reinterpret_cast<LPBYTE>(data), &data_size);
54 if (status == ERROR_NO_MORE_ITEMS) {
55 break;
56 }
57 if (status != ERROR_SUCCESS || type != REG_SZ) {
58 continue;
59 }
60 const std::string port(data, std::find(data, data + data_size, '\0'));
61 if (!port.empty()) {
62 ports.push_back({ .path = port, .name = port });
63 }
64 }
65 RegCloseKey(key);
66 }
67#elif defined(MAYAFLUX_PLATFORM_MACOS)
68 std::error_code ec;
69 for (std::filesystem::directory_iterator entry("/dev", ec), end; !ec && entry != end; entry.increment(ec)) {
70 const std::string file = entry->path().filename().string();
71 if (file.starts_with("cu.")) {
72 ports.push_back({ .path = entry->path(), .name = file });
73 }
74 }
75#else
76 std::map<std::filesystem::path, std::filesystem::path> stable;
77 std::error_code ec;
78 for (std::filesystem::directory_iterator entry("/dev/serial/by-id", ec), end; !ec && entry != end; entry.increment(ec)) {
79 std::error_code resolve_ec;
80 const auto target = std::filesystem::canonical(entry->path(), resolve_ec);
81 if (!resolve_ec) {
82 stable[target] = entry->path();
83 }
84 }
85
86 ec.clear();
87 for (std::filesystem::directory_iterator entry("/dev", ec), end; !ec && entry != end; entry.increment(ec)) {
88 const std::string file = entry->path().filename().string();
89 if (!file.starts_with("ttyACM") && !file.starts_with("ttyUSB")) {
90 continue;
91 }
92 std::error_code resolve_ec;
93 const auto target = std::filesystem::canonical(entry->path(), resolve_ec);
94 const auto link = resolve_ec ? stable.end() : stable.find(target);
95 if (link != stable.end()) {
96 ports.push_back({ .path = link->second, .name = link->second.filename().string() });
97 } else {
98 ports.push_back({ .path = entry->path(), .name = file });
99 }
100 }
101#endif
102
104 return ports;
105}
A serial port the system exposes.