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>
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
83#ifdef HAVE_SYS_FCNTL_H
87#ifdef HAVE_SYS_TYPES_H
97#include <linux/serial.h>
111#include "garmin_protocol_mgr.h"
114DEFINE_GUID(GARMIN_DETECT_GUID, 0x2c9c45c2L, 0x8e7d, 0x4c08, 0xa1, 0x2d, 0x81,
115 0x6b, 0xba, 0xe7, 0x22, 0xc0);
120#ifndef GUID_CLASS_COMPORT
121DEFINE_GUID(GUID_CLASS_COMPORT, 0x86e0d1e0L, 0x8089, 0x11d0, 0x9c, 0xe4, 0x08,
122 0x00, 0x3e, 0x30, 0x1f, 0x73);
126extern int g_nCOMPortCheck;
131 device_data(
const std::string& p,
const std::string& i) : info(i), path(p) {}
137 symlink(
const std::string& p,
const std::string& t) : path(p), target(t) {}
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;
148#elif defined(HAVE_LINUX_SERIAL_H) && defined(HAVE_SYS_STAT_H)
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(
'/'));
158static int isTTYreal(
const char* dev) {
161#pragma GCC diagnostic push
162#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
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;
172 struct serial_struct serinfo;
173 if (ioctl(fd, TIOCGSERIAL, &serinfo) == 0) {
174 ok = serinfo.type != PORT_UNKNOWN;
179 if (ioctl(fd, TIOCMGET, &modem_sts) == 0) {
180 ok = (modem_sts & (TIOCM_CTS | TIOCM_LE | TIOCM_DSR)) != 0;
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)) {
201#pragma GCC diagnostic pop
205static int isTTYreal(
const char* dev) {
return 1; }
210 return isTTYreal(data.path.c_str());
213#if defined(HAVE_DIRENT_H) && defined(HAVE_READLINK)
215#define HAVE_SYSFS_PORTS
218static std::vector<std::string> get_device_candidates() {
219 std::vector<std::string> devices;
222 dir = opendir(
"/sys/class/tty");
224 wxLogWarning(
"Cannot open /sys/class/tty: %s", strerror(errno));
227 const std::string prefix(
"/dev/");
228 for (ent = readdir(dir); ent; ent = readdir(dir)) {
229 devices.push_back(prefix + ent->d_name);
236static std::vector<struct symlink> get_all_links() {
237 std::vector<struct symlink> links;
240 dir = opendir(
"/dev");
242 wxLogError(
"Cannot open /dev: %s", strerror(errno));
245 const std::string prefix(
"/dev/");
246 for (ent = readdir(dir); ent; ent = readdir(dir)) {
248 const std::string path(prefix + ent->d_name);
249 int r = lstat(path.c_str(), &buf);
251 wxLogDebug(
"get_all_links: Cannot stat %s: %s", path.c_str(),
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);
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);
273 wxLogDebug(
"Enumerate: found %d good ports", ports.size());
275 std::unordered_set<std::string>(ports.begin(), ports.end());
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);
282 wxLogDebug(
"Enumerate: found %d devices", ports.size());
284 auto wx_ports =
new wxArrayString();
285 for (
auto p : ports) {
293#if defined(HAVE_LIBUDEV)
296static std::string get_device_info(
struct udev_device* ud) {
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;
306#pragma GCC diagnostic push
307#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
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);
317 const char* linkname = udev_list_entry_get_name(link);
318 if (!std::regex_search(linkname, exclude)) {
320 items.push_back(item);
322 link = udev_list_entry_get_next(link);
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);
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());
347 udev_device_unref(device);
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());
366static wxArrayString* EnumerateWindowsSerialPorts(
void) {
367 wxArrayString* preturn =
new wxArrayString;
378 for (
int i = 1; i < g_nCOMPortCheck; i++) {
380 s.Printf(_T(
"COM%d"), i);
383 DWORD dwSize =
sizeof(COMMCONFIG);
384 if (GetDefaultCommConfig(s.fn_str(), &cc, &dwSize))
385 preturn->Add(wxString(s));
394 for (
int j=1; j<256; j++)
397 sprintf(s,
"\\\\.\\COM%d", j);
400 BOOL bSuccess = FALSE;
401 HANDLE hComm = ::CreateFile(s, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
404 if (hComm == INVALID_HANDLE_VALUE)
406 DWORD dwError = GetLastError();
408 if (dwError == ERROR_ACCESS_DENIED ||
409 dwError == ERROR_GEN_FAILURE ||
410 dwError == ERROR_SHARING_VIOLATION ||
411 dwError == ERROR_SEM_TIMEOUT)
421 preturn->Add(wxString(s));
429 GUID* guidDev = (GUID*)&GUID_CLASS_COMPORT;
431 HDEVINFO hDevInfo = INVALID_HANDLE_VALUE;
433 hDevInfo = SetupDiGetClassDevs(guidDev, NULL, NULL,
434 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
436 if (hDevInfo != INVALID_HANDLE_VALUE) {
438 SP_DEVICE_INTERFACE_DATA ifcData;
440 ifcData.cbSize =
sizeof(SP_DEVICE_INTERFACE_DATA);
441 for (DWORD ii = 0; bOk; ii++) {
442 bOk = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guidDev, ii, &ifcData);
446 SP_DEVINFO_DATA devdata = {
sizeof(SP_DEVINFO_DATA)};
447 bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo, &ifcData, NULL, 0, NULL,
452 if (GetLastError() ==
458 TCHAR fname[256] = {0};
459 TCHAR desc[256] = {0};
461 BOOL bSuccess = SetupDiGetDeviceRegistryProperty(
462 hDevInfo, &devdata, SPDRP_FRIENDLYNAME, NULL, (PBYTE)fname,
463 sizeof(fname), NULL);
465 bSuccess = bSuccess && SetupDiGetDeviceRegistryProperty(
466 hDevInfo, &devdata, SPDRP_DEVICEDESC, NULL,
467 (PBYTE)desc,
sizeof(desc), NULL);
472 bool bFoundCom =
false;
474 HKEY hDeviceRegistryKey =
475 SetupDiOpenDevRegKey(hDevInfo, &devdata, DICS_FLAG_GLOBAL, 0,
476 DIREG_DEV, KEY_QUERY_VALUE);
477 if (INVALID_HANDLE_VALUE != hDeviceRegistryKey) {
480 LPCWSTR cstr = wport;
481 MultiByteToWideChar(0, 0,
"PortName", -1, wport, 80);
482 DWORD len =
sizeof(dname);
484 int result = RegQueryValueEx(hDeviceRegistryKey, cstr, 0,
485 &RegKeyType, (PBYTE)dname, &len);
486 if (result == 0) bFoundCom =
true;
490 wxString port(dname, wxConvUTF8);
495 for (
unsigned int n = 0; n < preturn->GetCount(); n++) {
496 if ((preturn->Item(n)).IsSameAs(port)) {
497 preturn->RemoveAt(n);
501 wxString desc_name(desc, wxConvUTF8);
514 HDEVINFO hdeviceinfo = INVALID_HANDLE_VALUE;
516 hdeviceinfo = SetupDiGetClassDevs((GUID*)&GARMIN_DETECT_GUID, NULL, NULL,
517 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
519 if (hdeviceinfo != INVALID_HANDLE_VALUE) {
520 if (GarminProtocolHandler::IsGarminPlugged()) {
521 wxLogMessage(_T(
"EnumerateSerialPorts() Found Garmin USB Device."));
522 preturn->Add(_T(
"Garmin-USB"));
527 SP_DEVICE_INTERFACE_DATA deviceinterface;
528 deviceinterface.cbSize =
sizeof(deviceinterface);
530 if (SetupDiEnumDeviceInterfaces(hdeviceinfo,
532 (GUID *) &GARMIN_DETECT_GUID,
536 wxLogMessage(_T(
"Found Garmin Device."));
538 preturn->Add(_T(
"GARMIN"));
547#if defined(OCPN_USE_SYSFS_PORTS) && defined(HAVE_SYSFS_PORTS)
549wxArrayString* EnumerateSerialPorts(
void) {
550 return EnumerateSysfsSerialPorts();
553#elif defined(OCPN_USE_UDEV_PORTS) && defined(HAVE_LIBUDEV)
555wxArrayString* EnumerateSerialPorts(
void) {
return EnumerateUdevSerialPorts(); }
557#elif defined(__ANDROID__)
559wxArrayString* EnumerateSerialPorts(
void) {
560 return androidGetSerialPortsArray();
563#elif defined(__WXOSX__)
565wxArrayString* EnumerateSerialPorts(
void) {
566 wxArrayString* preturn =
new wxArrayString;
567 char* paPortNames[MAX_SERIAL_PORTS];
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);
575 free(paPortNames[iPortIndex]);
580#elif defined(__WXMSW__)
582wxArrayString* EnumerateSerialPorts(
void) {
583 return EnumerateWindowsSerialPorts();
586#elif defined(OCPN_USE_NEWSERIAL)
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") {
595 port.Append(wxString::FromUTF8((it->description).c_str()));
604#error "Cannot enumerate serial ports (missing libudev.h?)"