28 #include <wx/msw/winundef.h>
35 #pragma GCC diagnostic push
36 #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
38 #pragma GCC diagnostic pop
41 #include <unordered_set>
44 #include <wx/arrstr.h>
54 #include "androidUTIL.h"
59 #ifdef OCPN_USE_NEWSERIAL
60 #include "serial/serial.h"
71 #ifdef HAVE_LINUX_SERIAL_H
72 #include "linux/serial.h"
75 #ifdef HAVE_SYS_IOCTL_H
76 #include <sys/ioctl.h>
83 #ifdef HAVE_SYS_FCNTL_H
84 #include <sys/fcntl.h>
87 #ifdef HAVE_SYS_TYPES_H
88 #include <sys/types.h>
97 #include <linux/serial.h>
103 #include <setupapi.h>
107 #include "model/macutils.h"
110 #include "model/config_vars.h"
111 #include "model/garmin_protocol_mgr.h"
114 DEFINE_GUID(GARMIN_DETECT_GUID, 0x2c9c45c2L, 0x8e7d, 0x4c08, 0xa1, 0x2d, 0x81,
115 0x6b, 0xba, 0xe7, 0x22, 0xc0);
120 #ifndef GUID_CLASS_COMPORT
121 DEFINE_GUID(GUID_CLASS_COMPORT, 0x86e0d1e0L, 0x8089, 0x11d0, 0x9c, 0xe4, 0x08,
122 0x00, 0x3e, 0x30, 0x1f, 0x73);
129 device_data(
const std::string& p,
const std::string& i) : info(i), path(p) {}
135 symlink(
const std::string& p,
const std::string& t) : path(p), target(t) {}
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;
146 #elif defined(HAVE_LINUX_SERIAL_H) && defined(HAVE_SYS_STAT_H)
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(
'/'));
156 static int isTTYreal(
const char* dev) {
159 #pragma GCC diagnostic push
160 #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
166 std::string path = device_path(dev);
167 int fd = open(path.c_str(), O_RDONLY | O_NONBLOCK | O_NOCTTY);
169 struct serial_struct serinfo;
170 if (ioctl(fd, TIOCGSERIAL, &serinfo) == 0) {
171 ok = serinfo.type != PORT_UNKNOWN;
176 if (ioctl(fd, TIOCMGET, &modem_sts) == 0) {
177 ok = (modem_sts & (TIOCM_CTS | TIOCM_LE | TIOCM_DSR)) != 0;
181 if (fd >= 0) close(fd);
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)
191 for (
auto re : patterns) {
192 if (std::regex_search(dev, re)) {
200 #pragma GCC diagnostic pop
204 static int isTTYreal(
const char* dev) {
return 1; }
209 return isTTYreal(data.path.c_str());
212 #if defined(HAVE_DIRENT_H) && defined(HAVE_READLINK)
214 #define HAVE_SYSFS_PORTS
217 static std::vector<std::string> get_device_candidates() {
218 std::vector<std::string> devices;
221 dir = opendir(
"/sys/class/tty");
223 wxLogWarning(
"Cannot open /sys/class/tty: %s", strerror(errno));
226 const std::string prefix(
"/dev/");
227 for (ent = readdir(dir); ent; ent = readdir(dir)) {
228 devices.push_back(prefix + ent->d_name);
235 static std::vector<struct symlink> get_all_links() {
236 std::vector<struct symlink> links;
239 dir = opendir(
"/dev");
241 wxLogError(
"Cannot open /dev: %s", strerror(errno));
244 const std::string prefix(
"/dev/");
245 for (ent = readdir(dir); ent; ent = readdir(dir)) {
247 const std::string path(prefix + ent->d_name);
248 int r = lstat(path.c_str(), &buf);
250 wxLogDebug(
"get_all_links: Cannot stat %s: %s", path.c_str(),
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);
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);
272 wxLogDebug(
"Enumerate: found %d good ports", ports.size());
274 std::unordered_set<std::string>(ports.begin(), ports.end());
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);
281 wxLogDebug(
"Enumerate: found %d devices", ports.size());
283 auto wx_ports =
new wxArrayString();
284 for (
auto p : ports) {
292 #if defined(HAVE_LIBUDEV)
295 static std::string get_device_info(
struct udev_device* ud) {
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;
305 #pragma GCC diagnostic push
306 #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
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);
316 const char* linkname = udev_list_entry_get_name(link);
317 if (!std::regex_search(linkname, exclude)) {
319 items.push_back(item);
321 link = udev_list_entry_get_next(link);
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);
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());
346 udev_device_unref(device);
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;
367 static wxArrayString* EnumerateWindowsSerialPorts(
void) {
368 wxArrayString* preturn =
new wxArrayString;
379 for (
int i = 1; i < g_nCOMPortCheck; i++) {
381 s.Printf(_T(
"COM%d"), i);
384 DWORD dwSize =
sizeof(COMMCONFIG);
385 if (GetDefaultCommConfig(s.fn_str(), &cc, &dwSize))
386 preturn->Add(wxString(s));
395 for (
int j=1; j<256; j++)
398 sprintf(s,
"\\\\.\\COM%d", j);
401 BOOL bSuccess = FALSE;
402 HANDLE hComm = ::CreateFile(s, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
405 if (hComm == INVALID_HANDLE_VALUE)
407 DWORD dwError = GetLastError();
409 if (dwError == ERROR_ACCESS_DENIED ||
410 dwError == ERROR_GEN_FAILURE ||
411 dwError == ERROR_SHARING_VIOLATION ||
412 dwError == ERROR_SEM_TIMEOUT)
422 preturn->Add(wxString(s));
430 GUID* guidDev = (GUID*)&GUID_CLASS_COMPORT;
432 HDEVINFO hDevInfo = INVALID_HANDLE_VALUE;
434 hDevInfo = SetupDiGetClassDevs(guidDev, NULL, NULL,
435 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
437 if (hDevInfo != INVALID_HANDLE_VALUE) {
439 SP_DEVICE_INTERFACE_DATA ifcData;
441 ifcData.cbSize =
sizeof(SP_DEVICE_INTERFACE_DATA);
442 for (DWORD ii = 0; bOk; ii++) {
443 bOk = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guidDev, ii, &ifcData);
447 SP_DEVINFO_DATA devdata = {
sizeof(SP_DEVINFO_DATA)};
448 bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifcData, NULL, 0, NULL,
453 if (GetLastError() ==
459 TCHAR fname[256] = {0};
460 TCHAR desc[256] = {0};
462 BOOL bSuccess = SetupDiGetDeviceRegistryProperty(
463 hDevInfo, &devdata, SPDRP_FRIENDLYNAME, NULL, (PBYTE)fname,
464 sizeof(fname), NULL);
466 bSuccess = bSuccess && SetupDiGetDeviceRegistryProperty(
467 hDevInfo, &devdata, SPDRP_DEVICEDESC, NULL,
468 (PBYTE)desc,
sizeof(desc), NULL);
473 bool bFoundCom =
false;
475 HKEY hDeviceRegistryKey =
476 SetupDiOpenDevRegKey(hDevInfo, &devdata, DICS_FLAG_GLOBAL, 0,
477 DIREG_DEV, KEY_QUERY_VALUE);
478 if (INVALID_HANDLE_VALUE != hDeviceRegistryKey) {
481 LPCWSTR cstr = wport;
482 MultiByteToWideChar(0, 0,
"PortName", -1, wport, 80);
483 DWORD len =
sizeof(dname);
485 int result = RegQueryValueEx(hDeviceRegistryKey, cstr, 0,
486 &RegKeyType, (PBYTE)dname, &len);
487 if (result == 0) bFoundCom =
true;
491 wxString port(dname, wxConvUTF8);
496 for (
unsigned int n = 0; n < preturn->GetCount(); n++) {
497 if ((preturn->Item(n)).IsSameAs(port)) {
498 preturn->RemoveAt(n);
502 wxString desc_name(desc, wxConvUTF8);
515 HDEVINFO hdeviceinfo = INVALID_HANDLE_VALUE;
517 hdeviceinfo = SetupDiGetClassDevs((GUID*)&GARMIN_DETECT_GUID, NULL, NULL,
518 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
520 if (hdeviceinfo != INVALID_HANDLE_VALUE) {
521 if (GarminProtocolHandler::IsGarminPlugged()) {
522 wxLogMessage(_T(
"EnumerateSerialPorts() Found Garmin USB Device."));
523 preturn->Add(_T(
"Garmin-USB"));
528 SP_DEVICE_INTERFACE_DATA deviceinterface;
529 deviceinterface.cbSize =
sizeof(deviceinterface);
531 if (SetupDiEnumDeviceInterfaces(hdeviceinfo,
533 (GUID *) &GARMIN_DETECT_GUID,
537 wxLogMessage(_T(
"Found Garmin Device."));
539 preturn->Add(_T(
"GARMIN"));
548 #if defined(OCPN_USE_SYSFS_PORTS) && defined(HAVE_SYSFS_PORTS)
550 wxArrayString* EnumerateSerialPorts(
void) {
551 return EnumerateSysfsSerialPorts();
554 #elif defined(OCPN_USE_UDEV_PORTS) && defined(HAVE_LIBUDEV)
556 wxArrayString* EnumerateSerialPorts(
void) {
return EnumerateUdevSerialPorts(); }
558 #elif defined(__ANDROID__)
560 wxArrayString* EnumerateSerialPorts(
void) {
561 return androidGetSerialPortsArray();
564 #elif defined(__WXOSX__)
566 wxArrayString* EnumerateSerialPorts(
void) {
567 wxArrayString* preturn =
new wxArrayString;
568 char* paPortNames[MAX_SERIAL_PORTS];
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);
576 free(paPortNames[iPortIndex]);
581 #elif defined(__WXMSW__)
583 wxArrayString* EnumerateSerialPorts(
void) {
584 return EnumerateWindowsSerialPorts();
587 #elif defined(OCPN_USE_NEWSERIAL)
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") {
596 port.Append(wxString::FromUTF8((it->description).c_str()));
605 #error "Cannot enumerate serial ports (missing libudev.h?)"