Hi,

The attached patch for libserialport implements FreeBSD OS-specific serial port detection and query.

/Uffe
>From 919abecb98da34f523d6aa2ae5c3593818613d74 Mon Sep 17 00:00:00 2001
From: Uffe Jakobsen <[email protected]>
Date: Tue, 13 Jan 2015 23:14:54 +0100
Subject: [PATCH] Implement FreeBSD OS-specific serial port detection and query

---
 Makefile.am  |   3 +
 configure.ac |  10 ++
 freebsd.c    | 367 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 380 insertions(+)
 create mode 100644 freebsd.c

diff --git a/Makefile.am b/Makefile.am
index 93bd793..d278a94 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -34,6 +34,9 @@ endif
 if MACOSX
 libserialport_la_SOURCES += macosx.c
 endif
+if FREEBSD
+libserialport_la_SOURCES += freebsd.c
+endif
 
 libserialport_la_LIBADD = $(LIBOBJS)
 
diff --git a/configure.ac b/configure.ac
index f8123d2..4cd1278 100644
--- a/configure.ac
+++ b/configure.ac
@@ -83,11 +83,13 @@ case $target_os in
 	AM_CONDITIONAL([LINUX], true)
 	AM_CONDITIONAL([WIN32], false)
 	AM_CONDITIONAL([MACOSX], false)
+	AM_CONDITIONAL([FREEBSD], false)
 	;;
 *darwin*)
 	AM_CONDITIONAL([LINUX], false)
 	AM_CONDITIONAL([WIN32], false)
 	AM_CONDITIONAL([MACOSX], true)
+	AM_CONDITIONAL([FREEBSD], false)
 	LDFLAGS="$LDFLAGS -Wl,-framework -Wl,IOKit -Wl,-framework -Wl,CoreFoundation"
 	AC_CHECK_HEADER(IOKit/IOKitLib.h, [], [AC_MSG_ERROR([IOKit/IOKitLib.h not found])])
 	;;
@@ -95,12 +97,20 @@ mingw* | cygwin*)
 	AM_CONDITIONAL([LINUX], false)
 	AM_CONDITIONAL([WIN32], true)
 	AM_CONDITIONAL([MACOSX], false)
+	AM_CONDITIONAL([FREEBSD], false)
 	SP_LIBS="-lsetupapi -luuid"
 	;;
+*freebsd*)
+	AM_CONDITIONAL([LINUX], false)
+	AM_CONDITIONAL([WIN32], false)
+	AM_CONDITIONAL([MACOSX], false)
+	AM_CONDITIONAL([FREEBSD], true)
+	;;
 *)
 	AM_CONDITIONAL([LINUX], false)
 	AM_CONDITIONAL([WIN32], false)
 	AM_CONDITIONAL([MACOSX], false)
+	AM_CONDITIONAL([FREEBSD], false)
 	AC_DEFINE(NO_ENUMERATION)
 	AC_DEFINE(NO_PORT_METADATA)
 esac
