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 assert(readlink(path.c_str(), buff, PATH_MAX) >= 0);
250 std::string target(buff);
251 struct symlink link(path.c_str(), prefix + target);
252 links.push_back(link);
253 }
254 }
255 closedir(dir);
256 return links;
257}
258
260static wxArrayString* EnumerateSysfsSerialPorts() {
261 std::vector<std::string> ports;
262 auto all_ports = get_device_candidates();
263 wxLogDebug("Enumerate: found %d candidates", all_ports.size());
264 for (auto p : all_ports) {
265 if (isTTYreal(p.c_str())) ports.push_back(p);
266 }
267 wxLogDebug("Enumerate: found %d good ports", ports.size());
268 const auto targets =
269 std::unordered_set<std::string>(ports.begin(), ports.end());
270
271 auto all_links = get_all_links();
272 wxLogDebug("Enumerate: found %d links", all_links.size());
273 for (auto l : all_links) {
274 if (targets.find(l.target) != targets.end()) ports.push_back(l.path);
275 }
276 wxLogDebug("Enumerate: found %d devices", ports.size());
277
278 auto wx_ports = new wxArrayString();
279 for (auto p : ports) {
280 wx_ports->Add(p);
281 }
282 return wx_ports;
283}
284
285#endif // HAVE_DIRENT_H && defined(HAVE_READLINK)
286
287#if defined(HAVE_LIBUDEV)
288
290static std::string get_device_info(struct udev_device* ud) {
291 std::string info;
292 const char* prop = udev_device_get_property_value(ud, "ID_VENDOR");
293 if (prop) info += prop;
294 prop = udev_device_get_property_value(ud, "ID_MODEL");
295 if (prop) info += std::string(" - ") + prop;
296 return info;
297}
298
299// gcc bogus regex warning
300#pragma GCC diagnostic push
301#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
302
304static std::vector<struct device_data> get_links(struct udev_device* dev,
305 const std::regex& exclude) {
306 std::vector<struct device_data> items;
307 std::string info(" link -> ");
308 info += udev_device_get_devnode(dev);
309 struct udev_list_entry* link = udev_device_get_devlinks_list_entry(dev);
310 while (link) {
311 const char* linkname = udev_list_entry_get_name(link);
312 if (!std::regex_search(linkname, exclude)) {
313 struct device_data item(linkname, info);
314 items.push_back(item);
315 }
316 link = udev_list_entry_get_next(link);
317 }
318 return items;
319}
320
321static std::vector<struct device_data> enumerate_udev_ports(struct udev* udev) {
322 struct udev_enumerate* enumerate = udev_enumerate_new(udev);
323 udev_enumerate_add_match_subsystem(enumerate, "tty");
324 udev_enumerate_scan_devices(enumerate);
325 struct udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate);
326
327 const std::regex bad_ttys(".*tty[0-9][0-9]|^/dev/serial/.*|.*ttyS[0-9][0-9]");
328 std::vector<struct device_data> items;
329 struct udev_list_entry* entry;
330 udev_list_entry_foreach(entry, devices) {
331 const char* const path = udev_list_entry_get_name(entry);
332 struct udev_device* device = udev_device_new_from_syspath(udev, path);
333 const char* const devnode = udev_device_get_devnode(device);
334 struct device_data item(devnode, get_device_info(device));
335 if (!std::regex_search(devnode, bad_ttys) &&
336 (isTTYreal(path) || item.info.length() > 0)) {
337 items.push_back(item);
338 auto links = get_links(device, bad_ttys);
339 items.insert(items.end(), links.begin(), links.end());
340 }
341 udev_device_unref(device);
342 }
343 return items;
344}
345
346#pragma GCC diagnostic pop
347static wxArrayString* EnumerateUdevSerialPorts() {
348 struct udev* udev = udev_new();
349 auto dev_items = enumerate_udev_ports(udev);
350 wxArrayString* ports = new wxArrayString;
351 for (const auto& item : dev_items) {
352 std::string port(item.path);
353 if (item.info.size() > 0) port += std::string(" - ") + item.info;
354 ports->Add(port);
355 }
356 return ports;
357}
358
359#endif // HAVE_LIBUDEV
360
361#ifdef __WXMSW__
362static wxArrayString* EnumerateWindowsSerialPorts() {
363 wxArrayString* preturn = new wxArrayString;
364 /*************************************************************************
365 * Windows provides no system level enumeration of available serial ports
366 * There are several ways of doing this.
367 *
368 *************************************************************************/
369
370 // Method 1: Use GetDefaultCommConfig()
371 // Try first {g_nCOMPortCheck} possible COM ports, check for a default
372 // configuration
373 // This method will not find some Bluetooth SPP ports
374 for (int i = 1; i < g_nCOMPortCheck; i++) {
375 wxString s;
376 s.Printf("COM%d", i);
377
378 COMMCONFIG cc;
379 DWORD dwSize = sizeof(COMMCONFIG);
380 if (GetDefaultCommConfig(s.fn_str(), &cc, &dwSize))
381 preturn->Add(wxString(s));
382 }
383
384 // Method 3: WDM-Setupapi
385 // This method may not find XPort virtual ports,
386 // but does find Bluetooth SPP ports
387
388 GUID* guidDev = (GUID*)&GUID_CLASS_COMPORT;
389
390 HDEVINFO hDevInfo = INVALID_HANDLE_VALUE;
391
392 hDevInfo = SetupDiGetClassDevs(guidDev, NULL, NULL,
393 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
394
395 if (hDevInfo != INVALID_HANDLE_VALUE) {
396 BOOL bOk = TRUE;
397 SP_DEVICE_INTERFACE_DATA ifcData;
398
399 ifcData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
400 for (DWORD ii = 0; bOk; ii++) {
401 bOk = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guidDev, ii, &ifcData);
402 if (bOk) {
403 // Got a device. Get the details.
404
405 SP_DEVINFO_DATA devdata = {sizeof(SP_DEVINFO_DATA)};
406 bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifcData, NULL, 0, NULL,
407 &devdata);
408
409 // We really only need devdata
410 if (!bOk) {
411 if (GetLastError() ==
412 122) // ERROR_INSUFFICIENT_BUFFER, OK in this case
413 bOk = true;
414 }
415
416 // We could get friendly name and/or description here
417 TCHAR fname[256] = {0};
418 TCHAR desc[256] = {0};
419 if (bOk) {
420 BOOL bSuccess = SetupDiGetDeviceRegistryProperty(
421 hDevInfo, &devdata, SPDRP_FRIENDLYNAME, NULL, (PBYTE)fname,
422 sizeof(fname), NULL);
423
424 bSuccess = bSuccess && SetupDiGetDeviceRegistryProperty(
425 hDevInfo, &devdata, SPDRP_DEVICEDESC, NULL,
426 (PBYTE)desc, sizeof(desc), NULL);
427 }
428
429 // Get the "COMn string from the registry key
430 if (bOk) {
431 bool bFoundCom = false;
432 TCHAR dname[256];
433 HKEY hDeviceRegistryKey =
434 SetupDiOpenDevRegKey(hDevInfo, &devdata, DICS_FLAG_GLOBAL, 0,
435 DIREG_DEV, KEY_QUERY_VALUE);
436 if (INVALID_HANDLE_VALUE != hDeviceRegistryKey) {
437 DWORD RegKeyType;
438 wchar_t wport[80];
439 LPCWSTR cstr = wport;
440 MultiByteToWideChar(0, 0, "PortName", -1, wport, 80);
441 DWORD len = sizeof(dname);
442
443 int result = RegQueryValueEx(hDeviceRegistryKey, cstr, 0,
444 &RegKeyType, (PBYTE)dname, &len);
445 if (result == 0) bFoundCom = true;
446 }
447
448 if (bFoundCom) {
449 wxString port(dname, wxConvUTF8);
450
451 // If the port has already been found, remove the prior entry
452 // in favor of this entry, which will have descriptive
453 // information appended
454 for (unsigned int n = 0; n < preturn->GetCount(); n++) {
455 if ((preturn->Item(n)).IsSameAs(port)) {
456 preturn->RemoveAt(n);
457 break;
458 }
459 }
460 wxString desc_name(desc, wxConvUTF8); // append "description"
461 port += " ";
462 port += desc_name;
463
464 preturn->Add(port);
465 }
466 }
467 }
468 } // for
469 } // if
470
471 // Search for Garmin device driver on Windows platforms
472
473 HDEVINFO hdeviceinfo = INVALID_HANDLE_VALUE;
474
475 hdeviceinfo = SetupDiGetClassDevs((GUID*)&GARMIN_DETECT_GUID, NULL, NULL,
476 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
477
478 if (hdeviceinfo != INVALID_HANDLE_VALUE) {
479 if (GarminProtocolHandler::IsGarminPlugged()) {
480 wxLogMessage("EnumerateSerialPorts() Found Garmin USB Device.");
481 preturn->Add("Garmin-USB"); // Add generic Garmin selectable device
482 }
483 }
484
485 return preturn;
486}
487
488#endif // __WXMSW__
489
490#if defined(OCPN_USE_SYSFS_PORTS) && defined(HAVE_SYSFS_PORTS)
491
492wxArrayString* EnumerateSerialPorts() { return EnumerateSysfsSerialPorts(); }
493
494#elif defined(OCPN_USE_UDEV_PORTS) && defined(HAVE_LIBUDEV)
495
496wxArrayString* EnumerateSerialPorts() { return EnumerateUdevSerialPorts(); }
497
498#elif defined(__ANDROID__)
499
500wxArrayString* EnumerateSerialPorts() { return androidGetSerialPortsArray(); }
501
502#elif defined(__WXOSX__)
503
504wxArrayString* EnumerateSerialPorts() {
505 wxArrayString* preturn = new wxArrayString;
506 char* paPortNames[MAX_SERIAL_PORTS];
507 int iPortNameCount;
508
509 memset(paPortNames, 0x00, sizeof(paPortNames));
510 iPortNameCount = FindSerialPortNames(&paPortNames[0], MAX_SERIAL_PORTS);
511 for (int iPortIndex = 0; iPortIndex < iPortNameCount; iPortIndex++) {
512 wxString sm(paPortNames[iPortIndex], wxConvUTF8);
513 preturn->Add(sm);
514 free(paPortNames[iPortIndex]);
515 }
516 return preturn;
517}
518
519#elif defined(__WXMSW__)
520
521wxArrayString* EnumerateSerialPorts() { return EnumerateWindowsSerialPorts(); }
522
523#elif defined(OCPN_USE_NEWSERIAL)
524
525wxArrayString* EnumerateSerialPorts() {
526 wxArrayString* preturn = new wxArrayString;
527 std::vector<serial::PortInfo> ports = serial::list_ports();
528 for (auto it = ports.begin(); it != ports.end(); ++it) {
529 wxString port(it->port);
530 if (it->description.length() > 0 && it->description != "n/a") {
531 port.Append(" - ");
532 port.Append(wxString::FromUTF8((it->description).c_str()));
533 }
534 preturn->Add(port);
535 }
536 return preturn;
537}
538
539#else
540
541#error "Cannot enumerate serial ports (missing libudev.h?)"
542
543#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.