OpenCPN Partial API docs
Loading...
Searching...
No Matches
ser_ports.cpp
1/***************************************************************************
2 *
3 * Project: OpenCPN
4 * Purpose: OpenCPN Main wxWidgets Program
5 * Author: David Register
6 *
7 ***************************************************************************
8 * Copyright (C) 2010 by David S. Register *
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 * This program is distributed in the hope that it will be useful, *
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
18 * GNU General Public License for more details. *
19 * *
20 * You should have received a copy of the GNU General Public License *
21 * along with this program; if not, write to the *
22 * Free Software Foundation, Inc., *
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
24 **************************************************************************/
25
26#ifdef __MSVC__
27#include <winsock2.h>
28#include <wx/msw/winundef.h>
29#endif
30
31#include "config.h"
32
33#include <iostream>
34
35#pragma GCC diagnostic push
36#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
37#include <regex>
38#pragma GCC diagnostic pop
39
40#include <string>
41#include <unordered_set>
42#include <vector>
43
44#include <wx/arrstr.h>
45#include <wx/log.h>
46#include <wx/utils.h>
47
48#ifdef __MINGW32__
49#undef IPV6STRICT // mingw FTBS fix: missing struct ip_mreq
50#include <windows.h>
51#endif
52
53#ifdef __ANDROID__
54#include "androidUTIL.h"
55#include "qdebug.h"
56#endif
57
58#ifdef OCPN_USE_NEWSERIAL
59#include "serial/serial.h"
60#endif
61
62#ifdef HAVE_LIBUDEV
63#include "libudev.h"
64#endif
65
66#ifdef HAVE_DIRENT_H
67#include "dirent.h"
68#endif
69
70#ifdef HAVE_LINUX_SERIAL_H
71#include "linux/serial.h"
72#endif
73
74#ifdef HAVE_SYS_IOCTL_H
75#include <sys/ioctl.h>
76#endif
77
78#ifdef HAVE_FCNTL_H
79#include <fcntl.h>
80#endif
81
82#ifdef HAVE_SYS_FCNTL_H
83#include <sys/fcntl.h>
84#endif
85
86#ifdef HAVE_SYS_TYPES_H
87#include <sys/types.h>
88#endif
89
90#ifdef HAVE_READLINK
91#include <unistd.h>
92#endif
93
94#ifdef __linux__
95#include <termios.h>
96#include <linux/serial.h>
97#endif
98
99#ifdef __WXMSW__
100#include <windows.h>
101#include <setupapi.h>
102#endif
103
104#ifdef __WXOSX__
105#include "model/macutils.h"
106#endif
107
108#include "model/config_vars.h"
109#include "model/garmin_protocol_mgr.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 readlink(path.c_str(), buff, PATH_MAX);
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(void) {
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(void) {
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(void) {
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(_T("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#if 0
385 // Method 2: Use FileOpen()
386 // Try all 255 possible COM ports, check to see if it can be opened, or if
387 // not, that an expected error is returned.
388
389 BOOL bFound;
390 for (int j=1; j<256; j++)
391 {
392 char s[20];
393 sprintf(s, "\\\\.\\COM%d", j);
394
395 // Open the port tentatively
396 BOOL bSuccess = FALSE;
397 HANDLE hComm = ::CreateFile(s, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
398
399 // Check for the error returns that indicate a port is there, but not currently useable
400 if (hComm == INVALID_HANDLE_VALUE)
401 {
402 DWORD dwError = GetLastError();
403
404 if (dwError == ERROR_ACCESS_DENIED ||
405 dwError == ERROR_GEN_FAILURE ||
406 dwError == ERROR_SHARING_VIOLATION ||
407 dwError == ERROR_SEM_TIMEOUT)
408 bFound = TRUE;
409 }
410 else
411 {
412 bFound = TRUE;
413 CloseHandle(hComm);
414 }
415
416 if (bFound)
417 preturn->Add(wxString(s));
418 }
419#endif // 0
420
421 // Method 3: WDM-Setupapi
422 // This method may not find XPort virtual ports,
423 // but does find Bluetooth SPP ports
424
425 GUID* guidDev = (GUID*)&GUID_CLASS_COMPORT;
426
427 HDEVINFO hDevInfo = INVALID_HANDLE_VALUE;
428
429 hDevInfo = SetupDiGetClassDevs(guidDev, NULL, NULL,
430 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
431
432 if (hDevInfo != INVALID_HANDLE_VALUE) {
433 BOOL bOk = TRUE;
434 SP_DEVICE_INTERFACE_DATA ifcData;
435
436 ifcData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
437 for (DWORD ii = 0; bOk; ii++) {
438 bOk = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guidDev, ii, &ifcData);
439 if (bOk) {
440 // Got a device. Get the details.
441
442 SP_DEVINFO_DATA devdata = {sizeof(SP_DEVINFO_DATA)};
443 bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifcData, NULL, 0, NULL,
444 &devdata);
445
446 // We really only need devdata
447 if (!bOk) {
448 if (GetLastError() ==
449 122) // ERROR_INSUFFICIENT_BUFFER, OK in this case
450 bOk = true;
451 }
452
453 // We could get friendly name and/or description here
454 TCHAR fname[256] = {0};
455 TCHAR desc[256] = {0};
456 if (bOk) {
457 BOOL bSuccess = SetupDiGetDeviceRegistryProperty(
458 hDevInfo, &devdata, SPDRP_FRIENDLYNAME, NULL, (PBYTE)fname,
459 sizeof(fname), NULL);
460
461 bSuccess = bSuccess && SetupDiGetDeviceRegistryProperty(
462 hDevInfo, &devdata, SPDRP_DEVICEDESC, NULL,
463 (PBYTE)desc, sizeof(desc), NULL);
464 }
465
466 // Get the "COMn string from the registry key
467 if (bOk) {
468 bool bFoundCom = false;
469 TCHAR dname[256];
470 HKEY hDeviceRegistryKey =
471 SetupDiOpenDevRegKey(hDevInfo, &devdata, DICS_FLAG_GLOBAL, 0,
472 DIREG_DEV, KEY_QUERY_VALUE);
473 if (INVALID_HANDLE_VALUE != hDeviceRegistryKey) {
474 DWORD RegKeyType;
475 wchar_t wport[80];
476 LPCWSTR cstr = wport;
477 MultiByteToWideChar(0, 0, "PortName", -1, wport, 80);
478 DWORD len = sizeof(dname);
479
480 int result = RegQueryValueEx(hDeviceRegistryKey, cstr, 0,
481 &RegKeyType, (PBYTE)dname, &len);
482 if (result == 0) bFoundCom = true;
483 }
484
485 if (bFoundCom) {
486 wxString port(dname, wxConvUTF8);
487
488 // If the port has already been found, remove the prior entry
489 // in favor of this entry, which will have descriptive
490 // information appended
491 for (unsigned int n = 0; n < preturn->GetCount(); n++) {
492 if ((preturn->Item(n)).IsSameAs(port)) {
493 preturn->RemoveAt(n);
494 break;
495 }
496 }
497 wxString desc_name(desc, wxConvUTF8); // append "description"
498 port += _T(" ");
499 port += desc_name;
500
501 preturn->Add(port);
502 }
503 }
504 }
505 } // for
506 } // if
507
508 // Search for Garmin device driver on Windows platforms
509
510 HDEVINFO hdeviceinfo = INVALID_HANDLE_VALUE;
511
512 hdeviceinfo = SetupDiGetClassDevs((GUID*)&GARMIN_DETECT_GUID, NULL, NULL,
513 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
514
515 if (hdeviceinfo != INVALID_HANDLE_VALUE) {
516 if (GarminProtocolHandler::IsGarminPlugged()) {
517 wxLogMessage(_T("EnumerateSerialPorts() Found Garmin USB Device."));
518 preturn->Add(_T("Garmin-USB")); // Add generic Garmin selectable device
519 }
520 }
521
522#if 0
523 SP_DEVICE_INTERFACE_DATA deviceinterface;
524 deviceinterface.cbSize = sizeof(deviceinterface);
525
526 if (SetupDiEnumDeviceInterfaces(hdeviceinfo,
527 NULL,
528 (GUID *) &GARMIN_DETECT_GUID,
529 0,
530 &deviceinterface))
531 {
532 wxLogMessage(_T("Found Garmin Device."));
533
534 preturn->Add(_T("GARMIN")); // Add generic Garmin selectable device
535 }
536#endif // 0
537 return preturn;
538}
539
540#endif // __WXMSW__
541
542#if defined(OCPN_USE_SYSFS_PORTS) && defined(HAVE_SYSFS_PORTS)
543
544wxArrayString* EnumerateSerialPorts(void) {
545 return EnumerateSysfsSerialPorts();
546}
547
548#elif defined(OCPN_USE_UDEV_PORTS) && defined(HAVE_LIBUDEV)
549
550wxArrayString* EnumerateSerialPorts(void) { return EnumerateUdevSerialPorts(); }
551
552#elif defined(__ANDROID__)
553
554wxArrayString* EnumerateSerialPorts(void) {
555 return androidGetSerialPortsArray();
556}
557
558#elif defined(__WXOSX__)
559
560wxArrayString* EnumerateSerialPorts(void) {
561 wxArrayString* preturn = new wxArrayString;
562 char* paPortNames[MAX_SERIAL_PORTS];
563 int iPortNameCount;
564
565 memset(paPortNames, 0x00, sizeof(paPortNames));
566 iPortNameCount = FindSerialPortNames(&paPortNames[0], MAX_SERIAL_PORTS);
567 for (int iPortIndex = 0; iPortIndex < iPortNameCount; iPortIndex++) {
568 wxString sm(paPortNames[iPortIndex], wxConvUTF8);
569 preturn->Add(sm);
570 free(paPortNames[iPortIndex]);
571 }
572 return preturn;
573}
574
575#elif defined(__WXMSW__)
576
577wxArrayString* EnumerateSerialPorts(void) {
578 return EnumerateWindowsSerialPorts();
579}
580
581#elif defined(OCPN_USE_NEWSERIAL)
582
583wxArrayString* EnumerateSerialPorts(void) {
584 wxArrayString* preturn = new wxArrayString;
585 std::vector<serial::PortInfo> ports = serial::list_ports();
586 for (auto it = ports.begin(); it != ports.end(); ++it) {
587 wxString port(it->port);
588 if (it->description.length() > 0 && it->description != "n/a") {
589 port.Append(" - ");
590 port.Append(wxString::FromUTF8((it->description).c_str()));
591 }
592 preturn->Add(port);
593 }
594 return preturn;
595}
596
597#else
598
599#error "Cannot enumerate serial ports (missing libudev.h?)"
600
601#endif // outermost if - elif - else