diff --git a/freebsd.c b/freebsd.c
new file mode 100644
index 0000000..856d61c
--- /dev/null
+++ b/freebsd.c
@@ -0,0 +1,367 @@
+/*
+ * This file is part of the libserialport project.
+ *
+ * Copyright (C) 2015 Uffe Jakobsen <[email protected]>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/*
+ * FreeBSD platform specific serial port information:
+ *
+ * FreeBSD has two device nodes for each serial port:
+ *
+ *  1) a call-in port
+ *  2) a call-out port
+ *
+ * Quoting FreeBSD Handbook section 26.2.1
+ *
+ * https://www.freebsd.org/doc/handbook/serial.html
+ *
+ * In FreeBSD, each serial port is accessed through an entry in /dev.
+ * There are two different kinds of entries:
+ *
+ * 1) Call-in ports are named /dev/ttyuN where N is the port number,
+ *    starting from zero.
+ *
+ *    If a terminal is connected to the first serial port (COM1),
+ *    use /dev/ttyu0 to refer to the terminal.
+ *    If the terminal is on the second serial port (COM2), use /dev/ttyu1,
+ *    and so forth.
+ *    Generally, the call-in port is used for terminals.
+ *    Call-in ports require that the serial line assert
+ *    the “Data Carrier Detect” signal to work correctly.
+ *
+ * 2) Call-out ports are named /dev/cuauN on FreeBSD versions 10.x and higher
+ *    and /dev/cuadN on FreeBSD versions 9.x and lower.
+ *
+ *    Call-out ports are usually not used for terminals, but are used for modems.
+ *    The call-out port can be used if the serial cable or
+ *    the terminal does not support the “Data Carrier Detect” signal.
+ *
+ * FreeBSD also provides initialization devices
+ * (/dev/ttyuN.init and /dev/cuauN.init or /dev/cuadN.init) and
+ * locking devices (/dev/ttyuN.lock and /dev/cuauN.lock or /dev/cuadN.lock).
+ * The initialization devices are used to initialize communications port parameters
+ * each time a port is opened, such as crtscts for modems which use RTS/CTS signaling
+ * for flow control.
+ * The locking devices are used to lock flags on ports to prevent users
+ * or programs changing certain parameters.
+ *
+ *
+ * In line with the above device naming USB-serial devices have
+ * the following naming:
+ *
+ * 1) call-in ports: /dev/ttyUN where N is the port number
+ * 2) call-out ports: /dev/cuaUN where N is the port number
+ *
+ * See also: ucom(4)
+ * Link: https://www.freebsd.org/cgi/man.cgi?query=ucom
+ *
+ *
+ * Getting USB serial port device description:
+ *
+ * In order to query USB serial ports for device description -
+ * the mapping between the kernel device driver instances must
+ * be correlated it with the above mentioned device nodes.
+ *
+ * 1) For each USB-serial port (/dev/cuaUN) use libusb to lookup the device description
+ *    and the name of the kernel device driver instance.
+ * 2) Query sysctl for the kernel device driver instance info.
+ * 3) Derive the ttyname and and (serial) port count for
+ *    the kernel device driver instance.
+ * 4) if sysctl ttyname and port matches /dev/cuaUN apply the libusb device description
+ *
+ */
+
+#include "libserialport.h"
+#include "libserialport_internal.h"
+
+#include <unistd.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <sys/types.h>
+#include <sys/sysctl.h>
+#include <dirent.h>
+
+#include <libusb20.h>
+#include <libusb20_desc.h>
+
+
+#define DEV_CUA_PATH "/dev/cua"
+
+//#define DBG(...) printf(__VA_ARGS__)
+#define DBG(...)
+
+/*
+ * strrspn() helper-util
+ */
+static char* sp_strrspn(const char* s, const char* charset)
+{
+  char* t = (char*) s + strlen(s);
+  while (t != (char*)s)
+    if (!strchr(charset, *(--t)))
+      return (++t);
+
+  return t;
+}
+
+/*
+ * strend() helper-util
+ */
+static int sp_strend(const char* str, const char* pattern)
+{
+    size_t slen = strlen(str);
+    size_t plen = strlen(pattern);
+    if  (slen >= plen) {
+       return (memcmp(pattern, (str+slen-plen), plen) == 0);
+    }
+    return 0;
+}
+
+SP_PRIV enum sp_return get_port_details(struct sp_port *port)
+{
+  int rc;
+  struct libusb20_backend *p_be;
+  struct libusb20_device *p_dev, *p_dev_last;
+  char sbuf[FILENAME_MAX];
+  char *p_cua_sfx;
+  int cua_dev_found;
+  uint8_t idx;
+
+  DBG("portname: '%s'\n", port->name);
+
+  if (strncmp(port->name, DEV_CUA_PATH, strlen(DEV_CUA_PATH)) == 0) {
+    p_cua_sfx = port->name+strlen(DEV_CUA_PATH);
+    DBG("'%s': '%s'\n", DEV_CUA_PATH, p_cua_sfx);
+  } else
+    RETURN_ERROR(SP_ERR_ARG, "Device name not recognized.");
+
+  p_dev =  p_dev_last = NULL;
+  p_be = libusb20_be_alloc_default();
+  cua_dev_found = 0;
+  while (cua_dev_found == 0) {
+    p_dev = libusb20_be_device_foreach(p_be, p_dev_last);
+    if (p_dev == NULL) {
+      break;
+    }
+
+    libusb20_dev_open(p_dev, 0);
+    DBG("device descriptor: '%s'\n", libusb20_dev_get_desc(p_dev));
+
+    for (idx = 0; idx <= UINT8_MAX-1; idx++) {
+      rc = libusb20_dev_kernel_driver_active(p_dev, idx);
+      if (rc >= 0) {
+
+        sbuf[0] = 0;
+        libusb20_dev_get_iface_desc(p_dev, idx, (char*)&sbuf, (uint8_t)sizeof(sbuf)-1);
+        if (sbuf[0] != 0) {
+          char *i, *j;
+          char *p_dev_drv_str;
+          char *p_drv_name_str = NULL;
+          char *p_drv_inst_str = NULL;
+          char *p_ttyname = NULL;
+          int ttyport_cnt;
+          char tbuf[FILENAME_MAX];
+          size_t tbuf_len;
+
+          DBG("device interface descriptor: idx=%003d '%s'\n", idx, sbuf);
+
+          i = sbuf;
+          j = strchr(sbuf, ':');
+          if (j > i) {
+            p_dev_drv_str = strndup(i, j-i);
+
+            // The device driver name may contain digits that
+            // is not a part of the device instance number - like "u3g"
+            i = p_dev_drv_str;
+            j = sp_strrspn(i, "0123456789");
+            if (j > i) {
+              p_drv_name_str = strndup(i, j-i);
+              p_drv_inst_str = strdup((j));
+
+              DBG("info: '%s' '%s' '%s'\n", p_dev_drv_str?p_dev_drv_str:"NULL", p_drv_name_str?p_drv_name_str:"NULL", p_drv_inst_str?p_drv_inst_str:"NULL");
+
+              snprintf(sbuf, sizeof(sbuf)-1, "dev.%s.%s.ttyname", p_drv_name_str, p_drv_inst_str);
+              tbuf_len = sizeof(tbuf)-1;
+              rc = sysctlbyname(sbuf, tbuf, &tbuf_len, NULL, 0);
+              if (rc == 0) {
+                tbuf[tbuf_len] = 0;
+                p_ttyname = strndup(tbuf, tbuf_len);
+                DBG("sysctl: '%s' (%d) (%d): '%.*s'\n", sbuf, rc, (int)tbuf_len, (int)tbuf_len, tbuf);
+              }
+
+              snprintf(sbuf, sizeof(sbuf)-1, "dev.%s.%s.ttyports", p_drv_name_str, p_drv_inst_str);
+              tbuf_len = sizeof(tbuf)-1;
+              rc = sysctlbyname(sbuf, tbuf, &tbuf_len, NULL, 0);
+              if (rc == 0) {
+                ttyport_cnt = *(uint32_t*)tbuf;
+                DBG("sysctl: '%s' (%d) (%d): '%d'\n", sbuf, rc, (int)tbuf_len, (int)ttyport_cnt);
+              } else {
+                ttyport_cnt = 0;
+              }
+
+              {
+                int sub_inst;
+                // handle multiple subinstances of serial ports in the same driver instance
+                for (sub_inst = 0; sub_inst < ttyport_cnt; sub_inst++) {
+                  if (ttyport_cnt == 1) {
+                    snprintf(tbuf, sizeof(tbuf)-1, "%s", p_ttyname);
+                  } else {
+                    snprintf(tbuf, sizeof(tbuf)-1, "%s.%d", p_ttyname, sub_inst);
+                  }
+                  if (strcmp(p_cua_sfx, tbuf) == 0) {
+                    DBG("MATCH: '%s' == '%s'\n", p_cua_sfx, tbuf);
+                    // populate port structure
+                    struct LIBUSB20_DEVICE_DESC_DECODED* p_dev_desc = libusb20_dev_get_device_desc(p_dev);
+                    if (p_dev_desc) {
+                      port->transport = SP_TRANSPORT_USB;
+                      port->usb_vid = p_dev_desc->idVendor;
+                      port->usb_pid = p_dev_desc->idProduct;
+                      port->usb_bus = libusb20_dev_get_bus_number(p_dev);
+                      port->usb_address = libusb20_dev_get_address(p_dev);
+                      if (libusb20_dev_req_string_simple_sync(p_dev, p_dev_desc->iManufacturer, tbuf, sizeof(tbuf)) == 0) {
+                        port->usb_manufacturer = strdup(tbuf);
+                      }
+                      if (libusb20_dev_req_string_simple_sync(p_dev, p_dev_desc->iProduct, tbuf, sizeof(tbuf)) == 0) {
+                        port->usb_product = strdup(tbuf);
+                      }
+                      if (libusb20_dev_req_string_simple_sync(p_dev, p_dev_desc->iSerialNumber, tbuf, sizeof(tbuf)) == 0) {
+                        port->usb_serial = strdup(tbuf);
+                      }
+
+                      // if present - add serial to description for better identification
+                      tbuf[0] = '\0';
+                      if (port->usb_product && port->usb_product[0]) {
+                        strncat(tbuf, port->usb_product, sizeof(tbuf)-1);
+                      } else {
+                        strncat(tbuf, libusb20_dev_get_desc(p_dev), sizeof(tbuf)-1);
+                      }
+                      if (port->usb_serial && port->usb_serial[0]) {
+                        strncat(tbuf, " ", sizeof(tbuf)-1);
+                        strncat(tbuf, port->usb_serial, sizeof(tbuf)-1);
+                      }
+                      port->description = strdup(tbuf);
+                      port->bluetooth_address = NULL;
+                    }
+                    cua_dev_found = 1;
+                    break;
+                  }
+                }
+              }
+
+              if (p_ttyname) {
+                free(p_ttyname);
+              }
+              if (p_dev_drv_str) {
+                free(p_dev_drv_str);
+              }
+              if (p_drv_name_str) {
+                free(p_drv_name_str);
+              }
+              if (p_drv_inst_str) {
+                free(p_drv_inst_str);
+              }
+            }
+          }
+        }
+      }
+      // if found break from port idx loop
+      if (cua_dev_found) {
+        break;
+      }
+    }
+
+    libusb20_dev_close(p_dev);
+    p_dev_last = p_dev;
+  }
+
+  libusb20_be_free(p_be);
+
+  if (cua_dev_found == 0) {
+    DBG("WARN: found no match '%s' %s'\n", port->name, p_cua_sfx);
+  }
+
+  RETURN_OK();
+}
+
+SP_PRIV enum sp_return list_ports(struct sp_port ***list)
+{
+  DIR *dir;
+  struct dirent entry;
+  struct dirent *result;
+  struct termios tios;
+  char name[PATH_MAX];
+  int fd;
+  int ret = SP_OK;
+
+  DEBUG("Enumerating tty devices");
+  if (!(dir = opendir("/dev")))
+    RETURN_FAIL("could not open dir /dev");
+
+  DEBUG("Iterating over results");
+  while (!readdir_r(dir, &entry, &result) && result) {
+    //DBG("%s: %s\n", __func__, entry.d_name);
+    if (entry.d_type != DT_CHR)
+      continue;
+    if (strncmp(entry.d_name, "cuaU", 4) != 0)
+      if (strncmp(entry.d_name, "cuau", 4) != 0)
+        if (strncmp(entry.d_name, "cuad", 4) != 0)
+          continue;
+    if (sp_strend(entry.d_name, ".init"))
+      continue;
+    if (sp_strend(entry.d_name, ".lock"))
+      continue;
+
+    DEBUG_FMT("Found device %s", name);
+    snprintf(name, sizeof(name), "/dev/%s", entry.d_name);
+
+    // check that we can open tty/cua device in rw mode - we need that
+    if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY | O_TTY_INIT | O_CLOEXEC)) < 0) {
+      DEBUG("open failed, skipping");
+      continue;
+    }
+
+    // sanity check if we got a real tty
+    if (!isatty(fd)) {
+      close(fd);
+      continue;
+    }
+    if (tcgetattr(fd, &tios) < 0) {
+      close(fd);
+      continue;
+    }
+    close(fd);
+
+    if ((cfgetospeed(&tios) <= 0) || (cfgetispeed(&tios) <= 0)) {
+      continue;
+    }
+
+    DEBUG_FMT("Found port %s", name);
+    DBG("%s: %s\n", __func__, entry.d_name);
+
+    *list = list_append(*list, name);
+    if (!list) {
+      SET_ERROR(ret, SP_ERR_MEM, "list append failed");
+      break;
+    }
+  }
+  closedir(dir);
+
+  return ret;
+}
-- 
2.2.2

------------------------------------------------------------------------------
New Year. New Location. New Benefits. New Data Center in Ashburn, VA.
GigeNET is offering a free month of service with a new server in Ashburn.
Choose from 2 high performing configs, both with 100TB of bandwidth.
Higher redundancy.Lower latency.Increased capacity.Completely compliant.
http://p.sf.net/sfu/gigenet
_______________________________________________
sigrok-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/sigrok-devel

Reply via email to