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 <cassert>
34#include <iostream>
35
36#pragma GCC diagnostic push
37#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
38#include <regex>
39#pragma GCC diagnostic pop
40
41#include <string>
42#include <unordered_set>
43#include <vector>
44
45#include <wx/arrstr.h>
46#include <wx/log.h>
47#include <wx/utils.h>
48
49#ifdef __MINGW32__
50#undef IPV6STRICT // mingw FTBS fix: missing struct ip_mreq
51#include <windows.h>
52#endif
53
54#ifdef __ANDROID__
55#include "androidUTIL.h"
56#include "qdebug.h"
57#endif
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#ifdef __WXMSW__
101#include <windows.h>
102#include <setupapi.h>
103#endif
104
105#ifdef __WXOSX__
106#include "model/macutils.h"
107#endif
108
109#include "model/config_vars.h"
110#include "model/garmin_protocol_mgr.h"
111
112#ifdef __WXMSW__
113DEFINE_GUID(GARMIN_DETECT_GUID, 0x2c9c45c2L, 0x8e7d, 0x4c08, 0xa1, 0x2d, 0x81,
114 0x6b, 0xba, 0xe7, 0x22, 0xc0);
115#endif
116
117#ifdef __MINGW32__ // do I need this because of mingw, or because I am running
118 // mingw under wine?
119#ifndef GUID_CLASS_COMPORT
120DEFINE_GUID(GUID_CLASS_COMPORT, 0x86e0d1e0L, 0x8089, 0x11d0, 0x9c, 0xe4, 0x08,
121 0x00, 0x3e, 0x30, 0x1f, 0x73);
122#endif
123#endif
124
126 std::string info; // Free format info text, possibly empty
127 std::string path; // Complete /dev device path
128 device_data(const std::string& p, const std::string& i) : info(i), path(p) {}
129};
130
131struct symlink {
132 std::string path;
133 std::string target;
134 symlink(const std::string& p, const std::string& t) : path(p), target(t) {}
135};
136
137#ifdef __NetBSD__
138static int isTTYreal(const char* dev) {
139 if (strncmp("/dev/tty0", dev, 9) == 0) return 1;
140 if (strncmp("/dev/ttyU", dev, 9) == 0) return 1;
141 if (strcmp("/dev/gps", dev) == 0) return 1;
142 return 0;
143}
144
145#elif defined(HAVE_LINUX_SERIAL_H) && defined(HAVE_SYS_STAT_H)
146
148static std::string device_path(const char* dev) {
149 if (strstr(dev, "/sysfs/") != 0) return std::string(dev);
150 std::string path(dev);
151 return std::string("/dev") + path.substr(path.rfind('/'));
152}
153
154static int isTTYreal(const char* dev) {
155// gcc 12 bogus regex warning
156#pragma GCC diagnostic push
157#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
158
159 bool ok = false;
160
161 // This original check does not work in kernels > 5.12.
162 // See: https://github.com/torvalds/linux/commit/f64d74a59c476
163 std::string path = device_path(dev);
164 int fd = open(path.c_str(), O_RDONLY | O_NONBLOCK | O_NOCTTY);
165 if (fd >= 0) {
166 struct serial_struct serinfo;
167 if (ioctl(fd, TIOCGSERIAL, &serinfo) == 0) {
168 ok = serinfo.type != PORT_UNKNOWN;
169 }
170 if (!ok) {
171 // Accept any device with hardware lines DSR or CTS set.
172 int modem_sts;
173 if (ioctl(fd, TIOCMGET, &modem_sts) == 0) {
174 ok = (modem_sts & (TIOCM_CTS | TIOCM_LE | TIOCM_DSR)) != 0;
175 }
176 }
177 }
178 if (fd >= 0) close(fd);
179
180 if (!ok) {
181 // Accept standard ttyS0..ttyS3 + devices configured by udev:
182 static const std::vector<std::regex> patterns = {
183 std::regex("ttyS[0-3]$", std::regex_constants::ECMAScript),
184 std::regex("ttyUSB", std::regex_constants::ECMAScript),
185 std::regex("ttyACM", std::regex_constants::ECMAScript),
186 std::regex("ttyAMA", std::regex_constants::ECMAScript)};
187 for (auto re : patterns) {
188 if (std::regex_search(dev, re)) {
189 ok = true;
190 break;
191 }
192 }
193 }
194 return ok ? 1 : 0;
195
196#pragma GCC diagnostic pop
197}
198
199#else
200static int isTTYreal(const char* dev) { return 1; }
201
202#endif /* !NetBSD */
203
204static bool isTTYreal(const device_data& data) {
205 return isTTYreal(data.path.c_str());
206}
207
208#if defined(HAVE_DIRENT_H) && defined(HAVE_READLINK)
209
210#define HAVE_SYSFS_PORTS
211
213static std::vector<std::string> get_device_candidates() {
214 std::vector<std::string> devices;
215 DIR* dir;
216 struct dirent* ent;
217 dir = opendir("/sys/class/tty");
218 if (dir == 0) {
219 wxLogWarning("Cannot open /sys/class/tty: %s", strerror(errno));
220 return devices;
221 }
222 const std::string prefix("/dev/");
223 for (ent = readdir(dir); ent; ent = readdir(dir)) {
224 devices.push_back(prefix + ent->d_name);
225 }
226 closedir(dir);
227 return devices;
228}
229
231static std::vector<struct symlink> get_all_links() {
232 std::vector<struct symlink> links;
233 DIR* dir;
234 struct dirent* ent;
235 dir = opendir("/dev");
236 if (dir == 0) {
237 wxLogError("Cannot open /dev: %s", strerror(errno));
238 return links;
239 }
240 const std::string prefix("/dev/");
241 for (ent = readdir(dir); ent; ent = readdir(dir)) {
242 struct stat buf;
243 const std::string path(prefix + ent->d_name);
244 int r = lstat(path.c_str(), &buf);
245 if (r == -1) {
246 wxLogDebug("get_all_links: Cannot stat %s: %s", path.c_str(),
247 strerror(errno));
248 } else if (S_ISLNK(buf.st_mode)) {
249 char buff[PATH_MAX + 1];
250 assert(readlink(path.c_str(), buff, PATH_MAX) >= 0);
251 std::string target(buff);
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(void) {
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 return items;
345}
346
347#pragma GCC diagnostic pop
348static wxArrayString* EnumerateUdevSerialPorts(void) {
349 struct udev* udev = udev_new();
350 auto dev_items = enumerate_udev_ports(udev);
351 wxArrayString* ports = new wxArrayString;
352 for (const auto& item : dev_items) {
353 std::string port(item.path);
354 if (item.info.size() > 0) port += std::string(" - ") + item.info;
355 ports->Add(port);
356 }
357 return ports;
358}
359
360#endif // HAVE_LIBUDEV
361
362#ifdef __WXMSW__
363static wxArrayString* EnumerateWindowsSerialPorts(void) {
364 wxArrayString* preturn = new wxArrayString;
365 /*************************************************************************
366 * Windows provides no system level enumeration of available serial ports
367 * There are several ways of doing this.
368 *
369 *************************************************************************/
370
371 // Method 1: Use GetDefaultCommConfig()
372 // Try first {g_nCOMPortCheck} possible COM ports, check for a default
373 // configuration
374 // This method will not find some Bluetooth SPP ports
375 for (int i = 1; i < g_nCOMPortCheck; i++) {
376 wxString s;
377 s.Printf(_T("COM%d"), i);
378
379 COMMCONFIG cc;
380 DWORD dwSize = sizeof(COMMCONFIG);
381 if (GetDefaultCommConfig(s.fn_str(), &cc, &dwSize))
382 preturn->Add(wxString(s));
383 }
384
385#if 0
386 // Method 2: Use FileOpen()
387 // Try all 255 possible COM ports, check to see if it can be opened, or if
388 // not, that an expected error is returned.
389
390 BOOL bFound;
391 for (int j=1; j<256; j++)
392 {
393 char s[20];
394 sprintf(s, "\\\\.\\COM%d", j);
395
396 // Open the port tentatively
397 BOOL bSuccess = FALSE;
398 HANDLE hComm = ::CreateFile(s, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
399
400 // Check for the error returns that indicate a port is there, but not currently useable
401 if (hComm == INVALID_HANDLE_VALUE)
402 {
403 DWORD dwError = GetLastError();
404
405 if (dwError == ERROR_ACCESS_DENIED ||
406 dwError == ERROR_GEN_FAILURE ||
407 dwError == ERROR_SHARING_VIOLATION ||
408 dwError == ERROR_SEM_TIMEOUT)
409 bFound = TRUE;
410 }
411 else
412 {
413 bFound = TRUE;
414 CloseHandle(hComm);
415 }
416
417 if (bFound)
418 preturn->Add(wxString(s));
419 }
420#endif // 0
421
422 // Method 3: WDM-Setupapi
423 // This method may not find XPort virtual ports,
424 // but does find Bluetooth SPP ports
425
426 GUID* guidDev = (GUID*)&GUID_CLASS_COMPORT;
427
428 HDEVINFO hDevInfo = INVALID_HANDLE_VALUE;
429
430 hDevInfo = SetupDiGetClassDevs(guidDev, NULL, NULL,
431 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
432
433 if (hDevInfo != INVALID_HANDLE_VALUE) {
434 BOOL bOk = TRUE;
435 SP_DEVICE_INTERFACE_DATA ifcData;
436
437 ifcData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
438 for (DWORD ii = 0; bOk; ii++) {
439 bOk = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guidDev, ii, &ifcData);
440 if (bOk) {
441 // Got a device. Get the details.
442
443 SP_DEVINFO_DATA devdata = {sizeof(SP_DEVINFO_DATA)};
444 bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifcData, NULL, 0, NULL,
445 &devdata);
446
447 // We really only need devdata
448 if (!bOk) {
449 if (GetLastError() ==
450 122) // ERROR_INSUFFICIENT_BUFFER, OK in this case
451 bOk = true;
452 }
453
454 // We could get friendly name and/or description here
455 TCHAR fname[256] = {0};
456 TCHAR desc[256] = {0};
457 if (bOk) {
458 BOOL bSuccess = SetupDiGetDeviceRegistryProperty(
459 hDevInfo, &devdata, SPDRP_FRIENDLYNAME, NULL, (PBYTE)fname,
460 sizeof(fname), NULL);
461
462 bSuccess = bSuccess && SetupDiGetDeviceRegistryProperty(
463 hDevInfo, &devdata, SPDRP_DEVICEDESC, NULL,
464 (PBYTE)desc, sizeof(desc), NULL);
465 }
466
467 // Get the "COMn string from the registry key
468 if (bOk) {
469 bool bFoundCom = false;
470 TCHAR dname[256];
471 HKEY hDeviceRegistryKey =
472 SetupDiOpenDevRegKey(hDevInfo, &devdata, DICS_FLAG_GLOBAL, 0,
473 DIREG_DEV, KEY_QUERY_VALUE);
474 if (INVALID_HANDLE_VALUE != hDeviceRegistryKey) {
475 DWORD RegKeyType;
476 wchar_t wport[80];
477 LPCWSTR cstr = wport;
478 MultiByteToWideChar(0, 0, "PortName", -1, wport, 80);
479 DWORD len = sizeof(dname);
480
481 int result = RegQueryValueEx(hDeviceRegistryKey, cstr, 0,
482 &RegKeyType, (PBYTE)dname, &len);
483 if (result == 0) bFoundCom = true;
484 }
485
486 if (bFoundCom) {
487 wxString port(dname, wxConvUTF8);
488
489 // If the port has already been found, remove the prior entry
490 // in favor of this entry, which will have descriptive
491 // information appended
492 for (unsigned int n = 0; n < preturn->GetCount(); n++) {
493 if ((preturn->Item(n)).IsSameAs(port)) {
494 preturn->RemoveAt(n);
495 break;
496 }
497 }
498 wxString desc_name(desc, wxConvUTF8); // append "description"
499 port += _T(" ");
500 port += desc_name;
501
502 preturn->Add(port);
503 }
504 }
505 }
506 } // for
507 } // if
508
509 // Search for Garmin device driver on Windows platforms
510
511 HDEVINFO hdeviceinfo = INVALID_HANDLE_VALUE;
512
513 hdeviceinfo = SetupDiGetClassDevs((GUID*)&GARMIN_DETECT_GUID, NULL, NULL,
514 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
515
516 if (hdeviceinfo != INVALID_HANDLE_VALUE) {
517 if (GarminProtocolHandler::IsGarminPlugged()) {
518 wxLogMessage(_T("EnumerateSerialPorts() Found Garmin USB Device."));
519 preturn->Add(_T("Garmin-USB")); // Add generic Garmin selectable device
520 }
521 }
522
523#if 0
524 SP_DEVICE_INTERFACE_DATA deviceinterface;
525 deviceinterface.cbSize = sizeof(deviceinterface);
526
527 if (SetupDiEnumDeviceInterfaces(hdeviceinfo,
528 NULL,
529 (GUID *) &GARMIN_DETECT_GUID,
530 0,
531 &deviceinterface))
532 {
533 wxLogMessage(_T("Found Garmin Device."));
534
535 preturn->Add(_T("GARMIN")); // Add generic Garmin selectable device
536 }
537#endif // 0
538 return preturn;
539}
540
541#endif // __WXMSW__
542
543#if defined(OCPN_USE_SYSFS_PORTS) && defined(HAVE_SYSFS_PORTS)
544
545wxArrayString* EnumerateSerialPorts(void) {
546 return EnumerateSysfsSerialPorts();
547}
548
549#elif defined(OCPN_USE_UDEV_PORTS) && defined(HAVE_LIBUDEV)
550
551wxArrayString* EnumerateSerialPorts(void) { return EnumerateUdevSerialPorts(); }
552
553#elif defined(__ANDROID__)
554
555wxArrayString* EnumerateSerialPorts(void) {
556 return androidGetSerialPortsArray();
557}
558
559#elif defined(__WXOSX__)
560
561wxArrayString* EnumerateSerialPorts(void) {
562 wxArrayString* preturn = new wxArrayString;
563 char* paPortNames[MAX_SERIAL_PORTS];
564 int iPortNameCount;
565
566 memset(paPortNames, 0x00, sizeof(paPortNames));
567 iPortNameCount = FindSerialPortNames(&paPortNames[0], MAX_SERIAL_PORTS);
568 for (int iPortIndex = 0; iPortIndex < iPortNameCount; iPortIndex++) {
569 wxString sm(paPortNames[iPortIndex], wxConvUTF8);
570 preturn->Add(sm);
571 free(paPortNames[iPortIndex]);
572 }
573 return preturn;
574}
575
576#elif defined(__WXMSW__)
577
578wxArrayString* EnumerateSerialPorts(void) {
579 return EnumerateWindowsSerialPorts();
580}
581
582#elif defined(OCPN_USE_NEWSERIAL)
583
584wxArrayString* EnumerateSerialPorts(void) {
585 wxArrayString* preturn = new wxArrayString;
586 std::vector<serial::PortInfo> ports = serial::list_ports();
587 for (auto it = ports.begin(); it != ports.end(); ++it) {
588 wxString port(it->port);
589 if (it->description.length() > 0 && it->description != "n/a") {
590 port.Append(" - ");
591 port.Append(wxString::FromUTF8((it->description).c_str()));
592 }
593 preturn->Add(port);
594 }
595 return preturn;
596}
597
598#else
599
600#error "Cannot enumerate serial ports (missing libudev.h?)"
601
602#endif // outermost if - elif - else
std::vector< PortInfo > list_ports()
Lists the serial ports available on the system.