### Build and install libnserial.so with cmake Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Alternative installation method that builds the library in a separate directory and installs it system-wide using sudo make install. Requires cmake and a C compiler. ```shell cd serialportstream/dll/serialunix mkdir mybuild cd mybuild cmake .. && make sudo make install ``` -------------------------------- ### Configure and install CMake package files Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Sets the CMake install directory, computes relative include dir, configures nserialConfig.cmake and nserialConfigVersion.cmake for build and install trees, and installs them along with the exported targets. ```cmake set(CMAKE_INSTALL_CMAKEDIR "${CMAKE_INSTALL_LIBDIR}/nserial-${PACKAGE_VERSION}" CACHE PATH "Installation directory for CMake files") # Create the nserialConfig.cmake and nserialConfigVersion.cmake relative(REL_INCLUDE_DIR "${CMAKE_INSTALL_CMAKEDIR}" "${CMAKE_INSTALL_INCLUDEDIR}") # ... for the build tree set(CONF_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}") configure_file(nserialConfig.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/nserialConfig.cmake" @ONLY) # ... for the install tree (note, the file nserialConfig.cmake defines NSERIAL_CMAKE_DIR there) set(CONF_INCLUDE_DIRS "\${NSERIAL_CMAKE_DIR}/${REL_INCLUDE_DIR}") configure_file(nserialConfig.cmake.in "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/nserialConfig.cmake" @ONLY) # ... for both configure_file(nserialConfigVersion.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/nserialConfigVersion.cmake" @ONLY) # Install nserialConfig.cmake and nserialConfigVersion.cmake install(FILES "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/nserialConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/nserialConfigVersion.cmake" DESTINATION "${CMAKE_INSTALL_CMAKEDIR}" COMPONENT dev) install(EXPORT nserialTargets DESTINATION "${CMAKE_INSTALL_CMAKEDIR}" COMPONENT dev) ``` -------------------------------- ### Install library and headers Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Installs the nserial target, exporting it as nserialTargets, with runtime, library, archive, and public header destinations. ```cmake install(TARGETS nserial EXPORT nserialTargets RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") ``` -------------------------------- ### Project setup and includes Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Initializes the project with C and CXX languages, includes helper CMake modules, and configures a config.h file from config.h.in. ```cmake project(libnserial C CXX) include(${CMAKE_MODULE_PATH}/doxygen.cmake) include(${CMAKE_MODULE_PATH}/serial.cmake) include(${CMAKE_MODULE_PATH}/types.cmake) include(GNUInstallDirs) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h) ``` -------------------------------- ### Install prerequisites and build locally on Ubuntu Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/BUILD.md Run these commands on Ubuntu 16.04 or later to install Google Test and Doxygen, then execute the build script. ```sh sudo apt install libgtest-dev sudo apt install doxygen ./build.sh ``` -------------------------------- ### Install libnserial package with apt Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Install the libnserial package on Ubuntu using apt. The package version is 1.1.4-0ubuntu1~focal1_amd64.deb. ```cmd # apt install libnserial_1.1.4-0ubuntu1~focal1_amd64.deb ``` -------------------------------- ### Download and install GoogleTest Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/README.cygwin.md Commands to clone the GoogleTest framework from GitHub, build it with CMake, and install it. Required before building the serialunix package with unit tests. ```sh $ git clone https://github.com/google/googletest.git $ mkdir gtestbuild $ cd gtestbuild $ cmake ../googletest $ make $ make install ``` -------------------------------- ### Get Port Descriptions with SerialPortStream.GetPortDescriptions() Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Getting-a-List-of-Serial-Ports-with-SerialPortStream Use this method to obtain descriptions for each serial port. It returns a collection of PortDescription objects, each containing Port and Description properties. The example writes these details to the trace output. ```csharp using System.Diagnostic; foreach (SerialPortStream.PortDescription desc in SerialPortStream.GetPortDescriptions()) { Trace.WriteLine("GetPortDescriptions: " + desc.Port + "; Description: " + desc.Description); } ``` -------------------------------- ### CMakeLists.txt for nserial Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/README.cmake.md Minimal CMake configuration that finds the nserial package and links it to an executable. Requires CMake 2.8 or later and the Threads package. The nserialConfig.cmake file must be installed in the libs directory. ```cmake cmake_minimum_required(VERSION 2.8) project(helloworld) add_executable(helloworld hello.c) find_package(Threads REQUIRED) find_package(nserial CONFIG REQUIRED) include_directories(${nserial_INCLUDE_DIRS}) target_link_libraries(helloworld ${nserial_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) ``` -------------------------------- ### List COM Ports with SerialPortStream.GetPortNames() Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Getting-a-List-of-Serial-Ports-with-SerialPortStream Use this method to get a list of COM port names, compatible with the Microsoft System.IO.SerialPort implementation. The example iterates over the returned strings and writes each to the trace output. ```csharp using System.Diagnostic; foreach (string c in SerialPortStream.GetPortNames()) { Trace.WriteLine("GetPortNames: " + c); } ``` -------------------------------- ### Build Docker image with build-arg CODE_VERSION Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/docker/README.md Creates a Docker image named libnserial: based on the specified Ubuntu version. The CODENAME environment variable is set to 'focal' as an example. ```sh export CODENAME=focal docker build --build-arg CODE_VERSION=${CODENAME} -t libnserial:${CODENAME} . ``` -------------------------------- ### Access container shell as root Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/docker/README.md Runs the Docker container with 'sh' to get a shell as root. This command does not set the user/group, so it runs as root. Useful for debugging and inspecting the container. ```sh mkdir -p ../build docker run -it --rm --read-only --cap-drop all \ -v ${PWD}:/source:ro \ -v ${PWD}/../build:/build:rw \ --tmpfs /tmp \ libnserial:${CODENAME} \ sh ``` -------------------------------- ### CP2101 Driver BytesToWrite Log Output Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Example log output showing BytesToWrite values from the CP2101 driver, where the driver reports more bytes in the output queue than the current write operation returns. The internal buffer is 40kB, and the driver returned 1024 bytes written while the queue still has 40412 bytes. ```text BytesToWrite = 40960 (driver 12288) RJCP.IO.Ports.SerialPortStream Verbose: 0 : COM5: SerialThread: ProcessWriteEvent: 1024 bytes BytesToWrite = 40412 (driver 40412) RJCP.IO.Ports.SerialPortStream Verbose: 0 : COM5: SerialThread: DoWriteEvent: WriteFile(736, 312385272, 39936, ...) == False BytesToWrite = 40387 (driver 40387) BytesToWrite = 40386 (driver 40386) ``` -------------------------------- ### Modem Output Pin Properties Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Overview-of-SerialPortStream-properties Properties to get and set the state of the output pins DTR and RTS, which can be set only when handshaking is disabled. ```APIDOC ## DtrEnable ### Description Gets or sets the Data Terminal Ready (DTR) line state. Can be set only if handshaking is disabled. ### Property Type bool (read/write) ### Remarks When handshaking is enabled, the driver controls this line automatically. ## RtsEnable ### Description Gets or sets the Request To Send (RTS) line state. Can be set only if handshaking is disabled. ### Property Type bool (read/write) ### Remarks When handshaking is enabled, the driver controls this line automatically. ``` -------------------------------- ### TIOCGICOUNT Support Test Output (icount) Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Output from running the icount test program to check if the driver supports the ioctl(TIOCGICOUNT) call. The first example shows a driver that supports it (e.g., /dev/ttyS0), the second shows a driver that does not (e.g., /dev/ttyUSB0) with error 25. ```sh $ ./icount /dev/ttyS0 Your driver supports TIOCGICOUNT ocounter.cts=0 ocounter.dsr=0 ocounter.rng=3 ocounter.dcd=0 ``` ```sh $ ./icount /dev/ttyUSB0 Your driver doesn't support TIOCGICOUNT Error: 25 (Inappropriate ioctl for device) ``` -------------------------------- ### Build Release Mode Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Builds the solution in Release configuration. Release mode is unsigned, useful for beta testing or your own testing. ```cmd PS1> dotnet build -c Release ``` -------------------------------- ### Clone and build libnserial.so on Linux Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Run these commands after cloning the repository to compile the native support library libnserial.so. Requires a compiler (e.g., GCC 4.8 or later) and cmake. The binaries are placed in the bin folder relative to where the build script is run. ```shell git clone https://github.com/jcurl/serialportstream.git cd serialportstream/dll/serialunix ./build.sh ``` -------------------------------- ### hello.c using nserial Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/README.cmake.md Simple C program that includes nserial.h and prints the serial library version. The main function is declared as void, which is non-standard but works in this context. ```c #include #include #include void main(void) { printf("Version: %s\n", serial_version()); } ``` -------------------------------- ### Set up LogSource singleton for .NET Core Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Use this C# code to set up the LogSource singleton for .NET Core. It creates an ILoggerFactory with filters and adds an NUnit logger. Call Initialize() to trigger the static constructor. This is useful when upgrading from .NET Framework to .NET Core without refactoring to dependency injection. ```csharp using Microsoft.Extensions.Logging; using RJCP.CodeQuality.NUnitExtensions.Trace; using RJCP.Diagnostics.Trace; internal static class GlobalLogger { static GlobalLogger() { ILoggerFactory factory = LoggerFactory.Create(builder => { builder .AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) .AddFilter("RJCP", LogLevel.Debug) .AddNUnitLogger(); }); LogSource.SetLoggerFactory(factory); } public static void Initialize() { /* Intentially empty. By calling this method, the static constructor will be automatically called */ } } ``` -------------------------------- ### Platform-specific source selection Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Adds portlinux.c on Linux, otherwise portnone.c. ```cmake if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") set(NSERIAL_SRCS ${NSERIAL_SRCS} portlinux.c) else() set(NSERIAL_SRCS ${NSERIAL_SRCS} portnone.c) endif() ``` -------------------------------- ### Compile software in Docker container Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/docker/README.md Runs the Docker container to compile the software. It mounts the current directory as read-only source and ../build as writable build directory, uses a tmpfs for /tmp, and runs as the current user. The container expects build.sh in the source directory. ```sh mkdir -p ../build docker run -it --rm --read-only --cap-drop all \ -v ${PWD}:/source:ro \ -v ${PWD}/../build:/build:rw \ --tmpfs /tmp \ -u $(id -u ${USER}):$(id -g ${USER}) \ libnserial:${CODENAME} ``` -------------------------------- ### Run unit and component tests manually on Cygwin Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/README.cygwin.md Commands to set environment variables and run the unit and component test executables. Replace SERIALUNIXBASE with the path to the serialunix package. This workaround is needed because the tests initially fail to find the built library. ```sh $ export SERIALUNIXBASE=/home/user/serialunix $ export PATH=$PATH:$SERIALUNIXBASE/build/libnserial $ cd $SERIALUNIXBASE/build/libnserial/unittest $ ./nserialtest.exe $ cd $SERIALUNIXBASE/build/libnserial/comptest $ ./nserialcomptest.exe ``` -------------------------------- ### CMakeLists.txt for serialunix Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/CMakeLists.txt Configures the serialunix project with version variables and enables testing. Adds the libnserial subdirectory. ```cmake cmake_minimum_required(VERSION 3.10) project(serialunix C CXX) set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/CMakeModules) set(VERSION_MAJOR 1 CACHE STRING "Project major version number.") set(VERSION_MINOR 1 CACHE STRING "Project minor version number.") set(VERSION_PATCH 4 CACHE STRING "Project patch version number.") set(PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}") mark_as_advanced(VERSION_MAJOR VERSION_MINOR VERSION_PATCH) enable_testing() add_subdirectory(libnserial) ``` -------------------------------- ### Build project with dotnet build Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Build the SerialPortStream solution from the directory containing SerialPortStream.sln. The output shows the build engine version and the resulting DLLs for net40 and net45 targets. ```cmd $ dotnet build Microsoft (R) Build Engine version 16.9.0+57a23d249 for .NET Copyright (C) Microsoft Corporation. All rights reserved. Determining projects to restore... All projects are up-to-date for restore. SerialPortStream -> /home/jcurl/source/rjcp.dll.serialportstream/code/bin/Debug/net40/RJCP.SerialPortStream.dll SerialPortStream -> /home/jcurl/source/rjcp.dll.serialportstream/code/bin/Debug/net45/RJCP.SerialPortStream.dll SerialPortStreamTest -> /home/jcurl/source/rjcp.dll.serialportstream/test/SerialPortStreamTest/bin/Debug/net45/RJCP.SerialPortStreamTest.dll DatastructuresTest -> /home/jcurl/source/rjcp.dll.serialportstream/test/DatastructuresTest/bin/Debug/net40/RJCP.DatastructuresTest.dll SerialPortStreamTest -> /home/jcurl/source/rjcp.dll.serialportstream/test/SerialPortStreamTest/bin/Debug/net40/RJCP.SerialPortStreamTest.dll DatastructuresTest -> /home/jcurl/source/rjcp.dll.serialportstream/test/DatastructuresTest/bin/Debug/net45/RJCP.DatastructuresTest.dll ``` -------------------------------- ### Create shared library Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Creates the shared library target nserial from the source files. ```cmake add_library(nserial SHARED ${NSERIAL_SRCS}) ``` -------------------------------- ### Build AOT test with dotnet publish Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/test/SerialPortStream.AotSmoke/README.md Run this command in the project directory to publish the AOT test. The output on Windows is a single EXE with no DLLs at bin\Release\net10.0\win-x64\publish. ```txt dotnet publish -c release ``` -------------------------------- ### Check serial port permissions and add user to dialout group Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Lists /dev/ttyUSB* devices to verify permissions and adds the current user to the dialout group using sudo usermod. Replace with the actual username. After this, you may need to log out and back in. ```cmd $ ls -l /dev/ttyU* crw-rw---- 1 root dialout 188, 0 Apr 24 18:32 /dev/ttyUSB0 crw-rw---- 1 root dialout 188, 1 Apr 24 18:32 /dev/ttyUSB1 $ sudo usermod -aG dialout ``` -------------------------------- ### Constructor with Port Parameters Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Overview-of-SerialPortStream-properties Instantiates a SerialPortStream with specified port name and optional baud rate, data bits, parity, and stop bits. Other properties receive default values. ```APIDOC ## SerialPortStream(string portName, int baudRate = 115200, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One) ### Description Creates a new SerialPortStream instance with the specified port name and optional communication parameters. All other properties are set to their default values. ### Method Constructor ### Parameters - **portName** (string) - Required - The name of the serial port (e.g., "COM1"). - **baudRate** (int) - Optional - The baud rate. Default is 115200. - **dataBits** (int) - Optional - The number of data bits. Default is 8. - **parity** (Parity) - Optional - The parity setting. Default is Parity.None. - **stopBits** (StopBits) - Optional - The stop bits setting. Default is StopBits.One. ### Default Property Values - **HandShake** (Handshake) - Handshake.None - **Binary mode** - set (not configurable) - **AbortOnError** - cleared (not configurable) - **EventChar** - 0x1A (not configurable) - **EofChar** - 0x1A (not configurable) - **RtsControl** - checked for consistency with the properties - **XonChar** - 17 (not configurable) - **XoffChar** - 19 (not configurable) ### Examples ```csharp SerialPortStream s1 = new SerialPortStream("COM1"); SerialPortStream s2 = new SerialPortStream("COM2", 115200); SerialPortStream s3 = new SerialPortStream("COM3", 115200, 8, Parity.None, StopBits.One); ``` ``` -------------------------------- ### CMake: Configure nserial unit tests with GTest Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/unittest/CMakeLists.txt Finds GTest and Threads, includes GTest headers, builds the nserialtest executable from listed sources, links it with nserial and GTest libraries, and registers a CTest test. Requires enable_testing() in the root CMakeLists.txt. ```cmake # On Ubuntu 14.04: # # sudo apt-get install libgtest-dev find_package(GTest) # Don't forget to enable_testing() in the root of your project if(GTEST_FOUND) find_package(Threads REQUIRED) include_directories(${GTEST_INCLUDE_DIRS}) set(SERIALUNIX_GTEST_SRCS serialinit.cpp serialopen.cpp serialerror.cpp serialmodem.cpp main.cpp configuration.cpp) add_executable(nserialtest ${SERIALUNIX_GTEST_SRCS}) target_link_libraries(nserialtest nserial ${GTEST_MAIN_LIBRARIES} ${GTEST_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) add_test(NAME nserialtests COMMAND nserialtest) endif(GTEST_FOUND) ``` -------------------------------- ### CMake configuration for GTest-based component tests Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/comptest/CMakeLists.txt This CMakeLists.txt configures the build for the libnserial component tests. It finds GTest and Threads, includes GTest headers, defines the source files for the component test executable 'nserialcomptest' and the port test executable 'nserialporttest', links them against the nserial library and GTest libraries, and registers only the port test with CTest. The component test is commented out to avoid running with 'make test'. ```CMake # On Ubuntu 14.04: # # sudo apt-get install libgtest-dev find_package(GTest) # Don't forget to enable_testing() in the root of your project if(GTEST_FOUND) find_package(Threads REQUIRED) include_directories(${GTEST_INCLUDE_DIRS}) set(SERIALUNIXCOMP_GTEST_SRCS SerialSendReceiveTest.cpp SerialParityTest.cpp SerialModemSignalsTest.cpp SerialModemEvents.cpp main.cpp SerialConfiguration.cpp Buffer.cpp BuffDump.cpp SerialReadWrite.cpp) add_executable(nserialcomptest ${SERIALUNIXCOMP_GTEST_SRCS}) target_link_libraries(nserialcomptest nserial ${GTEST_MAIN_LIBRARIES} ${GTEST_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} rt) add_executable(nserialporttest ListPortTest.cpp) target_link_libraries(nserialporttest nserial ${GTEST_MAIN_LIBRARIES} ${GTEST_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} rt) # Component tests should not run with "make test" #add_test(NAME nserialcomptest COMMAND nserialcomptest) add_test(NAME nserialporttest COMMAND nserialporttest) endif(GTEST_FOUND) ``` -------------------------------- ### Include directories and source lists Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Sets include directories and defines the public headers and source files for the library. ```cmake include_directories(${CMAKE_CURRENT_BINARY_DIR}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set(NSERIAL_PUBLIC_HEADERS nserial.h) set(NSERIAL_SRCS nserial.c baudrate.c basic.c openserial.c events.c properties.c flush.c modem.c lowlevel.c break.c errmsg.c threaddata.c log.c stringbuf.c netfx.c) ``` -------------------------------- ### Set version properties Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Sets VERSION, SOVERSION, FRAMEWORK, and PUBLIC_HEADER properties for the nserial target. The comments explain versioning rules. ```cmake # Version Details: This should specify the detail of the API. It is # independent of the actual version of the project. # # SOVERSION: This is the API version of the library. It should match the # major version for consistency. # MAJOR: Should be the same as the SOVERSION. Increment this by +1 when # there is an incompatible version with the previous release. The MINOR # version should be reset to 0. # MINOR: Increment by +1 if a new method is given and the API remains # backward compatible with the previous release. # # Unlike libtool, there is no "PATCH" version. CMake doesn't make more than # one symbolic link # e.g. # libfoo.so -> libfoo.so.1 # libfoo.so.1 -> libfoo.so.1.0 # libfoo.so.1.0 # # As the PATCH doesn't indicate a change in the API, there is no need for it # in the file name (and a library can't link therefore to a specific patch # version). This also means, that the SOVERSION and the MAJOR version must be # the same to support incremental updates. set_target_properties(nserial PROPERTIES VERSION ${VERSION_MAJOR}.${VERSION_MINOR} SOVERSION ${VERSION_MAJOR} FRAMEWORK ON PUBLIC_HEADER ${NSERIAL_PUBLIC_HEADERS}) ``` -------------------------------- ### Build Debug Mode Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Builds the solution in Debug configuration. This does not generate a NuGet package to prevent deployment mistakes. ```cmd PS1> dotnet build ``` -------------------------------- ### App.Config trace configuration for IO.Ports.SerialPortStream Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Tracing Add this XML to your App.Config file to enable tracing for the SerialPortStream. Use a switchValue of 'Warning' or less verbosity unless debugging. Do not trace to the console as it may halt the application under Visual Studio; logging to a file uses less CPU. ```XML ``` -------------------------------- ### Package for NuGet Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Builds the SerialPortStream project in Release configuration and creates a NuGet package including source code. The build command is for signing, and the pack command generates the package. ```cmd PS1> dotnet build -c release .\code\SerialPortStream.csproj PS1> dotnet pack -c release --include-source .\code\SerialPortStream.csproj ``` -------------------------------- ### Run unit tests with dotnet test Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Executes the unit tests on Linux using the dotnet test command. This is the same command used on Windows. ```cmd $ dotnet test ``` -------------------------------- ### Optional logging option Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Adds an option NSLOG_ENABLED to enable logging, which adds the -DNSLOG_ENABLED definition when enabled. ```cmake option(NSLOG_ENABLED "Build the project to enable logging" OFF) if(NSLOG_ENABLED) message(STATUS "Logging enabled") add_definitions(-DNSLOG_ENABLED) endif(NSLOG_ENABLED) ``` -------------------------------- ### Default Constructor Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Overview-of-SerialPortStream-properties Creates a SerialPortStream with default settings. PortName is null and must be set before calling Open(). Defaults include BaudRate 115200, DataBits 8, Parity.None, StopBits.One, Handshake.None, and specific limits. ```csharp SerialPortStream s = new SerialPortStream(); ``` -------------------------------- ### Constructor with Port Parameters Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Overview-of-SerialPortStream-properties Instantiates SerialPortStream with specified port name and optional baud rate, data bits, parity, and stop bits. Other properties use defaults from the default constructor. ```csharp SerialPortStream s1 = new SerialPortStream("COM1"); SerialPortStream s2 = new SerialPortStream("COM2", 115200); SerialPortStream s3 = new SerialPortStream("COM3", 115200, 8, Parity.None, StopBits.One); ``` -------------------------------- ### Add subdirectories Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Adds the unittest and comptest subdirectories. ```cmake add_subdirectory(unittest) add_subdirectory(comptest) ``` -------------------------------- ### Export targets and package Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Exports the nserial target to a build-tree export file and registers the package with the CMake registry. ```cmake # Add all targets to the build-tree export set export(TARGETS nserial FILE "${CMAKE_CURRENT_BINARY_DIR}/nserialTargets.cmake") # Export the package for use from the build-tree # (this registers the build-tree with a global CMake-registry) export(PACKAGE nserial) ``` -------------------------------- ### Set LD_LIBRARY_PATH for Mono Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Add the built library directory to LD_LIBRARY_PATH so that Mono can find libnserial.so. Run this from the directory where the build script was executed, then run your Mono program from there. ```shell export LD_LIBRARY_PATH=`pwd`/bin/usr/local/lib:$LD_LIBRARY_PATH ``` -------------------------------- ### SerialPortStream.GetPortDescriptions() Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Getting-a-List-of-Serial-Ports-with-SerialPortStream Returns a collection of port descriptions, including the port name and a description string. ```APIDOC ## GetPortDescriptions() ### Description Returns a collection of port descriptions, each containing the port name and a description. ### Method GetPortDescriptions ### Syntax `public static IEnumerable GetPortDescriptions()` ### Parameters None. ### Returns - **IEnumerable** - A collection of `PortDescription` objects. ### PortDescription Properties - **Port** (string) - The COM port name. - **Description** (string) - A description of the port. ### Example ```csharp using System.Diagnostic; foreach (SerialPortStream.PortDescription desc in SerialPortStream.GetPortDescriptions()) { Trace.WriteLine("GetPortDescriptions: " + desc.Port + "; Description: " + desc.Description); } ``` ``` -------------------------------- ### Run Unit Tests in Release Mode Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Runs unit tests in Release configuration with a trx logger. Tests marked as [Explicit] will not run. ```cmd PS1> dotnet test -c Release --logger "trx" ``` -------------------------------- ### Enable logging with app.config for .NET Framework Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Use this app.config to enable verbose logging for the SerialPortStream library on .NET Framework. The trace source name is 'RJCP.IO.Ports.SerialPortStream' and the switch value is set to 'Verbose'. The listener writes to 'logfile.txt'. ```xml ``` -------------------------------- ### Build Debian packages with deb command Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/docker/README.md Runs the Docker container with the 'deb' command to build Debian packages. It requires the debian/changelog and debian/control files to exist and the codename to match. Output is placed in build/${CODENAME}. ```sh mkdir -p ../build docker run -it --rm --read-only --cap-drop all \ -v ${PWD}:/source:ro \ -v ${PWD}/../build:/build:rw \ --tmpfs /tmp \ -u $(id -u ${USER}):$(id -g ${USER}) \ libnserial:${CODENAME} \ deb ``` -------------------------------- ### Driver Buffer Configuration Properties Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Overview-of-SerialPortStream-properties Properties to configure the driver input and output queue sizes, equivalent to ReadBufferSize and WriteBufferSize in System.IO.Ports.SerialPort. ```APIDOC ## DriverInQueue ### Description Gets or sets the size of the driver input buffer. Equivalent to System.IO.Ports.SerialPort.ReadBufferSize. ### Property Type int (read/write) ### Remarks This property directly influences software flow control behavior. ## DriverOutQueue ### Description Gets or sets the size of the driver output buffer. Equivalent to System.IO.Ports.SerialPort.WriteBufferSize. ### Property Type int (read/write) ### Remarks This property directly influences software flow control behavior. ``` -------------------------------- ### Default Constructor Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Overview-of-SerialPortStream-properties Instantiates a SerialPortStream with default property values. The port name is not defined and must be set before calling Open(). ```APIDOC ## SerialPortStream() ### Description Creates a new SerialPortStream instance with default settings. The port name is null and must be set before opening the port. ### Method Constructor ### Parameters None ### Default Property Values - **PortName** (string) - null (not defined) - **BaudRate** (int) - 115200 - **DataBits** (int) - 8 - **Parity** (Parity) - Parity.None - **ParityReplace** (byte) - 0 (disabled) - **StopBits** (StopBits) - StopBits.One - **HandShake** (Handshake) - Handshake.None - **TxContinueOnXoff** (bool) - false - **XonLimit** (int) - 2048 - **XOffLimit** (int) - 512 ### Example ```csharp SerialPortStream s = new SerialPortStream(); ``` ``` -------------------------------- ### Run BufferBytesTest command line tool Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/test/README.md Command to send 160kB over COM1 at 115200 baud. Prints logging when bytes are sent and remaining bytes. Expected: BytesToWrite should monotonically decrease after flushing, never exceed initial length or internal buffer size of 131072 bytes. Observed: CP2101 may increase BytesToWrite; PL2303 RA driver reports zero or last write result. ```cmd BufferBytesTest --port COM1 --baud 115200 --length 163840 ``` -------------------------------- ### Parity Error Test Output (nserialcomptest) Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Output from running ./nserialcomptest on loopback devices, showing parity error failures on certain chipsets (FTDI, PL2303H, PL2303RA). The 16550A chipset works as expected. ```sh $ ./nserialcomptest /dev/ttyUSB0 /dev/ttyUSB1` [ RUN ] SerialParityTest.Parity7E1ReceiveError /home/jcurl/Programming/serialportstream/dll/serialunix/libnserial/comptest/SerialParityTest.cpp:221: Failure Value of: comparison Actual: false Expected: true Unexpected byte received with Even Parity [ FAILED ] SerialParityTest.Parity7E1ReceiveError (585 ms) [ RUN ] SerialParityTest.Parity7O1ReceiveError /home/jcurl/Programming/serialportstream/dll/serialunix/libnserial/comptest/SerialParityTest.cpp:373: Failure Value of: comparison Actual: false Expected: true Unexpected byte received with Even Parity [ FAILED ] SerialParityTest.Parity7O1ReceiveError (584 ms) [ RUN ] SerialParityTest.Parity7O1ReceiveErrorWithReplace /home/jcurl/Programming/serialportstream/dll/serialunix/libnserial/comptest/SerialParityTest.cpp:427: Failure Value of: comparison Actual: false Expected: true Unexpected byte received with Even Parity [ FAILED ] SerialParityTest.Parity7O1ReceiveErrorWithReplace (572 ms) ``` -------------------------------- ### Modem Input Pin Properties Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Overview-of-SerialPortStream-properties Properties to read the state of the modem input pins: CDHolding, CtsHolding, DsrHolding, and RingHolding. ```APIDOC ## CDHolding ### Description Gets the state of the Carrier Detect (CD) line. ### Property Type bool (read-only) ### Remarks Indicates whether the carrier detect signal is present. ## CtsHolding ### Description Gets the state of the Clear To Send (CTS) line. ### Property Type bool (read-only) ### Remarks Indicates whether the clear-to-send signal is present. ## DsrHolding ### Description Gets the state of the Data Set Ready (DSR) line. ### Property Type bool (read-only) ### Remarks Indicates whether the data-set-ready signal is present. ## RingHolding ### Description Gets the state of the Ring Indicator (RI) line. ### Property Type bool (read-only) ### Remarks Indicates whether the ring indicator signal is present. ``` -------------------------------- ### Garbage Data on Open Test Output (kernelbug) Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Output from running the kernelbug test program twice on /dev/ttyUSB0 and /dev/ttyUSB1. The first run passes, the second run shows a comparison mismatch due to garbage data from USB-SER drivers on Ubuntu 14.04/16.04. ```sh $ kernelbug /dev/ttyUSB0 /dev/ttyUSB1 Offset: 4 Flushing... Writing Complete... Reading complete... Comparison MATCH <---- PASS Flushing... Reading complete... Complete... $ kernelbug /dev/ttyUSB0 /dev/ttyUSB1 Offset: 108 Flushing... Flush 2 bytes Writing Complete... Reading complete... ERROR: Comparison mismatch <---- ERROR Flushing... Flush 510 bytes Reading complete... Complete... ``` -------------------------------- ### Run ReadToWithMbcs test repeatedly Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Command to run the ReadToWithMbcs test case from SerialPortStreamNativeTest, modified to run 2000 times with [Repeat(2000)], to reproduce intermittent failures when opening ports on Linux with USB serial devices. ```cmd dotnet test RJCP.SerialPortStreamNativeTest.dll --filter Name=ReadToWithMbcs ``` -------------------------------- ### VirtualSerialPortFactory for tests Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/test/SerialPortStream.Virtual/README.md Test factory that creates VirtualNativeSerial instances and stores them in a dictionary keyed by port name. This allows test code to access the virtual serial objects to simulate and verify serial communication. ```csharp public class VirtualSerialPortFactory : ISerialPortFactory { public Dictionary EndPoints = new Dictionary(); public SerialPortStream Create(string port) { VirtualNativeSerial serial = new VirtualNativeSerial();; if (EndPoints.Contains(port)) { EndPoints[port] = serial; } else { EndPoints.Add(port, serial); } return new SerialPortStream(serial); } } ``` -------------------------------- ### Assign the virtual factory Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/test/SerialPortStream.Virtual/README.md Assigns the VirtualSerialPortFactory to the static Instance property of SerialPortFactory, enabling test code to use virtual serial ports. ```csharp SerialPortFactory.Instance = new VirtualSerialPortFactory() ``` -------------------------------- ### Configure Test Ports Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Default port configuration for unit tests in test\SerialPortStreamTest\App.config. Change Win32SourcePort and Win32DestPort to actual hardware (e.g., COM1, COM2). ```xml ``` -------------------------------- ### Run Unit Tests in Debug Mode Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/BUILD.md Runs unit tests in Debug configuration. Tests marked as [Explicit] will not run. ```cmd PS1> dotnet test ``` -------------------------------- ### Configure WriteTotalTimeoutConstant for PL2303 Driver Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Sets WriteTotalTimeoutMultiplier to 0 and WriteTotalTimeoutConstant to 500 before opening the port. The PL2303 driver only works correctly when WriteTotalTimeoutConstant is zero; setting it to 500 causes flush to return too soon. The default was changed from 500 to zero in version 3.0.0-3.0.2 as part of Issue #154. ```csharp var serialPort = new RJCP.IO.Ports.WinSerialPortStream(com, 115200, 8, RJCP.IO.Ports.Parity.None, IO.Ports.StopBits.One); serialPort.Settings.WriteTotalTimeoutMultiplier = 0; serialPort.Settings.WriteTotalTimeoutConstant = 500; serialPort.Open(); ``` -------------------------------- ### Define ISerialPortFactory and SerialPortFactory Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/test/SerialPortStream.Virtual/README.md Defines the factory interface and a production implementation that creates SerialPortStream instances. The factory pattern allows test code to substitute a virtual serial port factory. ```csharp public interface ISerialPortFactory { SerialPortStream Create(string port); } public class SerialPortFactory : ISerialPortFactory { private static ISerialPortFactory _SerialPortFactory; public static ISerialPortFactory Instance { get { if (_SerialPortFactory == null) { _SerialPortFactory = new SerialPortFactory(); } return _SerialPortFactory; } set { _SerialPortFactory = value; } } public SerialPortStream Create(string port) { return new SerialPortStream(port); } } ``` -------------------------------- ### DoTransfer method with commented-out workaround for serial port flush bug Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/NOTES.bug-serialportclose.md The original DoTransfer method from sendreceivesimple.cpp, showing the workaround of writing a single byte (serial_write) commented out. The code reads data from the serial port in a loop, waiting for events with a 500ms timeout. This workaround was needed for FTDI and PL2303H adapters to avoid reading zero bytes after a process restart without closing the port. ```c int SerialReadWrite::DoTransfer(Buffer *sendBuffer) { if (sendBuffer == NULL) { throw std::invalid_argument("sendBuffer may not be NULL"); } m_writebuff = sendBuffer; char *rbuff = m_readbuff->GetBuffer(); char *wbuff = m_writebuff->GetBuffer(); int error = 0; bool writefinished; bool readfinished; serialevent_t event; // Read all data from the serial port. writefinished = false; readfinished = false; char tmpbuff[256]; // Bug found for FTDI serial ports used to receive data. We have to write a // single byte to the FTDI device, so that we can reliably flush the data in // the FTDI device. If we don't, we might read some data and look like we // flush, but we read a lot of zero's causing data to be offset. As a // workaround, if the user removes the FTDI and then reinserts it, the write // isn't needed. // // To create the issue, we need to write to the receiving port, read only a // portion of that data and kill the process. On restart of the process, // flushing doesn't work unless a single byte is first written. The problem // canot be reproduced by simply writing a portion, closing the port, then // reopening the port without closing the process in-between. See test case // "SendReceiveOpenCloseOpenClose" that attempts to do this. See the test // case "SendReceiveFinalTestCase" that does create this problem, on the // second run of the test program. // // To create the condition where not writing a single byte causes flushing // to not work properly, we need to write from the remote side before the // serial port is open for read. For example, a previous test case could // write 1000 bytes, and end without reading it. That has the same effect. // // Tested to work properly: // * 16550A standard UART for input // * PL2303RA UART for input // // Tested to not work properly: // * FTDI for input // * PL2303H for input // // Removing the write and replacing also with tcflush(fd, TCIOFLUSH) doesn't // work either. //serial_write(m_writehandle, tmpbuff, 1); // We need a small delay before resetting. Instead of actually implementing // this delay, we will continue to read doing the flush manually, as it's // faster (with the assumption that we know that data isn't being sent to us // at that time). //serial_reset(m_writehandle); //serial_reset(m_readhandle); while (!readfinished) { event = serial_waitforevent(m_readhandle, READEVENT, 500); if (event == READEVENT) { int br = serial_read(m_readhandle, tmpbuff, 256); //std::cout << br << " = read() for flush\n"; } else { readfinished = true; } } } ``` -------------------------------- ### CMake targets for kernelbug and icount executables Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/comptest/CMakeLists.txt Defines two additional executables, 'kernelbug' and 'icount', from their respective C source files. These are separate from the GTest-based tests and are always built. ```CMake add_executable(kernelbug kernelbug.c) add_executable(icount icount.c) ``` -------------------------------- ### CP2101 Driver BytesToWrite Fluctuation Log Output Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/README.md Log output showing BytesToWrite values fluctuating without any writes or OS calls in between, illustrating the CP2101 driver's inconsistent reporting of output queue size. ```text BytesToWrite = 40418 (driver 40418) BytesToWrite = 40393 (driver 40393) BytesToWrite = 40392 (driver 40392) BytesToWrite = 40391 (driver 40391) BytesToWrite = 40390 (driver 40390) BytesToWrite = 40389 (driver 40389) BytesToWrite = 40428 (driver 40428) BytesToWrite = 40427 (driver 40427) BytesToWrite = 40426 (driver 40426) ``` -------------------------------- ### SerialPortStream.GetPortNames() Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Getting-a-List-of-Serial-Ports-with-SerialPortStream Returns a list of COM port names. This method is compatible with the Microsoft implementation. ```APIDOC ## GetPortNames() ### Description Returns a collection of COM port names available on the system. ### Method GetPortNames ### Syntax `public static string[] GetPortNames()` ### Parameters None. ### Returns - **string[]** - An array of COM port names. ### Example ```csharp using System.Diagnostic; foreach (string c in SerialPortStream.GetPortNames()) { Trace.WriteLine("GetPortNames: " + c); } ``` ``` -------------------------------- ### Relative path helper function Source: https://github.com/jcurl/rjcp.dll.serialportstream/blob/master/dll/serialunix/libnserial/CMakeLists.txt Defines a function 'relative' to compute a relative path between two paths, handling absolute paths and setting the result in parent scope. ```cmake # Calculate relative paths for installation function(relative relpath path1 path2) if(NOT IS_ABSOLUTE ${path1}) set(path1 "${CMAKE_INSTALL_PREFIX}/${path1}") endif() if(NOT IS_ABSOLUTE ${path2}) set(path2 "${CMAKE_INSTALL_PREFIX}/${path2}") endif() file(RELATIVE_PATH CALCRELPATH ${path1} ${path2}) set(${relpath} ${CALCRELPATH} PARENT_SCOPE) endfunction(relative) ``` -------------------------------- ### BreakState Property Source: https://github.com/jcurl/rjcp.dll.serialportstream/wiki/Overview-of-SerialPortStream-properties Property to control the break state of the serial line. ```APIDOC ## BreakState ### Description Gets or sets the break state of the serial line. ### Property Type bool (read/write) ### Remarks Setting this to true places the line in a break condition. ```