OpenCPN Partial API docs
Loading...
Searching...
No Matches
ser_ports.cpp
Go to the documentation of this file.
1/***************************************************************************
2 * Copyright (C) 2010 by David S. Register *
3 * *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
8 * *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, see <https://www.gnu.org/licenses/>. *
16 **************************************************************************/
17
24#include "config.h"
25
26#include <cassert>
27#include <iostream>
28
29#pragma GCC diagnostic push
30#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
31#include <regex>
32#pragma GCC diagnostic pop
33
34#include <string>
35#include <unordered_set>
36#include <vector>
37
38#ifdef __ANDROID__
39#include "androidUTIL.h"
40#include "qdebug.h"
41#endif
42
43#ifdef __MINGW32__
44#undef IPV6STRICT // mingw FTBS fix: missing struct ip_mreq
45#include <windows.h>
46#endif
47
48#ifdef __MSVC__
49#include <winsock2.h>
50#include <wx/msw/winundef.h>
51#endif
52
53#ifdef OCPN_USE_NEWSERIAL
54#include "serial/serial.h"
55#endif
56
57#ifdef HAVE_LIBUDEV
58#include <libudev.h>
59#endif
60
61#ifdef HAVE_DIRENT_H
62#include <dirent.h>
63#endif
64
65#ifdef HAVE_LINUX_SERIAL_H
66#include <linux/serial.h>
67#endif
68
69#ifdef HAVE_SYS_IOCTL_H
70#include <sys/ioctl.h>
71#endif
72
73#ifdef HAVE_FCNTL_H
74#include <fcntl.h>
75#endif
76
77#ifdef HAVE_SYS_FCNTL_H
78#include <sys/fcntl.h>
79#endif
80
81#ifdef HAVE_SYS_TYPES_H
82#include <sys/types.h>
83#endif
84
85#ifdef HAVE_READLINK
86#include <unistd.h>
87#endif
88
89#ifdef __linux__
90#include <termios.h>
91#include <linux/serial.h>
92#endif
93
94#ifdef _WIN32
95#include <winsock2.h>
96#include <windows.h>
97#include <setupapi.h>
98#endif
99
100#ifdef __APPLE__
101#include "model/macutils.h"
102#endif
103
104#include <wx/arrstr.h>
105#include <wx/log.h>
106#include <wx/utils.h>
107
108#include "model/config_vars.h"
110
111#ifdef __WXMSW__
112DEFINE_GUID(GARMIN_DETECT_GUID, 0x2c9c45c2L, 0x8e7d, 0x4c08, 0xa1, 0x2d, 0x81,
113 0x6b, 0xba, 0xe7, 0x22, 0xc0);
114#endif
115
116#ifdef __MINGW32__ // do I need this because of mingw, or because I am running
117 // mingw under wine?
118#ifndef GUID_CLASS_COMPORT
119DEFINE_GUID(GUID_CLASS_COMPORT, 0x86e0d1e0L, 0x8089, 0x11d0, 0x9c, 0xe4, 0x08,
120 0x00, 0x3e, 0x30, 0x1f, 0x73);
121#endif
122#endif
123
125 std::string info; // Free format info text, possibly empty
126 std::string path; // Complete /dev device path
127 device_data(const std::string& p, const std::string& i) : info(i), path(p) {}
128};
129
130struct symlink {
131 std::string path;
132 std::string target;
133 symlink(const std::string& p, const std::string& t) : path(p), target(t) {}
134};
135
136#ifdef __NetBSD__
137static int isTTYreal(const char* dev) {
138 if (strncmp("/dev/tty0", dev, 9) == 0) return 1;
139 if (strncmp("/dev/ttyU", dev, 9) == 0) return 1;
140 if (strcmp("/dev/gps", dev) == 0) return 1;
141 return 0;
142}
143
144#elif defined(HAVE_LINUX_SERIAL_H) && defined(HAVE_SYS_STAT_H)
145
147static std::string device_path(const char* dev) {
148 if (strstr(dev, "/sysfs/") != 0) return std::string(dev);
149 std::string path(dev);
150 return std::string("/dev") + path.substr(path.rfind('/'));
151}
152
153static int isTTYreal(const char* dev) {
154// gcc 12 bogus regex warning
155#pragma GCC diagnostic push
156#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
157
158 bool ok = false;
159
160 // This original check does not work in kernels > 5.12.
161 // See: https://github.com/torvalds/linux/commit/f64d74a59c476
162 std::string path = device_path(dev);
163 int fd = open(path.c_str(), O_RDONLY | O_NONBLOCK | O_NOCTTY);
164 if (fd >= 0) {
165 struct serial_struct serinfo;
166 if (ioctl(fd, TIOCGSERIAL, &serinfo) == 0) {
167 ok = serinfo.type != PORT_UNKNOWN;
168 }
169 if (!ok) {
170 // Accept any device with hardware lines DSR or CTS set.
171 int modem_sts;
172 if (ioctl(fd, TIOCMGET, &modem_sts) == 0) {
173 ok = (modem_sts & (TIOCM_CTS | TIOCM_LE | TIOCM_DSR)) != 0;
174 }
175 }
176 }
177 if (fd >= 0) close(fd);
178
179 if (!ok) {
180 // Accept standard ttyS0..ttyS3 + devices configured by udev:
181 static const std::vector<std::regex> patterns = {
182 std::regex("ttyS[0-3]$", std::regex_constants::ECMAScript),
183 std::regex("ttyUSB", std::regex_constants::ECMAScript),
184 std::regex("ttyACM", std::regex_constants::ECMAScript),
185 std::regex("ttyAMA", std::regex_constants::ECMAScript)};
186 for (auto re : patterns) {
187 if (std::regex_search(dev, re)) {
188 ok = true;
189 break;
190 }
191 }
192 }
193 return ok ? 1 : 0;
194
195#pragma GCC diagnostic pop
196}
197
198#else
199static int isTTYreal(const char* dev) { return 1; }
200
201#endif /* !NetBSD */
202
203static bool isTTYreal(const device_data& data) {
204 return isTTYreal(data.path.c_str());
205}
206
207#if defined(HAVE_DIRENT_H) && defined(HAVE_READLINK)
208
209#define HAVE_SYSFS_PORTS
210
212static std::vector<std::string> get_device_candidates() {
213 std::vector<std::string> devices;
214 DIR* dir;
215 struct dirent* ent;
216 dir = opendir("/sys/class/tty");
217 if (dir == 0) {
218 wxLogWarning("Cannot open /sys/class/tty: %s", strerror(errno));
219 return devices;
220 }
221 const std::string prefix("/dev/");
222 for (ent = readdir(dir); ent; ent = readdir(dir)) {
223 devices.push_back(prefix + ent->d_name);
224 }
225 closedir(dir);
226 return devices;
227}
228
230static std::vector<struct symlink> get_all_links() {
231 std::vector<struct symlink> links;
232 DIR* dir;
233 struct dirent* ent;
234 dir = opendir("/dev");
235 if (dir == 0) {
236 wxLogError("Cannot open /dev: %s", strerror(errno));
237 return links;
238 }
239 const std::string prefix("/dev/");
240 for (ent = readdir(dir); ent; ent = readdir(dir)) {
241 struct stat buf;
242 const std::string path(prefix + ent->d_name);
243 int r = lstat(path.c_str(), &buf);
244 if (r == -1) {
245 wxLogDebug("get_all_links: Cannot stat %s: %s", path.c_str(),
246 strerror(errno));
247 } else if (S_ISLNK(buf.st_mode)) {
248 char buff[PATH_MAX + 1];
249 ssize_t size = readlink(path.c_str(), buff, PATH_MAX);
250 assert(size > 0 && size < PATH_MAX);
251 std::string target(buff, size);
252 struct symlink link(path.c_str(), prefix + target);
253 links.push_back(link);
254 }
255 }
256 closedir(dir);
257 return links;
258}
259
261static wxArrayString* EnumerateSysfsSerialPorts() {
262 std::vector<std::string> ports;
263 auto all_ports = get_device_candidates();
264 wxLogDebug("Enumerate: found %d candidates", all_ports.size());
265 for (auto p : all_ports) {
266 if (isTTYreal(p.c_str())) ports.push_back(p);
267 }
268 wxLogDebug("Enumerate: found %d good ports", ports.size());
269 const auto targets =
270 std::unordered_set<std::string>(ports.begin(), ports.end());
271
272 auto all_links = get_all_links();
273 wxLogDebug("Enumerate: found %d links", all_links.size());
274 for (auto l : all_links) {
275 if (targets.find(l.target) != targets.end()) ports.push_back(l.path);
276 }
277 wxLogDebug("Enumerate: found %d devices", ports.size());
278
279 auto wx_ports = new wxArrayString();
280 for (auto p : ports) {
281 wx_ports->Add(p);
282 }
283 return wx_ports;
284}
285
286#endif // HAVE_DIRENT_H && defined(HAVE_READLINK)
287
288#if defined(HAVE_LIBUDEV)
289
291static std::string get_device_info(struct udev_device* ud) {
292 std::string info;
293 const char* prop = udev_device_get_property_value(ud, "ID_VENDOR");
294 if (prop) info += prop;
295 prop = udev_device_get_property_value(ud, "ID_MODEL");
296 if (prop) info += std::string(" - ") + prop;
297 return info;
298}
299
300// gcc bogus regex warning
301#pragma GCC diagnostic push
302#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
303
305static std::vector<struct device_data> get_links(struct udev_device* dev,
306 const std::regex& exclude) {
307 std::vector<struct device_data> items;
308 std::string info(" link -> ");
309 info += udev_device_get_devnode(dev);
310 struct udev_list_entry* link = udev_device_get_devlinks_list_entry(dev);
311 while (link) {
312 const char* linkname = udev_list_entry_get_name(link);
313 if (!std::regex_search(linkname, exclude)) {
314 struct device_data item(linkname, info);
315 items.push_back(item);
316 }
317 link = udev_list_entry_get_next(link);
318 }
319 return items;
320}
321
322static std::vector<struct device_data> enumerate_udev_ports(struct udev* udev) {
323 struct udev_enumerate* enumerate = udev_enumerate_new(udev);
324 udev_enumerate_add_match_subsystem(enumerate, "tty");
325 udev_enumerate_scan_devices(enumerate);
326 struct udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate);
327
328 const std::regex bad_ttys(".*tty[0-9][0-9]|^/dev/serial/.*|.*ttyS[0-9][0-9]");
329 std::vector<struct device_data> items;
330 struct udev_list_entry* entry;
331 udev_list_entry_foreach(entry, devices) {
332 const char* const path = udev_list_entry_get_name(entry);
333 struct udev_device* device = udev_device_new_from_syspath(udev, path);
334 const char* const devnode = udev_device_get_devnode(device);
335 struct device_data item(devnode, get_device_info(device));
336 if (!std::regex_search(devnode, bad_ttys) &&
337 (isTTYreal(path) || item.info.length() > 0)) {
338 items.push_back(item);
339 auto links = get_links(device, bad_ttys);
340 items.insert(items.end(), links.begin(), links.end());
341 }
342 udev_device_unref(device);
343 }
344 udev_enumerate_unref(enumerate);
345 return items;
346}
347
348#pragma GCC diagnostic pop
349static wxArrayString* EnumerateUdevSerialPorts() {
350 struct udev* udev = udev_new();
351 auto dev_items = enumerate_udev_ports(udev);
352 wxArrayString* ports = new wxArrayString;
353 for (const auto& item : dev_items) {
354 std::string port(item.path);
355 if (item.info.size() > 0) port += std::string(" - ") + item.info;
356 ports->Add(port);
357 }
358 udev_unref(udev);
359 return ports;
360}
361
362#endif // HAVE_LIBUDEV
363
364#ifdef __WXMSW__
365static wxArrayString* EnumerateWindowsSerialPorts() {
366 wxArrayString* preturn = new wxArrayString;
367 /*************************************************************************
368 * Windows provides no system level enumeration of available serial ports
369 * There are several ways of doing this.
370 *
371 *************************************************************************/
372
373 // Method 1: Use GetDefaultCommConfig()
374 // Try first {g_nCOMPortCheck} possible COM ports, check for a default
375 // configuration
376 // This method will not find some Bluetooth SPP ports
377 for (int i = 1; i < g_nCOMPortCheck; i++) {
378 wxString s;
379 s.Printf("COM%d", i);
380
381 COMMCONFIG cc;
382 DWORD dwSize = sizeof(COMMCONFIG);
383 if (GetDefaultCommConfig(s.fn_str(), &cc, &dwSize))
384 preturn->Add(wxString(s));
385 }
386
387 // Method 3: WDM-Setupapi
388 // This method may not find XPort virtual ports,
389 // but does find Bluetooth SPP ports
390
391 GUID* guidDev = (GUID*)&GUID_CLASS_COMPORT;
392
393 HDEVINFO hDevInfo = INVALID_HANDLE_VALUE;
394
395 hDevInfo = SetupDiGetClassDevs(guidDev, NULL, NULL,
396 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
397
398 if (hDevInfo != INVALID_HANDLE_VALUE) {
399 BOOL bOk = TRUE;
400 SP_DEVICE_INTERFACE_DATA ifcData;
401
402 ifcData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
403 for (DWORD ii = 0; bOk; ii++) {
404 bOk = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guidDev, ii, &ifcData);
405 if (bOk) {
406 // Got a device. Get the details.
407
408 SP_DEVINFO_DATA devdata = {sizeof(SP_DEVINFO_DATA)};
409 bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifcData, NULL, 0, NULL,
410 &devdata);
411
412 // We really only need devdata
413 if (!bOk) {
414 if (GetLastError() ==
415 122) // ERROR_INSUFFICIENT_BUFFER, OK in this case
416 bOk = true;
417 }
418
419 // We could get friendly name and/or description here
420 TCHAR fname[256] = {0};
421 TCHAR desc[256] = {0};
422 if (bOk) {
423 BOOL bSuccess = SetupDiGetDeviceRegistryProperty(
424 hDevInfo, &devdata, SPDRP_FRIENDLYNAME, NULL, (PBYTE)fname,
425 sizeof(fname), NULL);
426
427 bSuccess = bSuccess && SetupDiGetDeviceRegistryProperty(
428 hDevInfo, &devdata, SPDRP_DEVICEDESC, NULL,
429 (PBYTE)desc, sizeof(desc), NULL);
430 }
431
432 // Get the "COMn string from the registry key
433 if (bOk) {
434 bool bFoundCom = false;
435 TCHAR dname[256];
436 HKEY hDeviceRegistryKey =
437 SetupDiOpenDevRegKey(hDevInfo, &devdata, DICS_FLAG_GLOBAL, 0,
438 DIREG_DEV, KEY_QUERY_VALUE);
439 if (INVALID_HANDLE_VALUE != hDeviceRegistryKey) {
440 DWORD RegKeyType;
441 wchar_t wport[80];
442 LPCWSTR cstr = wport;
443 MultiByteToWideChar(0, 0, "PortName", -1, wport, 80);
444 DWORD len = sizeof(dname);
445
446 int result = RegQueryValueEx(hDeviceRegistryKey, cstr, 0,
447 &RegKeyType, (PBYTE)dname, &len);
448 if (result == 0) bFoundCom = true;
449 }
450
451 if (bFoundCom) {
452 wxString port(dname, wxConvUTF8);
453
454 // If the port has already been found, remove the prior entry
455 // in favor of this entry, which will have descriptive
456 // information appended
457 for (unsigned int n = 0; n < preturn->GetCount(); n++) {
458 if ((preturn->Item(n)).IsSameAs(port)) {
459 preturn->RemoveAt(n);
460 break;
461 }
462 }
463 wxString desc_name(desc, wxConvUTF8); // append "description"
464 port += " ";
465 port += desc_name;
466
467 preturn->Add(port);
468 }
469 }
470 }
471 } // for
472 } // if
473
474 // Search for Garmin device driver on Windows platforms
475
476 HDEVINFO hdeviceinfo = INVALID_HANDLE_VALUE;
477
478 hdeviceinfo = SetupDiGetClassDevs((GUID*)&GARMIN_DETECT_GUID, NULL, NULL,
479 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
480
481 if (hdeviceinfo != INVALID_HANDLE_VALUE) {
482 if (GarminProtocolHandler::IsGarminPlugged()) {
483 wxLogMessage("EnumerateSerialPorts() Found Garmin USB Device.");
484 preturn->Add("Garmin-USB"); // Add generic Garmin selectable device
485 }
486 }
487
488 return preturn;
489}
490
491#endif // __WXMSW__
492
493#if defined(OCPN_USE_SYSFS_PORTS) && defined(HAVE_SYSFS_PORTS)
494
495wxArrayString* EnumerateSerialPorts() { return EnumerateSysfsSerialPorts(); }
496
497#elif defined(OCPN_USE_UDEV_PORTS) && defined(HAVE_LIBUDEV)
498
499wxArrayString* EnumerateSerialPorts() { return EnumerateUdevSerialPorts(); }
500
501#elif defined(__ANDROID__)
502
503wxArrayString* EnumerateSerialPorts() { return androidGetSerialPortsArray(); }
504
505#elif defined(__WXOSX__)
506
507wxArrayString* EnumerateSerialPorts() {
508 wxArrayString* preturn = new wxArrayString;
509 char* paPortNames[MAX_SERIAL_PORTS];
510 int iPortNameCount;
511
512 memset(paPortNames, 0x00, sizeof(paPortNames));
513 iPortNameCount = FindSerialPortNames(&paPortNames[0], MAX_SERIAL_PORTS);
514 for (int iPortIndex = 0; iPortIndex < iPortNameCount; iPortIndex++) {
515 wxString sm(paPortNames[iPortIndex], wxConvUTF8);
516 preturn->Add(sm);
517 free(paPortNames[iPortIndex]);
518 }
519 return preturn;
520}
521
522#elif defined(__WXMSW__)
523
524wxArrayString* EnumerateSerialPorts() { return EnumerateWindowsSerialPorts(); }
525
526#elif defined(OCPN_USE_NEWSERIAL)
527
528wxArrayString* EnumerateSerialPorts() {
529 wxArrayString* preturn = new wxArrayString;
530 std::vector<serial::PortInfo> ports = serial::list_ports();
531 for (auto it = ports.begin(); it != ports.end(); ++it) {
532 wxString port(it->port);
533 if (it->description.length() > 0 && it->description != "n/a") {
534 port.Append(" - ");
535 port.Append(wxString::FromUTF8((it->description).c_str()));
536 }
537 preturn->Add(port);
538 }
539 return preturn;
540}
541
542#else
543
544#error "Cannot enumerate serial ports (missing libudev.h?)"
545
546#endif // outermost if - elif - else
Global variables stored in configuration file.
NMEA Data Object.
MacOS hardware probing functions.
wxArrayString * EnumerateSerialPorts(void)
Enumerate all serial ports.
std::vector< PortInfo > list_ports()
Lists the serial ports available on the system.