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
59#ifdef OCPN_USE_NEWSERIAL
60#include "serial/serial.h"
61#endif
62
63#ifdef HAVE_LIBUDEV
64#include "libudev.h"
65#endif
66
67#ifdef HAVE_DIRENT_H
68#include "dirent.h"
69#endif
70
71#ifdef HAVE_LINUX_SERIAL_H
72#include "linux/serial.h"
73#endif
74
75#ifdef HAVE_SYS_IOCTL_H
76#include <sys/ioctl.h>
77#endif
78
79#ifdef HAVE_FCNTL_H
80#include <fcntl.h>
81#endif
82
83#ifdef HAVE_SYS_FCNTL_H
84#include <sys/fcntl.h>
85#endif
86
87#ifdef HAVE_SYS_TYPES_H
88#include <sys/types.h>
89#endif
90
91#ifdef HAVE_READLINK
92#include <unistd.h>
93#endif
94
95#ifdef __linux__
96#include <termios.h>
97#include <linux/serial.h>
98#endif
99
100
101#ifdef __WXMSW__
102#include <windows.h>
103#include <setupapi.h>
104#endif
105
106#ifdef __WXOSX__
107#include "macutils.h"
108#endif
109
110#include "gui_lib.h"
111#include "garmin_protocol_mgr.h"
112
113#ifdef __WXMSW__
114DEFINE_GUID(GARMIN_DETECT_GUID, 0x2c9c45c2L, 0x8e7d, 0x4c08, 0xa1, 0x2d, 0x81,
115 0x6b, 0xba, 0xe7, 0x22, 0xc0);
116#endif
117
118#ifdef __MINGW32__ // do I need this because of mingw, or because I am running
119 // mingw under wine?
120#ifndef GUID_CLASS_COMPORT
121DEFINE_GUID(GUID_CLASS_COMPORT, 0x86e0d1e0L, 0x8089, 0x11d0, 0x9c, 0xe4, 0x08,
122 0x00, 0x3e, 0x30, 0x1f, 0x73);
123#endif
124#endif
125
126extern int g_nCOMPortCheck;
127
129 std::string info; // Free format info text, possibly empty
130 std::string path; // Complete /dev device path
131 device_data(const std::string& p, const std::string& i) : info(i), path(p) {}
132};
133
134struct symlink {
135 std::string path;
136 std::string target;
137 symlink(const std::string& p, const std::string& t) : path(p), target(t) {}
138};
139
140#ifdef __NetBSD__
141static int isTTYreal(const char* dev) {
142 if (strncmp("/dev/tty0", dev, 9) == 0) return 1;
143 if (strncmp("/dev/ttyU", dev, 9) == 0) return 1;
144 if (strcmp("/dev/gps", dev) == 0) return 1;
145 return 0;
146}
147
148#elif defined(HAVE_LINUX_SERIAL_H) && defined(HAVE_SYS_STAT_H)
149
151static std::string device_path(const char* dev) {
152 if (strstr(dev, "/sysfs/") != 0) return std::string(dev);
153 std::string path(dev);
154 return std::string("/dev") + path.substr(path.rfind('/'));
155}
156
157
158static int isTTYreal(const char* dev) {
159
160// gcc 12 bogus regex warning
161#pragma GCC diagnostic push
162#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
163
164 // Drop non-readable devices
165 std::string path = device_path(dev);
166 int fd = open(path.c_str(), O_RDONLY | O_NONBLOCK | O_NOCTTY);
167 if (fd < 0) return 0;
168
169 // This original check does not work in kernels > 5.12.
170 // See: https://github.com/torvalds/linux/commit/f64d74a59c476
171 bool ok = false;
172 struct serial_struct serinfo;
173 if (ioctl(fd, TIOCGSERIAL, &serinfo) == 0) {
174 ok = serinfo.type != PORT_UNKNOWN;
175 }
176 if (!ok) {
177 // Accept any device with hardware lines DSR or CTS set.
178 int modem_sts;
179 if (ioctl(fd, TIOCMGET, &modem_sts) == 0) {
180 ok = (modem_sts & (TIOCM_CTS | TIOCM_LE | TIOCM_DSR)) != 0;
181 }
182 }
183 if (!ok) {
184 // Accept standard ttyS0..ttyS3 + devices configured by udev:
185 static const std::vector<std::regex> patterns = {
186 std::regex("ttyS[0-3]$", std::regex_constants::ECMAScript),
187 std::regex("ttyUSB", std::regex_constants::ECMAScript),
188 std::regex("ttyACM", std::regex_constants::ECMAScript),
189 std::regex("ttyAMA", std::regex_constants::ECMAScript)
190 };
191 for (auto re : patterns) {
192 if (std::regex_search(dev, re)) {
193 ok = true;
194 break;
195 }
196 }
197 }
198 close(fd);
199 return ok ? 1 : 0;
200
201#pragma GCC diagnostic pop
202}
203
204#else
205static int isTTYreal(const char* dev) { return 1; }
206
207#endif /* !NetBSD */
208
209static bool isTTYreal(const device_data& data) {
210 return isTTYreal(data.path.c_str());
211}
212
213#if defined(HAVE_DIRENT_H) && defined(HAVE_READLINK)
214
215#define HAVE_SYSFS_PORTS
216
218static std::vector<std::string> get_device_candidates() {
219 std::vector<std::string> devices;
220 DIR* dir;
221 struct dirent* ent;
222 dir = opendir("/sys/class/tty");
223 if (dir == 0) {
224 wxLogWarning("Cannot open /sys/class/tty: %s", strerror(errno));
225 return devices;
226 }
227 const std::string prefix("/dev/");
228 for (ent = readdir(dir); ent; ent = readdir(dir)) {
229 devices.push_back(prefix + ent->d_name);
230 }
231 closedir(dir);
232 return devices;
233}
234
236static std::vector<struct symlink> get_all_links() {
237 std::vector<struct symlink> links;
238 DIR* dir;
239 struct dirent* ent;
240 dir = opendir("/dev");
241 if (dir == 0) {
242 wxLogError("Cannot open /dev: %s", strerror(errno));
243 return links;
244 }
245 const std::string prefix("/dev/");
246 for (ent = readdir(dir); ent; ent = readdir(dir)) {
247 struct stat buf;
248 const std::string path(prefix + ent->d_name);
249 int r = lstat(path.c_str(), &buf);
250 if (r == -1) {
251 wxLogDebug("get_all_links: Cannot stat %s: %s", path.c_str(),
252 strerror(errno));
253 } else if (S_ISLNK(buf.st_mode)) {
254 char buff[PATH_MAX + 1];
255 readlink(path.c_str(), buff, PATH_MAX);
256 std::string target(buff);
257 struct symlink link(path.c_str(), prefix + target);
258 links.push_back(link);
259 }
260 }
261 closedir(dir);
262 return links;
263}
264
266static wxArrayString* EnumerateSysfsSerialPorts(void) {
267 std::vector<std::string> ports;
268 auto all_ports = get_device_candidates();
269 wxLogDebug("Enumerate: found %d candidates", all_ports.size());
270 for (auto p : all_ports) {
271 if (isTTYreal(p.c_str())) ports.push_back(p);
272 }
273 wxLogDebug("Enumerate: found %d good ports", ports.size());
274 const auto targets =
275 std::unordered_set<std::string>(ports.begin(), ports.end());
276
277 auto all_links = get_all_links();
278 wxLogDebug("Enumerate: found %d links", all_links.size());
279 for (auto l : all_links) {
280 if (targets.find(l.target) != targets.end()) ports.push_back(l.path);
281 }
282 wxLogDebug("Enumerate: found %d devices", ports.size());
283
284 auto wx_ports = new wxArrayString();
285 for (auto p : ports) {
286 wx_ports->Add(p);
287 }
288 return wx_ports;
289}
290
291#endif // HAVE_DIRENT_H && defined(HAVE_READLINK)
292
293#if defined(HAVE_LIBUDEV)
294
296static std::string get_device_info(struct udev_device* ud) {
297 std::string info;
298 const char* prop = udev_device_get_property_value(ud, "ID_VENDOR");
299 if (prop) info += prop;
300 prop = udev_device_get_property_value(ud, "ID_MODEL");
301 if (prop) info += std::string(" - ") + prop;
302 return info;
303}
304
305// gcc bogus regex warning
306#pragma GCC diagnostic push
307#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
308
310static std::vector<struct device_data> get_links(struct udev_device* dev,
311 const std::regex& exclude) {
312 std::vector<struct device_data> items;
313 std::string info(" link -> ");
314 info += udev_device_get_devnode(dev);
315 struct udev_list_entry* link = udev_device_get_devlinks_list_entry(dev);
316 while (link) {
317 const char* linkname = udev_list_entry_get_name(link);
318 if (!std::regex_search(linkname, exclude)) {
319 struct device_data item(linkname, info);
320 items.push_back(item);
321 }
322 link = udev_list_entry_get_next(link);
323 }
324 return items;
325}
326
327static std::vector<struct device_data> enumerate_udev_ports(struct udev* udev) {
328 struct udev_enumerate* enumerate = udev_enumerate_new(udev);
329 udev_enumerate_add_match_subsystem(enumerate, "tty");
330 udev_enumerate_scan_devices(enumerate);
331 struct udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate);
332
333 const std::regex bad_ttys(".*tty[0-9][0-9]|^/dev/serial/.*|.*ttyS[0-9][0-9]");
334 std::vector<struct device_data> items;
335 struct udev_list_entry* entry;
336 udev_list_entry_foreach(entry, devices) {
337 const char* const path = udev_list_entry_get_name(entry);
338 struct udev_device* device = udev_device_new_from_syspath(udev, path);
339 const char* const devnode = udev_device_get_devnode(device);
340 struct device_data item(devnode, get_device_info(device));
341 if (!std::regex_search(devnode, bad_ttys) &&
342 (isTTYreal(path) || item.info.length() > 0)) {
343 items.push_back(item);
344 auto links = get_links(device, bad_ttys);
345 items.insert(items.end(), links.begin(), links.end());
346 }
347 udev_device_unref(device);
348 }
349 return items;
350}
351
352#pragma GCC diagnostic pop
353static wxArrayString* EnumerateUdevSerialPorts(void) {
354 struct udev* udev = udev_new();
355 auto dev_items = enumerate_udev_ports(udev);
356 wxArrayString* ports = new wxArrayString;
357 for (auto item : dev_items) {
358 ports->Add((item.path + " - " + item.info).c_str());
359 }
360 return ports;
361}
362
363#endif // HAVE_LIBUDEV
364
365#ifdef __WXMSW__
366static wxArrayString* EnumerateWindowsSerialPorts(void) {
367 wxArrayString* preturn = new wxArrayString;
368 /*************************************************************************
369 * Windows provides no system level enumeration of available serial ports
370 * There are several ways of doing this.
371 *
372 *************************************************************************/
373
374 // Method 1: Use GetDefaultCommConfig()
375 // Try first {g_nCOMPortCheck} possible COM ports, check for a default
376 // configuration
377 // This method will not find some Bluetooth SPP ports
378 for (int i = 1; i < g_nCOMPortCheck; i++) {
379 wxString s;
380 s.Printf(_T("COM%d"), i);
381
382 COMMCONFIG cc;
383 DWORD dwSize = sizeof(COMMCONFIG);
384 if (GetDefaultCommConfig(s.fn_str(), &cc, &dwSize))
385 preturn->Add(wxString(s));
386 }
387
388#if 0
389 // Method 2: Use FileOpen()
390 // Try all 255 possible COM ports, check to see if it can be opened, or if
391 // not, that an expected error is returned.
392
393 BOOL bFound;
394 for (int j=1; j<256; j++)
395 {
396 char s[20];
397 sprintf(s, "\\\\.\\COM%d", j);
398
399 // Open the port tentatively
400 BOOL bSuccess = FALSE;
401 HANDLE hComm = ::CreateFile(s, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
402
403 // Check for the error returns that indicate a port is there, but not currently useable
404 if (hComm == INVALID_HANDLE_VALUE)
405 {
406 DWORD dwError = GetLastError();
407
408 if (dwError == ERROR_ACCESS_DENIED ||
409 dwError == ERROR_GEN_FAILURE ||
410 dwError == ERROR_SHARING_VIOLATION ||
411 dwError == ERROR_SEM_TIMEOUT)
412 bFound = TRUE;
413 }
414 else
415 {
416 bFound = TRUE;
417 CloseHandle(hComm);
418 }
419
420 if (bFound)
421 preturn->Add(wxString(s));
422 }
423#endif // 0
424
425 // Method 3: WDM-Setupapi
426 // This method may not find XPort virtual ports,
427 // but does find Bluetooth SPP ports
428
429 GUID* guidDev = (GUID*)&GUID_CLASS_COMPORT;
430
431 HDEVINFO hDevInfo = INVALID_HANDLE_VALUE;
432
433 hDevInfo = SetupDiGetClassDevs(guidDev, NULL, NULL,
434 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
435
436 if (hDevInfo != INVALID_HANDLE_VALUE) {
437 BOOL bOk = TRUE;
438 SP_DEVICE_INTERFACE_DATA ifcData;
439
440 ifcData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
441 for (DWORD ii = 0; bOk; ii++) {
442 bOk = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guidDev, ii, &ifcData);
443 if (bOk) {
444 // Got a device. Get the details.
445
446 SP_DEVINFO_DATA devdata = {sizeof(SP_DEVINFO_DATA)};
447 bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifcData, NULL, 0, NULL,
448 &devdata);
449
450 // We really only need devdata
451 if (!bOk) {
452 if (GetLastError() ==
453 122) // ERROR_INSUFFICIENT_BUFFER, OK in this case
454 bOk = true;
455 }
456
457 // We could get friendly name and/or description here
458 TCHAR fname[256] = {0};
459 TCHAR desc[256] = {0};
460 if (bOk) {
461 BOOL bSuccess = SetupDiGetDeviceRegistryProperty(
462 hDevInfo, &devdata, SPDRP_FRIENDLYNAME, NULL, (PBYTE)fname,
463 sizeof(fname), NULL);
464
465 bSuccess = bSuccess && SetupDiGetDeviceRegistryProperty(
466 hDevInfo, &devdata, SPDRP_DEVICEDESC, NULL,
467 (PBYTE)desc, sizeof(desc), NULL);
468 }
469
470 // Get the "COMn string from the registry key
471 if (bOk) {
472 bool bFoundCom = false;
473 TCHAR dname[256];
474 HKEY hDeviceRegistryKey =
475 SetupDiOpenDevRegKey(hDevInfo, &devdata, DICS_FLAG_GLOBAL, 0,
476 DIREG_DEV, KEY_QUERY_VALUE);
477 if (INVALID_HANDLE_VALUE != hDeviceRegistryKey) {
478 DWORD RegKeyType;
479 wchar_t wport[80];
480 LPCWSTR cstr = wport;
481 MultiByteToWideChar(0, 0, "PortName", -1, wport, 80);
482 DWORD len = sizeof(dname);
483
484 int result = RegQueryValueEx(hDeviceRegistryKey, cstr, 0,
485 &RegKeyType, (PBYTE)dname, &len);
486 if (result == 0) bFoundCom = true;
487 }
488
489 if (bFoundCom) {
490 wxString port(dname, wxConvUTF8);
491
492 // If the port has already been found, remove the prior entry
493 // in favor of this entry, which will have descriptive
494 // information appended
495 for (unsigned int n = 0; n < preturn->GetCount(); n++) {
496 if ((preturn->Item(n)).IsSameAs(port)) {
497 preturn->RemoveAt(n);
498 break;
499 }
500 }
501 wxString desc_name(desc, wxConvUTF8); // append "description"
502 port += _T(" ");
503 port += desc_name;
504
505 preturn->Add(port);
506 }
507 }
508 }
509 } // for
510 } // if
511
512 // Search for Garmin device driver on Windows platforms
513
514 HDEVINFO hdeviceinfo = INVALID_HANDLE_VALUE;
515
516 hdeviceinfo = SetupDiGetClassDevs((GUID*)&GARMIN_DETECT_GUID, NULL, NULL,
517 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
518
519 if (hdeviceinfo != INVALID_HANDLE_VALUE) {
520 if (GarminProtocolHandler::IsGarminPlugged()) {
521 wxLogMessage(_T("EnumerateSerialPorts() Found Garmin USB Device."));
522 preturn->Add(_T("Garmin-USB")); // Add generic Garmin selectable device
523 }
524 }
525
526#if 0
527 SP_DEVICE_INTERFACE_DATA deviceinterface;
528 deviceinterface.cbSize = sizeof(deviceinterface);
529
530 if (SetupDiEnumDeviceInterfaces(hdeviceinfo,
531 NULL,
532 (GUID *) &GARMIN_DETECT_GUID,
533 0,
534 &deviceinterface))
535 {
536 wxLogMessage(_T("Found Garmin Device."));
537
538 preturn->Add(_T("GARMIN")); // Add generic Garmin selectable device
539 }
540#endif // 0
541 return preturn;
542}
543
544#endif // __WXMSW__
545
546
547#if defined(OCPN_USE_SYSFS_PORTS) && defined(HAVE_SYSFS_PORTS)
548
549wxArrayString* EnumerateSerialPorts(void) {
550 return EnumerateSysfsSerialPorts();
551}
552
553#elif defined(OCPN_USE_UDEV_PORTS) && defined(HAVE_LIBUDEV)
554
555wxArrayString* EnumerateSerialPorts(void) { return EnumerateUdevSerialPorts(); }
556
557#elif defined(__ANDROID__)
558
559wxArrayString* EnumerateSerialPorts(void) {
560 return androidGetSerialPortsArray();
561}
562
563#elif defined(__WXOSX__)
564
565wxArrayString* EnumerateSerialPorts(void) {
566 wxArrayString* preturn = new wxArrayString;
567 char* paPortNames[MAX_SERIAL_PORTS];
568 int iPortNameCount;
569
570 memset(paPortNames, 0x00, sizeof(paPortNames));
571 iPortNameCount = FindSerialPortNames(&paPortNames[0], MAX_SERIAL_PORTS);
572 for (int iPortIndex = 0; iPortIndex < iPortNameCount; iPortIndex++) {
573 wxString sm(paPortNames[iPortIndex], wxConvUTF8);
574 preturn->Add(sm);
575 free(paPortNames[iPortIndex]);
576 }
577 return preturn;
578}
579
580#elif defined(__WXMSW__)
581
582wxArrayString* EnumerateSerialPorts(void) {
583 return EnumerateWindowsSerialPorts();
584}
585
586#elif defined(OCPN_USE_NEWSERIAL)
587
588wxArrayString* EnumerateSerialPorts(void) {
589 wxArrayString* preturn = new wxArrayString;
590 std::vector<serial::PortInfo> ports = serial::list_ports();
591 for (auto it = ports.begin(); it != ports.end(); ++it) {
592 wxString port(it->port);
593 if (it->description.length() > 0 && it->description != "n/a") {
594 port.Append(" - ");
595 port.Append(wxString::FromUTF8((it->description).c_str()));
596 }
597 preturn->Add(port);
598 }
599 return preturn;
600}
601
602#else
603
604#error "Cannot enumerate serial ports (missing libudev.h?)"
605
606#endif // outermost if - elif - else