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