From c9a590f45d7eb04ae0acf240c229421812900f8c Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 13:14:44 +0200 Subject: [PATCH 01/45] Add initial project structure with CMake configuration, coding style settings, and core library headers --- .clang-format | 17 +++++++ .clang-tidy | 30 ++++++++++++ .gitignore | 4 ++ CMakeLists.txt | 74 ++++++++++++++++++++++++++++++ cmake/cpp_coreConfig.cmake.in | 5 ++ include/cpp_core/helpers.h | 3 ++ include/cpp_core/serial.h | 81 +++++++++++++++++++++++++++++++++ include/cpp_core/status_codes.h | 19 ++++++++ include/cpp_core/version.h.in | 17 +++++++ 9 files changed, 250 insertions(+) create mode 100644 .clang-format create mode 100644 .clang-tidy create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 cmake/cpp_coreConfig.cmake.in create mode 100644 include/cpp_core/helpers.h create mode 100644 include/cpp_core/serial.h create mode 100644 include/cpp_core/status_codes.h create mode 100644 include/cpp_core/version.h.in diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..0b8c0be --- /dev/null +++ b/.clang-format @@ -0,0 +1,17 @@ +BasedOnStyle: LLVM +IndentWidth: 4 +ColumnLimit: 140 +TabWidth: 4 +UseTab: Never +BreakBeforeBraces: Allman +AllowShortFunctionsOnASingleLine: Empty +PointerAlignment: Left +DerivePointerAlignment: false +SpaceBeforeParens: ControlStatements +SortIncludes: true +IncludeBlocks: Regroup +ReflowComments: true +ContinuationIndentWidth: 4 +BinPackParameters: false +BinPackArguments: false + \ No newline at end of file diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..c675794 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,30 @@ +Checks: > + -*, + readability-* , + modernize-* , + -modernize-use-trailing-return-type, + -readability-magic-numbers, + +WarningsAsErrors: > + bugprone-* , + performance-* , + clang-analyzer-* + +HeaderFilterRegex: 'include/.*' +FormatStyle: file + +CheckOptions: + - key: modernize-use-auto.MinTypeNameLength + value: '5' + - key: modernize-use-auto.RemoveStars + value: 'false' + - key: readability-identifier-naming.VariableCase + value: lower_case + - key: readability-identifier-naming.MemberCase + value: lower_case + - key: readability-identifier-naming.PrivateMemberPrefix + value: '_' + - key: readability-function-size.ParameterThreshold + value: '8' + - key: readability-braces-around-statements.ShortStatementLines + value: '0' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12d6de1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +include/cpp_core/version.h +build/ + + diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..2adf8d5 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,74 @@ +cmake_minimum_required(VERSION 3.14) + +project(cpp-core + VERSION 0.1.0 + DESCRIPTION "Cross-platform helper library shared by cpp-linux-bindings and cpp-windows-bindings" + LANGUAGES CXX) + +# --------------------------------------------------------------------------- +# Version information - can be overridden by parent project +# --------------------------------------------------------------------------- +if(NOT DEFINED CPP_CORE_VERSION_MAJOR) + set(CPP_CORE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) +endif() +if(NOT DEFINED CPP_CORE_VERSION_MINOR) + set(CPP_CORE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) +endif() +if(NOT DEFINED CPP_CORE_VERSION_PATCH) + set(CPP_CORE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) +endif() + +# Generate version header at configure time +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/include/cpp_core/version.h.in + ${CMAKE_CURRENT_SOURCE_DIR}/include/cpp_core/version.h + @ONLY) + +# Header-only library -------------------------------------------------------- +add_library(cpp_core INTERFACE) +add_library(cpp_core::cpp_core ALIAS cpp_core) + +# Public include directories +target_include_directories(cpp_core INTERFACE + $ + $ + $) + +# Require C++17 +target_compile_features(cpp_core INTERFACE cxx_std_17) + +# Install rules -------------------------------------------------------------- +include(GNUInstallDirs) + +install(TARGETS cpp_core + EXPORT cpp_coreTargets) + +install(DIRECTORY include/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + +# also install the generated version header +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/generated/cpp_core/version.h + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/cpp_core) + +# CMake package configuration ------------------------------------------------ +include(CMakePackageConfigHelpers) + +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/cpp_coreConfigVersion.cmake + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion) + +configure_package_config_file( + ${CMAKE_CURRENT_LIST_DIR}/cmake/cpp_coreConfig.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/cpp_coreConfig.cmake + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cpp_core) + +install(EXPORT cpp_coreTargets + FILE cpp_coreTargets.cmake + NAMESPACE cpp_core:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cpp_core) + +install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/cpp_coreConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/cpp_coreConfigVersion.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cpp_core) diff --git a/cmake/cpp_coreConfig.cmake.in b/cmake/cpp_coreConfig.cmake.in new file mode 100644 index 0000000..65434e4 --- /dev/null +++ b/cmake/cpp_coreConfig.cmake.in @@ -0,0 +1,5 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/cpp_coreTargets.cmake") + +check_required_components(cpp_core) diff --git a/include/cpp_core/helpers.h b/include/cpp_core/helpers.h new file mode 100644 index 0000000..e367b92 --- /dev/null +++ b/include/cpp_core/helpers.h @@ -0,0 +1,3 @@ +#pragma once + +namespace cpp_core {} // namespace cpp_core diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h new file mode 100644 index 0000000..0379864 --- /dev/null +++ b/include/cpp_core/serial.h @@ -0,0 +1,81 @@ +#pragma once +#include "version.h" + +#include + +#if defined(_WIN32) || defined(__CYGWIN__) +#ifdef cpp_windows_bindings_EXPORTS +#define MODULE_API __declspec(dllexport) +#else +#define MODULE_API __declspec(dllimport) +#endif +#else +#define MODULE_API __attribute__((visibility("default"))) +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + MODULE_API void getVersion(cpp_core::Version* out); + + // Basic serial API + MODULE_API intptr_t + serialOpen(void* port, int baudrate, int dataBits, int parity /*0-none,1-even,2-odd*/ = 0, int stopBits /*0-1bit,2-2bit*/ = 0); + + MODULE_API void serialClose(int64_t handle); + + MODULE_API int serialRead(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/, int multiplier); + + MODULE_API int serialReadUntil(int64_t handle, void* buffer, int bufferSize, int timeout, int multiplier, void* untilChar); + + MODULE_API int serialWrite(int64_t handle, const void* buffer, int bufferSize, int timeout, int multiplier); + + // Enumerate ports; callback gets simple COM name first (e.g. "COM3"), + // followed by the full device path and further meta-data. + MODULE_API int serialGetPortsInfo(void (*function)(const char* port, + const char* path, + const char* manufacturer, + const char* serialNumber, + const char* pnpId, + const char* locationId, + const char* productId, + const char* vendorId)); + + MODULE_API void serialClearBufferIn(int64_t handle); + MODULE_API void serialClearBufferOut(int64_t handle); + MODULE_API void serialAbortRead(int64_t handle); + MODULE_API void serialAbortWrite(int64_t handle); + + // Optional callback hooks (can be nullptr) + extern void (*on_read_callback)(int bytes); + extern void (*on_write_callback)(int bytes); + extern void (*on_error_callback)(int errorCode, const char* message); + + MODULE_API void serialOnRead(void (*func)(int bytes)); + MODULE_API void serialOnWrite(void (*func)(int bytes)); + MODULE_API void serialOnError(void (*func)(int code, const char* message)); + + MODULE_API int serialReadLine(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/); + + MODULE_API int serialWriteLine(int64_t handle, const void* buffer, int bufferSize, int timeout /*ms*/); + + MODULE_API int serialReadUntilSequence(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/, void* sequence); + + MODULE_API int serialReadFrame(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/, char startByte, char endByte); + + // Byte statistics + MODULE_API int64_t serialOutBytesTotal(int64_t handle); + MODULE_API int64_t serialInBytesTotal(int64_t handle); + + // Drain pending TX bytes (wait until sent) + MODULE_API int serialDrain(int64_t handle); + + // Bytes currently queued in the driver buffers + MODULE_API int serialInBytesWaiting(int64_t handle); + MODULE_API int serialOutBytesWaiting(int64_t handle); + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/status_codes.h b/include/cpp_core/status_codes.h new file mode 100644 index 0000000..a48b8c8 --- /dev/null +++ b/include/cpp_core/status_codes.h @@ -0,0 +1,19 @@ +#pragma once + +enum class StatusCodes +{ + SUCCESS = 0, + CLOSE_HANDLE_ERROR = -1, + INVALID_HANDLE_ERROR = -2, + READ_ERROR = -3, + WRITE_ERROR = -4, + GET_STATE_ERROR = -5, + SET_STATE_ERROR = -6, + SET_TIMEOUT_ERROR = -7, + BUFFER_ERROR = -8, + NOT_FOUND_ERROR = -9, + CLEAR_BUFFER_IN_ERROR = -10, + CLEAR_BUFFER_OUT_ERROR = -11, + ABORT_READ_ERROR = -12, + ABORT_WRITE_ERROR = -13, +}; diff --git a/include/cpp_core/version.h.in b/include/cpp_core/version.h.in new file mode 100644 index 0000000..5bdfa42 --- /dev/null +++ b/include/cpp_core/version.h.in @@ -0,0 +1,17 @@ +#pragma once + +namespace cpp_core +{ + +struct Version +{ + unsigned int major; + unsigned int minor; + unsigned int patch; +}; + +// Generated at configure time. Parent project can override the numbers via +// -DCPP_CORE_VERSION_XXX=... or CPM OPTIONS +constexpr Version VERSION{@CPP_CORE_VERSION_MAJOR@U, @CPP_CORE_VERSION_MINOR@U, @CPP_CORE_VERSION_PATCH@U}; + +} // namespace cpp_core From 4e8b4088aa1f37f53e2cd6534c135b494629e110 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 13:20:02 +0200 Subject: [PATCH 02/45] Revise README.md to reflect project renaming to cpp-core, update project description, add requirements, and include quick start guide for usage with CPM.cmake and find_package. --- README.md | 88 +++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 76 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index ccae452..092b5a4 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,82 @@ -# CPP-Bindings +# cpp-core -C++ bindings for low level communication with the OS. These bindings provide functions to `open`, `close`, `read`, `write`, etc. to or from a serial connection. The functions than can be used through a [dynamic link library](https://de.wikipedia.org/wiki/Dynamic_Link_Library) or [shared object](https://en.wikipedia.org/wiki/Library_(computing)#Shared_libraries). +Header-only C++ helper library that provides small, cross-platform utilities and a centrally maintained **Version** struct shared by the *cpp-linux-bindings* and *cpp-windows-bindings* repositories. -## Documentation -Check out the [Wiki](https://github.com/Serial-Link/CPP-Bindings/wiki) section on how to use these bindings. +* C++17, zero runtime dependencies +* Delivered as an INTERFACE target `cpp_core::cpp_core` +* Fetchable via [CPM.cmake](https://github.com/cpm-cmake/CPM.cmake) or regular `find_package` -## Credits -- Big thanks goes out to [@Katze719](https://github.com/Katze719) who wrote most of the C++ files and functions! -- Thanks to [@AapoAlas](https://github.com/aapoalas) for the great support and help on the [Deno Discord](https://discord.gg/deno)! -- Thanks to [@Dj](https://github.com/DjDeveloperr) for the inspiration on how to write such a library! +--- -## Licence -Apache-2.0. Check [LICENSE](https://github.com/Serial-Link/CPP-Bindings/blob/main/LICENSE) for more details. +## Requirements -Feel free to contribute to this project. +* CMake ≥ 3.14 +* A C++17 compatible compiler (GCC 10+, Clang 11+, MSVC 2019+) -Copyright 2024 © Paul & Max +--- + +## Quick Start + +### 1. Add *cpp-core* with CPM.cmake + +```cmake +# Your own project version +set(CPP_LINUX_VERSION_MAJOR 1) +set(CPP_LINUX_VERSION_MINOR 4) +set(CPP_LINUX_VERSION_PATCH 0) + +CPMAddPackage( + NAME cpp_core + GITHUB_REPOSITORY /cpp-core # Fork / upstream repo + GIT_TAG main # or a release tag like v0.1.0 + OPTIONS + "CPP_CORE_VERSION_MAJOR=${CPP_LINUX_VERSION_MAJOR}" + "CPP_CORE_VERSION_MINOR=${CPP_LINUX_VERSION_MINOR}" + "CPP_CORE_VERSION_PATCH=${CPP_LINUX_VERSION_PATCH}" +) + +add_executable(my_app src/main.cpp) +# Link the header-only target – this only sets include paths / compile features +target_link_libraries(my_app PRIVATE cpp_core::cpp_core) +``` + +> Tip: If you already set the version variables as cache variables in your project (e.g. `set(CPP_CORE_VERSION_MAJOR 1 CACHE STRING "")`), you can omit the three `OPTIONS` entries—CPM will forward the values to *cpp-core* automatically. + +### 2. Use in code + +```cpp +#include +#include + +int main() { + constexpr auto v = cpp_core::VERSION; // {1,4,0} +} +``` + +--- + +## Alternative: add_subdirectory + +If you include the source code directly as a sub-repository, simply do: + +```cmake +add_subdirectory(externals/cpp-core) +# the same version variables can be set before the call +``` + +--- + +## Using the package with `find_package` + +After running `cmake --install` (or `make install`) you can locate the package system-wide: + +```cmake +find_package(cpp_core REQUIRED) +add_executable(my_app src/main.cpp) +target_link_libraries(my_app PRIVATE cpp_core::cpp_core) +``` + +--- + +## License +Apache-2.0 – see [LICENSE](LICENSE). From 3f6cf0780e71626fc42db55483c31644716f72ec Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 13:21:15 +0200 Subject: [PATCH 03/45] Update README.md to change the GitHub repository reference for cpp-core --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 092b5a4..2a2177c 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ set(CPP_LINUX_VERSION_PATCH 0) CPMAddPackage( NAME cpp_core - GITHUB_REPOSITORY /cpp-core # Fork / upstream repo + GITHUB_REPOSITORY Serial-IO/cpp-core # Fork / upstream repo GIT_TAG main # or a release tag like v0.1.0 OPTIONS "CPP_CORE_VERSION_MAJOR=${CPP_LINUX_VERSION_MAJOR}" From 0285f3cb10c633556f32bf5897bf807b0266ed72 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 13:37:07 +0200 Subject: [PATCH 04/45] Add namespace cpp_core to StatusCodes enum in status_codes.h --- include/cpp_core/status_codes.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/include/cpp_core/status_codes.h b/include/cpp_core/status_codes.h index a48b8c8..3619f2f 100644 --- a/include/cpp_core/status_codes.h +++ b/include/cpp_core/status_codes.h @@ -1,5 +1,7 @@ #pragma once +namespace cpp_core +{ enum class StatusCodes { SUCCESS = 0, @@ -17,3 +19,4 @@ enum class StatusCodes ABORT_READ_ERROR = -12, ABORT_WRITE_ERROR = -13, }; +} // namespace cpp_core From 0effc9c357d37c5b35d8d88b6781f189a2b3c5a9 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 16:19:09 +0200 Subject: [PATCH 05/45] Refactor cpp_core namespace and update getVersion function to inline definition for header-only usage --- include/cpp_core/helpers.h | 5 ++++- include/cpp_core/serial.h | 9 ++++++++- include/cpp_core/version.h.in | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/include/cpp_core/helpers.h b/include/cpp_core/helpers.h index e367b92..d3b8cbc 100644 --- a/include/cpp_core/helpers.h +++ b/include/cpp_core/helpers.h @@ -1,3 +1,6 @@ #pragma once -namespace cpp_core {} // namespace cpp_core +namespace cpp_core +{ + +} // namespace cpp_core diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 0379864..1bf6e13 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -18,7 +18,14 @@ extern "C" { #endif - MODULE_API void getVersion(cpp_core::Version* out); + // Inline definition to keep the library header-only + inline MODULE_API void getVersion(cpp_core::Version* out) + { + if (out != nullptr) + { + *out = cpp_core::VERSION; + } + } // Basic serial API MODULE_API intptr_t diff --git a/include/cpp_core/version.h.in b/include/cpp_core/version.h.in index 5bdfa42..b02de82 100644 --- a/include/cpp_core/version.h.in +++ b/include/cpp_core/version.h.in @@ -12,6 +12,6 @@ struct Version // Generated at configure time. Parent project can override the numbers via // -DCPP_CORE_VERSION_XXX=... or CPM OPTIONS -constexpr Version VERSION{@CPP_CORE_VERSION_MAJOR@U, @CPP_CORE_VERSION_MINOR@U, @CPP_CORE_VERSION_PATCH@U}; +inline constexpr Version VERSION{@CPP_CORE_VERSION_MAJOR@U, @CPP_CORE_VERSION_MINOR@U, @CPP_CORE_VERSION_PATCH@U}; } // namespace cpp_core From e5b00b47010b96aead8439c71b7428abbb2fe7b4 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Sun, 6 Jul 2025 18:34:51 +0200 Subject: [PATCH 06/45] Apply suggestion from @Mqxx Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2a2177c..4d4eed7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # cpp-core -Header-only C++ helper library that provides small, cross-platform utilities and a centrally maintained **Version** struct shared by the *cpp-linux-bindings* and *cpp-windows-bindings* repositories. +Header-only C++ helper library that provides small, cross-platform utilities and a centrally maintained **Version** struct shared by the *cpp-bindings-linux*, *cpp-bindings-windows* and *cpp-bindings-macos* repositories. * C++17, zero runtime dependencies * Delivered as an INTERFACE target `cpp_core::cpp_core` From 908be3e0b84ea072adf88c0167ec30b3c118cd94 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Sun, 6 Jul 2025 18:36:19 +0200 Subject: [PATCH 07/45] Apply suggestion from @Mqxx Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/serial.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 1bf6e13..3b4df6a 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -64,7 +64,7 @@ extern "C" MODULE_API void serialOnWrite(void (*func)(int bytes)); MODULE_API void serialOnError(void (*func)(int code, const char* message)); - MODULE_API int serialReadLine(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/); + MODULE_API int serialReadLine(int64_t handle, void* buffer, int bufferSize, int timeoutMs); MODULE_API int serialWriteLine(int64_t handle, const void* buffer, int bufferSize, int timeout /*ms*/); From 6f24fab0b080dc8cbaf9424fae8dc0ef674c99f3 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Sun, 6 Jul 2025 18:36:28 +0200 Subject: [PATCH 08/45] Apply suggestion from @Mqxx Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/serial.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 3b4df6a..f7c03a2 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -66,7 +66,7 @@ extern "C" MODULE_API int serialReadLine(int64_t handle, void* buffer, int bufferSize, int timeoutMs); - MODULE_API int serialWriteLine(int64_t handle, const void* buffer, int bufferSize, int timeout /*ms*/); + MODULE_API int serialWriteLine(int64_t handle, const void* buffer, int bufferSize, int timeoutMs); MODULE_API int serialReadUntilSequence(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/, void* sequence); From ff62ee21db9a2fefc35e311af181168450085ded Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Sun, 6 Jul 2025 18:36:39 +0200 Subject: [PATCH 09/45] Apply suggestion from @Mqxx Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/serial.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index f7c03a2..c82c4cd 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -68,7 +68,7 @@ extern "C" MODULE_API int serialWriteLine(int64_t handle, const void* buffer, int bufferSize, int timeoutMs); - MODULE_API int serialReadUntilSequence(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/, void* sequence); + MODULE_API int serialReadUntilSequence(int64_t handle, void* buffer, int bufferSize, int timeoutMs, void* sequence); MODULE_API int serialReadFrame(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/, char startByte, char endByte); From 61723f59a6f16e4b1490322f61148de251d6fd49 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Sun, 6 Jul 2025 18:36:47 +0200 Subject: [PATCH 10/45] Apply suggestion from @Mqxx Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/serial.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index c82c4cd..94ae551 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -70,7 +70,7 @@ extern "C" MODULE_API int serialReadUntilSequence(int64_t handle, void* buffer, int bufferSize, int timeoutMs, void* sequence); - MODULE_API int serialReadFrame(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/, char startByte, char endByte); + MODULE_API int serialReadFrame(int64_t handle, void* buffer, int bufferSize, int timeoutMs, char startByte, char endByte); // Byte statistics MODULE_API int64_t serialOutBytesTotal(int64_t handle); From c50b4767544895e5da8d1baef50758ba66aaf5b2 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 18:48:26 +0200 Subject: [PATCH 11/45] Update CMake configuration to generate version header in the binary directory and adjust include directories for cpp_core library --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2adf8d5..66c4e0e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,7 +21,7 @@ endif() # Generate version header at configure time configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/include/cpp_core/version.h.in - ${CMAKE_CURRENT_SOURCE_DIR}/include/cpp_core/version.h + ${CMAKE_CURRENT_BINARY_DIR}/generated/cpp_core/version.h @ONLY) # Header-only library -------------------------------------------------------- @@ -30,8 +30,8 @@ add_library(cpp_core::cpp_core ALIAS cpp_core) # Public include directories target_include_directories(cpp_core INTERFACE - $ $ + $ $) # Require C++17 From 6b33329404902d2b1cbe1fd9f419286b92ec591d Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 18:51:34 +0200 Subject: [PATCH 12/45] Update serial.h to conditionally include version header based on availability --- include/cpp_core/serial.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 94ae551..bf49307 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -1,6 +1,9 @@ #pragma once +#if __has_include() +#include +#else #include "version.h" - +#endif #include #if defined(_WIN32) || defined(__CYGWIN__) From cdf3eaca7b5ea6a42a417daa16aa355a26ccb2b8 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 19:08:34 +0200 Subject: [PATCH 13/45] Refactor CMake configuration to simplify version handling and update include paths for version header --- CMakeLists.txt | 22 ++++++---------------- include/cpp_core/serial.h | 5 +---- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 66c4e0e..33a346a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,20 +8,15 @@ project(cpp-core # --------------------------------------------------------------------------- # Version information - can be overridden by parent project # --------------------------------------------------------------------------- -if(NOT DEFINED CPP_CORE_VERSION_MAJOR) - set(CPP_CORE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) -endif() -if(NOT DEFINED CPP_CORE_VERSION_MINOR) - set(CPP_CORE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) -endif() -if(NOT DEFINED CPP_CORE_VERSION_PATCH) - set(CPP_CORE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) -endif() +foreach(_part IN ITEMS MAJOR MINOR PATCH) + if(NOT DEFINED CPP_CORE_VERSION_${_part} OR CPP_CORE_VERSION_${_part} STREQUAL "") + set(CPP_CORE_VERSION_${_part} ${PROJECT_VERSION_${_part}}) + endif() +endforeach() -# Generate version header at configure time configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/include/cpp_core/version.h.in - ${CMAKE_CURRENT_BINARY_DIR}/generated/cpp_core/version.h + ${CMAKE_CURRENT_SOURCE_DIR}/include/cpp_core/version.h @ONLY) # Header-only library -------------------------------------------------------- @@ -30,7 +25,6 @@ add_library(cpp_core::cpp_core ALIAS cpp_core) # Public include directories target_include_directories(cpp_core INTERFACE - $ $ $) @@ -46,10 +40,6 @@ install(TARGETS cpp_core install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) -# also install the generated version header -install(FILES ${CMAKE_CURRENT_BINARY_DIR}/generated/cpp_core/version.h - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/cpp_core) - # CMake package configuration ------------------------------------------------ include(CMakePackageConfigHelpers) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index bf49307..94ae551 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -1,9 +1,6 @@ #pragma once -#if __has_include() -#include -#else #include "version.h" -#endif + #include #if defined(_WIN32) || defined(__CYGWIN__) From e731cd27498c2a6eabfb4f568112a48d092869b6 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 19:16:47 +0200 Subject: [PATCH 14/45] Update README.md to clarify usage of cache variables for versioning in CPM.cmake integration --- README.md | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 4d4eed7..2f6769f 100644 --- a/README.md +++ b/README.md @@ -17,30 +17,31 @@ Header-only C++ helper library that provides small, cross-platform utilities and ## Quick Start -### 1. Add *cpp-core* with CPM.cmake +### 1. Add *cpp-core* with CPM.cmake (empfohlener Weg) ```cmake -# Your own project version -set(CPP_LINUX_VERSION_MAJOR 1) -set(CPP_LINUX_VERSION_MINOR 4) -set(CPP_LINUX_VERSION_PATCH 0) +# Projekt-Version einmal als **Cache-Variablen** setzen – +# so landen sie garantiert in cpp-core, egal wann CPM konfiguriert. +set(CPP_CORE_VERSION_MAJOR 1 CACHE STRING "") +set(CPP_CORE_VERSION_MINOR 0 CACHE STRING "") +set(CPP_CORE_VERSION_PATCH 3 CACHE STRING "") CPMAddPackage( NAME cpp_core - GITHUB_REPOSITORY Serial-IO/cpp-core # Fork / upstream repo - GIT_TAG main # or a release tag like v0.1.0 - OPTIONS - "CPP_CORE_VERSION_MAJOR=${CPP_LINUX_VERSION_MAJOR}" - "CPP_CORE_VERSION_MINOR=${CPP_LINUX_VERSION_MINOR}" - "CPP_CORE_VERSION_PATCH=${CPP_LINUX_VERSION_PATCH}" + GITHUB_REPOSITORY Serial-IO/cpp-core # Fork / Upstream + GIT_TAG main # oder z. B. v0.1.0 ) add_executable(my_app src/main.cpp) -# Link the header-only target – this only sets include paths / compile features target_link_libraries(my_app PRIVATE cpp_core::cpp_core) ``` -> Tip: If you already set the version variables as cache variables in your project (e.g. `set(CPP_CORE_VERSION_MAJOR 1 CACHE STRING "")`), you can omit the three `OPTIONS` entries—CPM will forward the values to *cpp-core* automatically. +> Warum Cache-Variablen? +> Nur so ist sicher­gestellt, dass die Werte bereits **vor** dem +> `CPMAddPackage()`-Aufruf existieren. Falls die Variablen erst später oder +> über `OPTIONS ... "CPP_CORE_VERSION_MAJOR=${FOO}"` gesetzt werden und `FOO` +> zu diesem Zeitpunkt leer ist, fällt *cpp-core* auf seine Default-Version +> (0.1.0) zurück. ### 2. Use in code From 6ee1837c25abca0282eeceb1a3996681f2066f61 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 23:19:56 +0200 Subject: [PATCH 15/45] Enhance documentation with FFI usage guides for Deno, add C API reference, and update README for clarity on library usage --- README.md | 29 +++++--- docs/api_reference.md | 68 ++++++++++++++++++ docs/deno_ffi.md | 159 ++++++++++++++++++++++++++++++++++++++++++ docs/index.md | 117 +++++++++++++++++++++++++++++++ 4 files changed, 363 insertions(+), 10 deletions(-) create mode 100644 docs/api_reference.md create mode 100644 docs/deno_ffi.md create mode 100644 docs/index.md diff --git a/README.md b/README.md index 2f6769f..5a55577 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,18 @@ Header-only C++ helper library that provides small, cross-platform utilities and a centrally maintained **Version** struct shared by the *cpp-bindings-linux*, *cpp-bindings-windows* and *cpp-bindings-macos* repositories. +> ⚠️ **Note for FFI users**: This repository contains **headers only**. +> To obtain a working native library (SO / DLL / dylib) build one of the platform-specific projects instead: +> • Windows → [cpp-bindings-windows](https://github.com/Serial-IO/cpp-bindings-windows) +> • Linux → [cpp-bindings-linux](https://github.com/Serial-IO/cpp-bindings-linux) +> These repositories compile *cpp-core* for you and provide the ready-to-use shared library. + +## Documentation + +* 📄 **[Overview](docs/overview.md)** – architecture, build & quick start. +* 📜 **[C API Reference](docs/api_reference.md)** – parameter-by-parameter reference of every exported function. +* ⚡ **[Deno FFI Guide](docs/deno_ffi.md)** – step-by-step instructions plus full TypeScript examples. + * C++17, zero runtime dependencies * Delivered as an INTERFACE target `cpp_core::cpp_core` * Fetchable via [CPM.cmake](https://github.com/cpm-cmake/CPM.cmake) or regular `find_package` @@ -17,11 +29,11 @@ Header-only C++ helper library that provides small, cross-platform utilities and ## Quick Start -### 1. Add *cpp-core* with CPM.cmake (empfohlener Weg) +### 1. Add *cpp-core* with CPM.cmake (recommended way) ```cmake -# Projekt-Version einmal als **Cache-Variablen** setzen – -# so landen sie garantiert in cpp-core, egal wann CPM konfiguriert. +# Set the project version once via **cache variables** – +# ensures the values end up in cpp-core regardless of when CPM configures. set(CPP_CORE_VERSION_MAJOR 1 CACHE STRING "") set(CPP_CORE_VERSION_MINOR 0 CACHE STRING "") set(CPP_CORE_VERSION_PATCH 3 CACHE STRING "") @@ -29,19 +41,16 @@ set(CPP_CORE_VERSION_PATCH 3 CACHE STRING "") CPMAddPackage( NAME cpp_core GITHUB_REPOSITORY Serial-IO/cpp-core # Fork / Upstream - GIT_TAG main # oder z. B. v0.1.0 + GIT_TAG main # or e.g. v0.1.0 ) add_executable(my_app src/main.cpp) target_link_libraries(my_app PRIVATE cpp_core::cpp_core) ``` -> Warum Cache-Variablen? -> Nur so ist sicher­gestellt, dass die Werte bereits **vor** dem -> `CPMAddPackage()`-Aufruf existieren. Falls die Variablen erst später oder -> über `OPTIONS ... "CPP_CORE_VERSION_MAJOR=${FOO}"` gesetzt werden und `FOO` -> zu diesem Zeitpunkt leer ist, fällt *cpp-core* auf seine Default-Version -> (0.1.0) zurück. +> Why cache variables? +> They guarantee the values exist **before** the `CPMAddPackage()` call. If the variables are set later (or via +> `OPTIONS ... "CPP_CORE_VERSION_MAJOR=${FOO}"`) and `FOO` is empty at that moment, *cpp-core* falls back to its default version (0.1.0). ### 2. Use in code diff --git a/docs/api_reference.md b/docs/api_reference.md new file mode 100644 index 0000000..c6e676b --- /dev/null +++ b/docs/api_reference.md @@ -0,0 +1,68 @@ +# C API Reference + +All functions are declared in `src/serial.h`. **Return values ≤ 0** indicate an error; the numeric code maps to `StatusCodes` (see bottom). + +--- + +## Connection + +| Function | Description | +|----------|-------------| +| `intptr_t serialOpen(void* port, int baud, int dataBits, int parity, int stopBits)` | Open a device (e.g. `"/dev/ttyUSB0\0"`) and receive an opaque handle. Parity: `0` = none, `1` = even, `2` = odd. Stop bits: `0` = 1 bit, `2` = 2 bits. | +| `void serialClose(int64_t handle)` | Restore original tty settings and close the file descriptor. | + +## Basic I/O + +| Function | Description | +|----------|-------------| +| `int serialRead(handle, buf, len, timeoutMs, multiplier)` | Read up to *len* bytes. Returns actual bytes read or `0` on timeout. | +| `int serialWrite(handle, buf, len, timeoutMs, multiplier)` | Write *len* bytes and return the number of bytes written. | +| `int serialReadUntil(handle, buf, len, timeoutMs, multiplier, untilCharPtr)` | Read until the delimiter byte (inclusive). | + +## Extended helpers + +| Function | Description | +|----------|-------------| +| `int serialReadLine(handle, buf, len, timeoutMs)` | Read until `\n`. | +| `int serialWriteLine(handle, buf, len, timeoutMs)` | Write buffer followed by `\n`. | +| `int serialReadUntilSequence(handle, buf, len, timeoutMs, seqPtr)` | Read until the UTF-8 sequence is encountered. | +| `int serialReadFrame(handle, buf, len, timeoutMs, startByte, endByte)` | Read a frame delimited by *startByte* / *endByte*. | + +## Statistics & Buffer control + +| Function | Description | +|----------|-------------| +| `int64_t serialInBytesTotal(handle)` / `serialOutBytesTotal(handle)` | Cumulative RX / TX counters. | +| `int serialInBytesWaiting(handle)` / `serialOutBytesWaiting(handle)` | Bytes currently queued in driver buffers. | +| `int serialDrain(handle)` | Block until OS transmit buffer is empty. | +| `void serialClearBufferIn/Out(handle)` | Flush RX / TX buffers. | +| `void serialAbortRead/Write(handle)` | Cancel in-flight I/O from another thread. | + +## Enumeration & Callbacks + +| Function | Description | +|----------|-------------| +| `int serialGetPortsInfo(cb)` | Call *cb* for every entry under `/dev/serial/by-id`. | +| `void serialOnError(cb)` | Register global error callback. | +| `void serialOnRead(cb)` / `serialOnWrite(cb)` | Called after each successful read/write. | + +--- + +## StatusCodes + +| Constant | Value | Meaning | +|----------|------:|---------| +| `SUCCESS` | 0 | No error | +| `CLOSE_HANDLE_ERROR` | -1 | Closing the device failed | +| `INVALID_HANDLE_ERROR` | -2 | Handle was null / invalid | +| `READ_ERROR` | -3 | `read()` syscall failed | +| `WRITE_ERROR` | -4 | `write()` syscall failed | +| `GET_STATE_ERROR` | -5 | Could not query tty state | +| `SET_STATE_ERROR` | -6 | Could not set tty state | +| `SET_TIMEOUT_ERROR` | -7 | Could not configure timeout | +| `BUFFER_ERROR` | -8 | Internal buffer issue | +| `NOT_FOUND_ERROR` | -9 | Resource not found (`/dev/serial/by-id`) | +| `CLEAR_BUFFER_IN_ERROR` | -10 | Flushing RX failed | +| `CLEAR_BUFFER_OUT_ERROR` | -11 | Flushing TX failed | +| `ABORT_READ_ERROR` | -12 | Abort flag could not be set | +| `ABORT_WRITE_ERROR` | -13 | Abort flag could not be set | diff --git a/docs/deno_ffi.md b/docs/deno_ffi.md new file mode 100644 index 0000000..c0740a0 --- /dev/null +++ b/docs/deno_ffi.md @@ -0,0 +1,159 @@ +# Using cpp-core from Deno via FFI + +This guide shows how to consume the **cpp-core** serial API from [Deno](https://deno.land) using the built-in FFI interface. The same principles apply to Node-FFI, Python ctypes and Rust `libloading`. + +> Make sure you have read the [library overview](overview.md) first. + +--- + +## Prerequisites + +1. **Deno ≥ 1.41** (older versions lack callback support) +2. A shared library built from **cpp-bindings-linux** / **cpp-bindings-windows** (these repos compile cpp-core for you) +3. Basic understanding of TypeScript and native pointers + +### Building the shared library + +```bash +# inside the cpp-bindings-linux (or cpp-bindings-windows) repository +cmake -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build --config Release + +# copy / rename so Deno can find it next to the script +cp build/libcpp_core.so ./libserial.so # Linux example +``` + +On Windows the file will be called `cpp_core.dll`, on macOS `libcpp_core.dylib`. + +--- + +## 1. Describe the symbols + +Create a file `serial.ts` next to your Deno script: + +```ts +// serial.ts – symbol table for Deno.dlopen +export const symbols = { + serialOpen: { + parameters: ["pointer", "i32", "i32", "i32", "i32"] as const, + result: "i64", + }, + serialClose: { parameters: ["i64"] as const, result: "void" }, + serialReadLine: { + parameters: ["i64", "pointer", "i32", "i32"] as const, + result: "i32", + }, + serialWriteLine: { + parameters: ["i64", "pointer", "i32", "i32"] as const, + result: "i32", + }, + // Optional callbacks (Deno ≥ 1.41) + serialOnError: { parameters: ["pointer"] as const, result: "void" }, +} as const; +``` + +--- + +## 2. Open the library + +```ts +import { symbols } from "./serial.ts"; + +const lib = Deno.dlopen("./libserial.so", symbols); +``` + +`lib.symbols` now exposes plain JavaScript functions that forward to C. + +--- + +## 3. Helpers for strings & buffers + +Most serial functions expect **C-style null-terminated strings** (aka `char*`). A simple utility makes the conversion easier: + +```ts +// cstr.ts +export function cstr(text: string) { + const buf = new TextEncoder().encode(text + "\0"); + return [buf, Deno.UnsafePointer.of(buf) as Deno.PointerValue] as const; +} +``` + +--- + +## 4. Complete echo example + +```ts +// echo.ts +import { symbols } from "./serial.ts"; +import { cstr } from "./cstr.ts"; + +const lib = Deno.dlopen("./libserial.so", symbols); + +// Open port +const [portBuf, portPtr] = cstr("/dev/ttyUSB0"); +const handle = lib.symbols.serialOpen(portPtr, 115200, 8, 0, 0); +if (handle <= 0n) throw new Error(`open failed: ${handle}`); + +// Send a line +const [msgBuf, msgPtr] = cstr("Hello from Deno!"); +lib.symbols.serialWriteLine(handle, msgPtr, msgBuf.length - 1, 1000); + +// Receive until newline (max 256 bytes) +const readBuf = new Uint8Array(256); +const bytes = lib.symbols.serialReadLine(handle, Deno.UnsafePointer.of(readBuf), readBuf.length, 1000); + +if (bytes > 0) { + console.log(new TextDecoder().decode(readBuf.subarray(0, bytes))); +} + +lib.symbols.serialClose(handle); +lib.close(); +``` + +Run it: + +```bash +deno run --allow-ffi --allow-read echo.ts +``` + +--- + +## 5. Registering callbacks + +Deno FFI supports **C→JS callbacks** through `Deno.UnsafeCallback`: + +```ts +// error_callback.ts +import { symbols } from "./serial.ts"; +const lib = Deno.dlopen("./libserial.so", symbols); + +const onError = new Deno.UnsafeCallback( + { parameters: ["i32", "pointer"], result: "void" } as const, + (code: number, msgPtr: Deno.PointerValue) => { + const msg = new Deno.UnsafePointerView(msgPtr).getCString(); + console.error(`serial error ${code}: ${msg}`); + }, +); + +lib.symbols.serialOnError(onError.pointer); +``` + +Remember to `onError.close()` and `lib.close()` when shutting down to free native resources. + +--- + +## 6. Troubleshooting + +| Symptom | Solution | +|---------|----------| +| `TypeError: ffi symbol not found` | Verify the exact exported name (no C++ mangling). Use `nm -D libserial.so` on Linux. | +| `BadResource: attempted to call a non-function` | The parameters array/order does **not** match the C prototype. | +| Timeouts (`READ_ERROR` −3) | Increase `timeoutMs` or ensure the device actually sends data. | + +--- + +## Links & further reading + +* Back to [Overview](overview.md) +* Full [C API reference](api_reference.md) +* Deno FFI docs: https://docs.deno.com/runtime/manual/runtime/ffi diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..f8de987 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,117 @@ +# cpp-core – Library Overview + +Welcome to **cpp-core**, a header-only, cross-platform C++17 helper library that bundles utilities frequently needed in systems programming and embedded scenarios. Besides multiple compile-time helpers it exposes a fully-featured **C API for serial communication**, making the library consumable from virtually any language (Rust, Python, Deno, …). + +> ⚠️ **Looking for a ready-to-use shared library?** Build one of the platform bindings instead of cpp-core itself: +> • Windows → [cpp-bindings-windows](https://github.com/Serial-IO/cpp-bindings-windows) +> • Linux → [cpp-bindings-linux](https://github.com/Serial-IO/cpp-bindings-linux) + +> Looking for the raw function list? See the [C API reference](api_reference.md). +> +> Want to call the library from TypeScript? Jump straight to the [Deno FFI guide](deno_ffi.md). + +--- + +## What ships with cpp-core? + +| Area | Header | Highlights | +|------|--------|------------| +| Versioning | `cpp_core/version.h` | Compile-time `constexpr` version struct, filled during the build. +| Helpers | `cpp_core/helpers.h` | Collection of lightweight, header-only helper templates. +| Serial I/O | `cpp_core/serial.h` | Cross-platform serial helper built on the POSIX/Win32 APIs (see [C API reference](api_reference.md)). +| Error Codes| `cpp_core/status_codes.h` | Unified negative error codes shared across languages and bindings. + +All headers live in the `include/` tree and are directly usable after installation. + +--- + +## Directory structure + +``` +cpp-core/ +├── cmake/ # CMake helper modules +├── docs/ # You are here 📚 +├── include/ +│ └── cpp_core/ # Public headers (header-only!) +└── test/ # Unit tests (if enabled) +``` + +--- + +## Building the library + +### 1. Fetch & configure + +```bash +# clone +$ git clone https://github.com/Serial-IO/cpp-core.git +$ cd cpp-core + +# create an out-of-tree build directory +$ cmake -B build -DCMAKE_BUILD_TYPE=Release +``` + +### 2. Build & install (header-only) + +```bash +$ cmake --build build --target install +``` + +`install` copies the headers (and *optionally* a shared library, see below) to your default prefix (`/usr/local`, `Program Files/`, …). + +### 3. Building a shared library for FFI consumers + +Deno, Python and other FFI users expect a shared library (`*.so`, `*.dll`, `*.dylib`). Enable it like so: + +```bash +# add the switch – all code remains header-only for C++ callers +$ cmake -B build-shared -DBUILD_SHARED_LIBS=ON -DCMAKE_BUILD_TYPE=Release +$ cmake --build build-shared --config Release + +# resulting artifact (Linux) +$ ls build-shared +libcpp_core.so # rename or copy as needed, e.g. to libserial.so +``` + +> **Tip**: keep the header files close to your FFI project so you can re-generate bindings easily. + +--- + +## Minimal C example + +```c +#include +#include + +int main() { + intptr_t h = serialOpen("/dev/ttyUSB0", 115200, 8, 0, 0); + if (h <= 0) { + fprintf(stderr, "open failed: %ld\n", (long)h); + return 1; + } + + const char msg[] = "hello\n"; + serialWriteLine(h, msg, sizeof msg - 1, 1000); + + char buf[64]; + int n = serialReadLine(h, buf, sizeof buf, 1000); + fwrite(buf, 1, n, stdout); + + serialClose(h); +} +``` + +For a deep dive into every parameter head over to the [C API reference](api_reference.md). + +--- + +## Going further + +* **Deno, Node, Python & Rust**: see the dedicated [Deno FFI guide](deno_ffi.md) which includes a complete TypeScript example and hints for other languages. +* **Questions / issues** – open a ticket on GitHub; contributions are welcome! + +--- + +## License + +cpp-core is licensed under the terms of the Apache-2.0 license. See [LICENSE](../LICENSE) for details. From b8e2ec55c4734e2ee6cf24a78a5d7f3c0675d317 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 23:27:27 +0200 Subject: [PATCH 16/45] Add comprehensive library overview documentation, including installation instructions, directory structure, and minimal C example --- docs/{index.md => overview.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename docs/{index.md => overview.md} (100%) diff --git a/docs/index.md b/docs/overview.md similarity index 100% rename from docs/index.md rename to docs/overview.md From 26a7b349c4f755e45b5e7f6c9adf41f85576e74e Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 23:38:59 +0200 Subject: [PATCH 17/45] Enhance C API reference documentation with detailed function descriptions, error handling examples, and improved organization of sections for better clarity and usability. --- docs/api_reference.md | 163 +++++++++++++++++++++++++++++------------- 1 file changed, 112 insertions(+), 51 deletions(-) diff --git a/docs/api_reference.md b/docs/api_reference.md index c6e676b..7ef8a2b 100644 --- a/docs/api_reference.md +++ b/docs/api_reference.md @@ -1,68 +1,129 @@ # C API Reference -All functions are declared in `src/serial.h`. **Return values ≤ 0** indicate an error; the numeric code maps to `StatusCodes` (see bottom). +**Scope** – Public interface of `libcpp_unix_bindings` (C-linkable). +*Linux fully supported · Windows fully supported* + +Every function is declared in `src/serial.h` and follows the same +convention: **positive / non-zero** ⇒ success, **≤ 0** ⇒ failure (maps to +`StatusCodes`). + +--- + +## 1 · Connection + +```c +intptr_t serialOpen(void* port, int baud, int dataBits, + int parity /*0-none·1-even·2-odd*/, + int stopBits /*0-1bit·2-2bit*/); + +void serialClose(int64_t handle); +``` + +*Linux*: `port` is a NULL-terminated path like `/dev/ttyUSB0` or +`/dev/tty.SLAB_USBtoUART`. +*Windows*: use `"COM3"`, `"\\.\\COM12"`, etc. (to be implemented). + +--- + +## 2 · Basic I/O + +```c +int serialRead (int64_t handle, void* buf, int len, int timeoutMs, int mult); +int serialWrite(int64_t handle, const void* buf, int len, int timeoutMs, int mult); + +int serialReadUntil(int64_t handle, void* buf, int len, + int timeoutMs, int mult, void* untilCharPtr); +``` + +*mult* is a polling multiplier (usually **1**). `serialReadUntil` stops **after** +the delimiter byte has been copied into *buf*. --- -## Connection +## 3 · Convenience helpers -| Function | Description | -|----------|-------------| -| `intptr_t serialOpen(void* port, int baud, int dataBits, int parity, int stopBits)` | Open a device (e.g. `"/dev/ttyUSB0\0"`) and receive an opaque handle. Parity: `0` = none, `1` = even, `2` = odd. Stop bits: `0` = 1 bit, `2` = 2 bits. | -| `void serialClose(int64_t handle)` | Restore original tty settings and close the file descriptor. | +```c +int serialReadLine (int64_t h, void* buf, int len, int timeoutMs); // until '\n' +int serialWriteLine(int64_t h, const void* buf, int len, int timeoutMs); // appends '\n' -## Basic I/O +int serialReadUntilSequence(int64_t h, void* buf, int len, + int timeoutMs, void* sequencePtr); -| Function | Description | -|----------|-------------| -| `int serialRead(handle, buf, len, timeoutMs, multiplier)` | Read up to *len* bytes. Returns actual bytes read or `0` on timeout. | -| `int serialWrite(handle, buf, len, timeoutMs, multiplier)` | Write *len* bytes and return the number of bytes written. | -| `int serialReadUntil(handle, buf, len, timeoutMs, multiplier, untilCharPtr)` | Read until the delimiter byte (inclusive). | +int serialReadFrame(int64_t h, void* buf, int len, int timeoutMs, + char startByte, char endByte); +``` -## Extended helpers +--- + +## 4 · Statistics & Buffer control -| Function | Description | -|----------|-------------| -| `int serialReadLine(handle, buf, len, timeoutMs)` | Read until `\n`. | -| `int serialWriteLine(handle, buf, len, timeoutMs)` | Write buffer followed by `\n`. | -| `int serialReadUntilSequence(handle, buf, len, timeoutMs, seqPtr)` | Read until the UTF-8 sequence is encountered. | -| `int serialReadFrame(handle, buf, len, timeoutMs, startByte, endByte)` | Read a frame delimited by *startByte* / *endByte*. | +```c +int64_t serialInBytesTotal (int64_t handle); // cumulative RX +int64_t serialOutBytesTotal(int64_t handle); // cumulative TX -## Statistics & Buffer control +int serialInBytesWaiting (int64_t handle); // queued in driver +int serialOutBytesWaiting(int64_t handle); -| Function | Description | -|----------|-------------| -| `int64_t serialInBytesTotal(handle)` / `serialOutBytesTotal(handle)` | Cumulative RX / TX counters. | -| `int serialInBytesWaiting(handle)` / `serialOutBytesWaiting(handle)` | Bytes currently queued in driver buffers. | -| `int serialDrain(handle)` | Block until OS transmit buffer is empty. | -| `void serialClearBufferIn/Out(handle)` | Flush RX / TX buffers. | -| `void serialAbortRead/Write(handle)` | Cancel in-flight I/O from another thread. | +int serialDrain(int64_t handle); // wait for TX empty -## Enumeration & Callbacks +void serialClearBufferIn (int64_t handle); +void serialClearBufferOut(int64_t handle); -| Function | Description | -|----------|-------------| -| `int serialGetPortsInfo(cb)` | Call *cb* for every entry under `/dev/serial/by-id`. | -| `void serialOnError(cb)` | Register global error callback. | -| `void serialOnRead(cb)` / `serialOnWrite(cb)` | Called after each successful read/write. | +void serialAbortRead (int64_t handle); +void serialAbortWrite(int64_t handle); +``` --- -## StatusCodes - -| Constant | Value | Meaning | -|----------|------:|---------| -| `SUCCESS` | 0 | No error | -| `CLOSE_HANDLE_ERROR` | -1 | Closing the device failed | -| `INVALID_HANDLE_ERROR` | -2 | Handle was null / invalid | -| `READ_ERROR` | -3 | `read()` syscall failed | -| `WRITE_ERROR` | -4 | `write()` syscall failed | -| `GET_STATE_ERROR` | -5 | Could not query tty state | -| `SET_STATE_ERROR` | -6 | Could not set tty state | -| `SET_TIMEOUT_ERROR` | -7 | Could not configure timeout | -| `BUFFER_ERROR` | -8 | Internal buffer issue | -| `NOT_FOUND_ERROR` | -9 | Resource not found (`/dev/serial/by-id`) | -| `CLEAR_BUFFER_IN_ERROR` | -10 | Flushing RX failed | -| `CLEAR_BUFFER_OUT_ERROR` | -11 | Flushing TX failed | -| `ABORT_READ_ERROR` | -12 | Abort flag could not be set | -| `ABORT_WRITE_ERROR` | -13 | Abort flag could not be set | +## 5 · Port enumeration & Callbacks + +```c +// Enumerate available ports. For each port the callback receives: +// portPath, aliasPath, manufacturer, serialNumber, pnpId, +// locationId, productId, vendorId +int serialGetPortsInfo(void (*cb)(const char*, const char*, const char*, + const char*, const char*, const char*, + const char*, const char*)); + +void serialOnError(void (*cb)(int code, const char* msg)); +void serialOnRead (void (*cb)(int bytes)); +void serialOnWrite(void (*cb)(int bytes)); +``` + +*Linux*: implementation scans `/dev/serial/by-id` if present, otherwise falls +back to common tty names. +*Windows*: will iterate over available COM ports. + +--- + +## 6 · StatusCodes + +```c++ +enum class StatusCodes : int { + SUCCESS = 0, + CLOSE_HANDLE_ERROR = -1, + INVALID_HANDLE_ERROR = -2, + READ_ERROR = -3, + WRITE_ERROR = -4, + GET_STATE_ERROR = -5, + SET_STATE_ERROR = -6, + SET_TIMEOUT_ERROR = -7, + BUFFER_ERROR = -8, + NOT_FOUND_ERROR = -9, + CLEAR_BUFFER_IN_ERROR = -10, + CLEAR_BUFFER_OUT_ERROR = -11, + ABORT_READ_ERROR = -12, + ABORT_WRITE_ERROR = -13 +}; +``` + +--- + +### Error-handling idiom + +```c +int rv = serialWrite(h, data, len, 500, 1); +if (rv <= 0) { + // handle error – detailed info via registered onError callback (if any) +} +``` From d7a1b3c8effe8551e8b60814ceb5e394c154d556 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Sun, 6 Jul 2025 23:40:00 +0200 Subject: [PATCH 18/45] Update C API reference documentation to include `libcpp_windows_bindings` in the public interface description for improved clarity. --- docs/api_reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api_reference.md b/docs/api_reference.md index 7ef8a2b..1a14da8 100644 --- a/docs/api_reference.md +++ b/docs/api_reference.md @@ -1,6 +1,6 @@ # C API Reference -**Scope** – Public interface of `libcpp_unix_bindings` (C-linkable). +**Scope** – Public interface of `libcpp_unix_bindings` / `libcpp_windows_bindings` (C-linkable). *Linux fully supported · Windows fully supported* Every function is declared in `src/serial.h` and follows the same From 1a68cab4dee8560abe29a0fe8a4236476265d7be Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Mon, 7 Jul 2025 07:33:44 +0200 Subject: [PATCH 19/45] Update .clang-format --- .clang-format | 174 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 159 insertions(+), 15 deletions(-) diff --git a/.clang-format b/.clang-format index 0b8c0be..ed08e49 100644 --- a/.clang-format +++ b/.clang-format @@ -1,17 +1,161 @@ -BasedOnStyle: LLVM -IndentWidth: 4 -ColumnLimit: 140 -TabWidth: 4 -UseTab: Never -BreakBeforeBraces: Allman -AllowShortFunctionsOnASingleLine: Empty -PointerAlignment: Left +--- +Language: Cpp +# BasedOnStyle: Microsoft +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortEnumsOnASingleLine: false +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: Always + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: false + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: true +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DeriveLineEnding: true DerivePointerAlignment: false +DisableFormat: false +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +StatementAttributeLikeMacros: + - Q_EMIT +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentCaseLabels: false +IndentCaseBlocks: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentExternBlock: AfterExternBlock +IndentRequires: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 1000 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Right +ReflowComments: true +SortIncludes: true +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements -SortIncludes: true -IncludeBlocks: Regroup -ReflowComments: true -ContinuationIndentWidth: 4 -BinPackParameters: false -BinPackArguments: false - \ No newline at end of file +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +BitFieldColonSpacing: Both +Standard: Latest +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME +... From 5edc9a0dc856162aadf6f288080a20115bccad83 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Mon, 7 Jul 2025 07:34:03 +0200 Subject: [PATCH 20/45] Update .clang-tidy --- .clang-tidy | 607 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 584 insertions(+), 23 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index c675794..6d8f532 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,30 +1,591 @@ -Checks: > - -*, - readability-* , - modernize-* , - -modernize-use-trailing-return-type, - -readability-magic-numbers, - -WarningsAsErrors: > - bugprone-* , - performance-* , - clang-analyzer-* - -HeaderFilterRegex: 'include/.*' -FormatStyle: file - +--- +Checks: '*, + -bugprone-easily-swappable-parameters, + -bugprone-lambda-function-name, + -readability-magic-numbers, + -hicpp-no-array-decay, + -hicpp-signed-bitwise, + -hicpp-vararg, + -misc-non-private-member-variables-in-classes, + -cppcoreguidelines-*, + -fuchsia-*, + -altera-*, + -android-*, + -llvmlibc-*, + -readability-convert-member-functions-to-static, + -boost-use-ranges, + -performance-enum-size' +WarningsAsErrors: '' +HeaderFilterRegex: '^(?!magic_enum).*$' +FormatStyle: Microsoft CheckOptions: + - key: readability-identifier-naming.ClassCase + value: CamelCase + - key: readability-identifier-naming.ClassMemberCase + value: lower_case + - key: readability-identifier-naming.ConstexprVariableCase + value: CamelCase + - key: readability-identifier-naming.ConstexprVariablePrefix + value: k + - key: readability-identifier-naming.EnumCase + value: CamelCase + - key: readability-identifier-naming.EnumConstantCase + value: CamelCase + - key: readability-identifier-naming.EnumConstantPrefix + value: k + - key: readability-identifier-naming.FunctionCase + value: camelBack + - key: readability-identifier-naming.FunctionIgnoredRegexp + value: '^BM_.*$' + - key: readability-identifier-naming.GlobalConstantCase + value: CamelCase + - key: readability-identifier-naming.GlobalConstantPrefix + value: k + - key: readability-identifier-naming.StaticConstantCase + value: CamelCase + - key: readability-identifier-naming.StaticConstantPrefix + value: k + - key: readability-identifier-naming.StaticVariableCase + value: lower_case + - key: readability-identifier-naming.MacroDefinitionCase + value: UPPER_CASE + - key: readability-identifier-naming.MacroDefinitionIgnoredRegexp + value: '^[A-Z]+(_[A-Z]+)*_$' + - key: readability-identifier-naming.MemberCase + value: lower_case + - key: readability-identifier-naming.PrivateMemberSuffix + value: _ + - key: readability-identifier-naming.PublicMemberSuffix + value: '' + - key: readability-identifier-naming.NamespaceCase + value: lower_case + - key: readability-identifier-naming.ParameterCase + value: lower_case + - key: readability-identifier-naming.TypeAliasCase + value: CamelCase + - key: readability-identifier-naming.TypedefCase + value: CamelCase + - key: readability-identifier-naming.VariableCase + value: lower_case + - key: readability-identifier-naming.IgnoreMainLikeFunctions + value: 'true' + - key: readability-identifier-naming.AggressiveDependentMemberLookup + value: 'false' + - key: readability-identifier-naming.IgnoreFailedSplit + value: 'false' + - key: abseil-string-find-startswith.AbseilStringsMatchHeader + value: 'absl/strings/match.h' + - key: abseil-string-find-startswith.IncludeStyle + value: llvm + - key: abseil-string-find-startswith.StringLikeClasses + value: '::std::basic_string' + - key: abseil-string-find-str-contains.AbseilStringsMatchHeader + value: 'absl/strings/match.h' + - key: abseil-string-find-str-contains.IncludeStyle + value: llvm + - key: abseil-string-find-str-contains.StringLikeClasses + value: '::std::basic_string;::std::basic_string_view;::absl::string_view' + - key: bugprone-argument-comment.CommentBoolLiterals + value: '0' + - key: bugprone-argument-comment.CommentCharacterLiterals + value: '0' + - key: bugprone-argument-comment.CommentFloatLiterals + value: '0' + - key: bugprone-argument-comment.CommentIntegerLiterals + value: '0' + - key: bugprone-argument-comment.CommentNullPtrs + value: '0' + - key: bugprone-argument-comment.CommentStringLiterals + value: '0' + - key: bugprone-argument-comment.CommentUserDefinedLiterals + value: '0' + - key: bugprone-argument-comment.IgnoreSingleArgument + value: '0' + - key: bugprone-argument-comment.StrictMode + value: '0' + - key: bugprone-assert-side-effect.AssertMacros + value: assert + - key: bugprone-assert-side-effect.CheckFunctionCalls + value: 'false' + - key: bugprone-dangling-handle.HandleClasses + value: 'std::basic_string_view;std::experimental::basic_string_view' + - key: bugprone-dynamic-static-initializers.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: bugprone-exception-escape.FunctionsThatShouldNotThrow + value: '' + - key: bugprone-exception-escape.IgnoredExceptions + value: '' + - key: bugprone-misplaced-widening-cast.CheckImplicitCasts + value: 'false' + - key: bugprone-narrowing-conversions.PedanticMode + value: 'false' + - key: bugprone-narrowing-conversions.WarnOnFloatingPointNarrowingConversion + value: 'true' + - key: bugprone-not-null-terminated-result.WantToUseSafeFunctions + value: 'true' + - key: bugprone-reserved-identifier.AggressiveDependentMemberLookup + value: 'false' + - key: bugprone-reserved-identifier.AllowedIdentifiers + value: '' + - key: bugprone-reserved-identifier.Invert + value: 'false' + - key: bugprone-signed-char-misuse.CharTypdefsToIgnore + value: '' + - key: bugprone-signed-char-misuse.DiagnoseSignedUnsignedCharComparisons + value: 'true' + - key: bugprone-sizeof-expression.WarnOnSizeOfCompareToConstant + value: 'true' + - key: bugprone-sizeof-expression.WarnOnSizeOfConstant + value: 'true' + - key: bugprone-sizeof-expression.WarnOnSizeOfIntegerExpression + value: 'false' + - key: bugprone-sizeof-expression.WarnOnSizeOfThis + value: 'true' + - key: bugprone-string-constructor.LargeLengthThreshold + value: '8388608' + - key: bugprone-string-constructor.WarnOnLargeLength + value: 'true' + - key: bugprone-suspicious-enum-usage.StrictMode + value: 'false' + - key: bugprone-suspicious-include.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: bugprone-suspicious-include.ImplementationFileExtensions + value: 'c;cc;cpp;cxx' + - key: bugprone-suspicious-missing-comma.MaxConcatenatedTokens + value: '5' + - key: bugprone-suspicious-missing-comma.RatioThreshold + value: '0.200000' + - key: bugprone-suspicious-missing-comma.SizeThreshold + value: '5' + - key: bugprone-suspicious-string-compare.StringCompareLikeFunctions + value: '' + - key: bugprone-suspicious-string-compare.WarnOnImplicitComparison + value: 'true' + - key: bugprone-suspicious-string-compare.WarnOnLogicalNotComparison + value: 'false' + - key: bugprone-too-small-loop-variable.MagnitudeBitsUpperLimit + value: '16' + - key: bugprone-unhandled-self-assignment.WarnOnlyIfThisHasSuspiciousField + value: 'true' + - key: bugprone-unused-return-value.CheckedFunctions + value: '::std::async;::std::launder;::std::remove;::std::remove_if;::std::unique;::std::unique_ptr::release;::std::basic_string::empty;::std::vector::empty;::std::back_inserter;::std::distance;::std::find;::std::find_if;::std::inserter;::std::lower_bound;::std::make_pair;::std::map::count;::std::map::find;::std::map::lower_bound;::std::multimap::equal_range;::std::multimap::upper_bound;::std::set::count;::std::set::find;::std::setfill;::std::setprecision;::std::setw;::std::upper_bound;::std::vector::at;::bsearch;::ferror;::feof;::isalnum;::isalpha;::isblank;::iscntrl;::isdigit;::isgraph;::islower;::isprint;::ispunct;::isspace;::isupper;::iswalnum;::iswprint;::iswspace;::isxdigit;::memchr;::memcmp;::strcmp;::strcoll;::strncmp;::strpbrk;::strrchr;::strspn;::strstr;::wcscmp;::access;::bind;::connect;::difftime;::dlsym;::fnmatch;::getaddrinfo;::getopt;::htonl;::htons;::iconv_open;::inet_addr;::isascii;::isatty;::mmap;::newlocale;::openat;::pathconf;::pthread_equal;::pthread_getspecific;::pthread_mutex_trylock;::readdir;::readlink;::recvmsg;::regexec;::scandir;::semget;::setjmp;::shm_open;::shmget;::sigismember;::strcasecmp;::strsignal;::ttyname' + - key: cert-dcl16-c.IgnoreMacros + value: 'true' + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: cert-dcl37-c.AggressiveDependentMemberLookup + value: 'false' + - key: cert-dcl37-c.AllowedIdentifiers + value: '' + - key: cert-dcl37-c.Invert + value: 'false' + - key: cert-dcl51-cpp.AggressiveDependentMemberLookup + value: 'false' + - key: cert-dcl51-cpp.AllowedIdentifiers + value: '' + - key: cert-dcl51-cpp.Invert + value: 'false' + - key: cert-dcl59-cpp.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: cert-err09-cpp.CheckThrowTemporaries + value: 'true' + - key: cert-err09-cpp.MaxSize + value: '-1' + - key: cert-err09-cpp.WarnOnLargeObjects + value: 'false' + - key: cert-err61-cpp.CheckThrowTemporaries + value: 'true' + - key: cert-err61-cpp.MaxSize + value: '-1' + - key: cert-err61-cpp.WarnOnLargeObjects + value: 'false' + - key: cert-msc32-c.DisallowedSeedTypes + value: 'time_t,std::time_t' + - key: cert-msc51-cpp.DisallowedSeedTypes + value: 'time_t,std::time_t' + - key: cert-oop11-cpp.IncludeStyle + value: llvm + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: 'false' + - key: cert-oop57-cpp.MemCmpNames + value: '' + - key: cert-oop57-cpp.MemCpyNames + value: '' + - key: cert-oop57-cpp.MemSetNames + value: '' + - key: cert-str34-c.CharTypdefsToIgnore + value: '' + - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons + value: 'false' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoreAllFloatingPointValues + value: 'false' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoreBitFieldsWidths + value: 'true' + - key: cppcoreguidelines-avoid-magic-numbers.IgnorePowersOf2IntegerValues + value: 'false' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: cppcoreguidelines-explicit-virtual-functions.AllowOverrideAndFinal + value: 'false' + - key: cppcoreguidelines-explicit-virtual-functions.FinalSpelling + value: final + - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors + value: 'true' + - key: cppcoreguidelines-explicit-virtual-functions.OverrideSpelling + value: override + - key: cppcoreguidelines-init-variables.IncludeStyle + value: llvm + - key: cppcoreguidelines-init-variables.MathHeader + value: math.h + - key: cppcoreguidelines-macro-usage.AllowedRegexp + value: '^DEBUG_*' + - key: cppcoreguidelines-macro-usage.CheckCapsOnly + value: 'false' + - key: cppcoreguidelines-macro-usage.IgnoreCommandLineMacros + value: 'true' + - key: cppcoreguidelines-narrowing-conversions.PedanticMode + value: 'false' + - key: cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion + value: 'true' + - key: cppcoreguidelines-no-malloc.Allocations + value: '::malloc;::calloc' + - key: cppcoreguidelines-no-malloc.Deallocations + value: '::free' + - key: cppcoreguidelines-no-malloc.Reallocations + value: '::realloc' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: 'true' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnorePublicMemberVariables + value: 'false' + - key: cppcoreguidelines-owning-memory.LegacyResourceConsumers + value: '::free;::realloc;::freopen;::fclose' + - key: cppcoreguidelines-owning-memory.LegacyResourceProducers + value: '::malloc;::aligned_alloc;::realloc;::calloc;::fopen;::freopen;::tmpfile' + - key: cppcoreguidelines-pro-bounds-constant-array-index.GslHeader + value: '' + - key: cppcoreguidelines-pro-bounds-constant-array-index.IncludeStyle + value: llvm + - key: cppcoreguidelines-pro-type-member-init.IgnoreArrays + value: 'false' + - key: cppcoreguidelines-pro-type-member-init.UseAssignment + value: 'false' + - key: cppcoreguidelines-special-member-functions.AllowMissingMoveFunctions + value: 'false' + - key: cppcoreguidelines-special-member-functions.AllowMissingMoveFunctionsWhenCopyIsDeleted + value: 'false' + - key: cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor + value: 'false' + - key: google-build-namespaces.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: google-global-names-in-headers.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: google-readability-function-size.BranchThreshold + value: '4294967295' + - key: google-readability-function-size.LineThreshold + value: '4294967295' + - key: google-readability-function-size.NestingThreshold + value: '4294967295' + - key: google-readability-function-size.ParameterThreshold + value: '4294967295' + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: google-readability-function-size.VariableThreshold + value: '4294967295' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: google-runtime-int.SignedTypePrefix + value: int + - key: google-runtime-int.TypeSuffix + value: '' + - key: google-runtime-int.UnsignedTypePrefix + value: uint + - key: google-runtime-references.IncludedTypes + value: '' + - key: hicpp-braces-around-statements.ShortStatementLines + value: '0' + - key: hicpp-function-size.BranchThreshold + value: '4294967295' + - key: hicpp-function-size.LineThreshold + value: '4294967295' + - key: hicpp-function-size.NestingThreshold + value: '4294967295' + - key: hicpp-function-size.ParameterThreshold + value: '4294967295' + - key: hicpp-function-size.StatementThreshold + value: '800' + - key: hicpp-function-size.VariableThreshold + value: '4294967295' + - key: hicpp-member-init.IgnoreArrays + value: 'false' + - key: hicpp-member-init.UseAssignment + value: 'false' + - key: hicpp-move-const-arg.CheckTriviallyCopyableMove + value: 'true' + - key: hicpp-multiway-paths-covered.WarnOnMissingElse + value: 'false' + - key: hicpp-no-malloc.Allocations + value: '::malloc;::calloc' + - key: hicpp-no-malloc.Deallocations + value: '::free' + - key: hicpp-no-malloc.Reallocations + value: '::realloc' + - key: hicpp-signed-bitwise.IgnorePositiveIntegerLiterals + value: 'false' + - key: hicpp-special-member-functions.AllowMissingMoveFunctions + value: 'false' + - key: hicpp-special-member-functions.AllowMissingMoveFunctionsWhenCopyIsDeleted + value: 'false' + - key: hicpp-special-member-functions.AllowSoleDefaultDtor + value: 'false' + - key: hicpp-uppercase-literal-suffix.IgnoreMacros + value: 'true' + - key: hicpp-uppercase-literal-suffix.NewSuffixes + value: '' + - key: hicpp-use-auto.MinTypeNameLength + value: '5' + - key: hicpp-use-auto.RemoveStars + value: 'false' + - key: hicpp-use-emplace.ContainersWithPushBack + value: '::std::vector;::std::list;::std::deque' + - key: hicpp-use-emplace.IgnoreImplicitConstructors + value: 'false' + - key: hicpp-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' + - key: hicpp-use-emplace.TupleMakeFunctions + value: '::std::make_pair;::std::make_tuple' + - key: hicpp-use-emplace.TupleTypes + value: '::std::pair;::std::tuple' + - key: hicpp-use-equals-default.IgnoreMacros + value: 'true' + - key: hicpp-use-equals-delete.IgnoreMacros + value: 'true' + - key: hicpp-use-noexcept.ReplacementString + value: '' + - key: hicpp-use-noexcept.UseNoexceptFalse + value: 'true' + - key: hicpp-use-nullptr.NullMacros + value: '' + - key: hicpp-use-override.AllowOverrideAndFinal + value: 'false' + - key: hicpp-use-override.FinalSpelling + value: final + - key: hicpp-use-override.IgnoreDestructors + value: 'false' + - key: hicpp-use-override.OverrideSpelling + value: override + - key: llvm-else-after-return.WarnOnConditionVariables + value: 'false' + - key: llvm-else-after-return.WarnOnUnfixable + value: 'false' + - key: llvm-header-guard.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: llvm-namespace-comment.ShortNamespaceLines + value: '1' + - key: llvm-namespace-comment.SpacesBeforeComments + value: '1' + - key: llvm-qualified-auto.AddConstToQualified + value: 'false' + - key: misc-definitions-in-headers.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: misc-definitions-in-headers.UseHeaderFileExtension + value: 'true' + - key: misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: 'false' + - key: misc-non-private-member-variables-in-classes.IgnorePublicMemberVariables + value: 'false' + - key: misc-throw-by-value-catch-by-reference.CheckThrowTemporaries + value: 'true' + - key: misc-throw-by-value-catch-by-reference.MaxSize + value: '-1' + - key: misc-throw-by-value-catch-by-reference.WarnOnLargeObjects + value: 'false' + - key: misc-unused-parameters.StrictMode + value: 'false' + - key: modernize-avoid-bind.PermissiveParameterList + value: 'false' + - key: modernize-loop-convert.MaxCopySize + value: '16' + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: modernize-loop-convert.NamingStyle + value: CamelCase + - key: modernize-make-shared.IgnoreMacros + value: 'true' + - key: modernize-make-shared.IncludeStyle + value: llvm + - key: modernize-make-shared.MakeSmartPtrFunction + value: 'std::make_shared' + - key: modernize-make-shared.MakeSmartPtrFunctionHeader + value: memory + - key: modernize-make-unique.IgnoreMacros + value: 'true' + - key: modernize-make-unique.IncludeStyle + value: llvm + - key: modernize-make-unique.MakeSmartPtrFunction + value: 'std::make_unique' + - key: modernize-make-unique.MakeSmartPtrFunctionHeader + value: memory + - key: modernize-pass-by-value.IncludeStyle + value: llvm + - key: modernize-pass-by-value.ValuesOnly + value: 'false' + - key: modernize-raw-string-literal.DelimiterStem + value: lit + - key: modernize-raw-string-literal.ReplaceShorterLiterals + value: 'false' + - key: modernize-replace-auto-ptr.IncludeStyle + value: llvm + - key: modernize-replace-disallow-copy-and-assign-macro.MacroName + value: DISALLOW_COPY_AND_ASSIGN + - key: modernize-replace-random-shuffle.IncludeStyle + value: llvm - key: modernize-use-auto.MinTypeNameLength value: '5' - key: modernize-use-auto.RemoveStars value: 'false' - - key: readability-identifier-naming.VariableCase - value: lower_case - - key: readability-identifier-naming.MemberCase - value: lower_case - - key: readability-identifier-naming.PrivateMemberPrefix - value: '_' - - key: readability-function-size.ParameterThreshold - value: '8' + - key: modernize-use-bool-literals.IgnoreMacros + value: 'true' + - key: modernize-use-default-member-init.IgnoreMacros + value: 'true' + - key: modernize-use-default-member-init.UseAssignment + value: 'false' + - key: modernize-use-emplace.ContainersWithPushBack + value: '::std::vector;::std::list;::std::deque' + - key: modernize-use-emplace.IgnoreImplicitConstructors + value: 'false' + - key: modernize-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' + - key: modernize-use-emplace.TupleMakeFunctions + value: '::std::make_pair;::std::make_tuple' + - key: modernize-use-emplace.TupleTypes + value: '::std::pair;::std::tuple' + - key: modernize-use-equals-default.IgnoreMacros + value: 'true' + - key: modernize-use-equals-delete.IgnoreMacros + value: 'true' + - key: modernize-use-nodiscard.ReplacementString + value: '[[nodiscard]]' + - key: modernize-use-noexcept.ReplacementString + value: '' + - key: modernize-use-noexcept.UseNoexceptFalse + value: 'true' + - key: modernize-use-nullptr.NullMacros + value: 'NULL' + - key: modernize-use-override.AllowOverrideAndFinal + value: 'false' + - key: modernize-use-override.FinalSpelling + value: final + - key: modernize-use-override.IgnoreDestructors + value: 'false' + - key: modernize-use-override.OverrideSpelling + value: override + - key: modernize-use-transparent-functors.SafeMode + value: 'false' + - key: modernize-use-using.IgnoreMacros + value: 'true' + - key: objc-forbidden-subclassing.ForbiddenSuperClassNames + value: 'ABNewPersonViewController;ABPeoplePickerNavigationController;ABPersonViewController;ABUnknownPersonViewController;NSHashTable;NSMapTable;NSPointerArray;NSPointerFunctions;NSTimer;UIActionSheet;UIAlertView;UIImagePickerController;UITextInputMode;UIWebView' + - key: openmp-exception-escape.IgnoredExceptions + value: '' + - key: performance-faster-string-find.StringLikeClasses + value: '::std::basic_string;::std::basic_string_view' + - key: performance-for-range-copy.AllowedTypes + value: '' + - key: performance-for-range-copy.WarnOnAllAutoCopies + value: 'false' + - key: performance-inefficient-string-concatenation.StrictMode + value: 'false' + - key: performance-inefficient-vector-operation.EnableProto + value: 'false' + - key: performance-inefficient-vector-operation.VectorLikeClasses + value: '::std::vector' + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: 'true' + - key: performance-move-constructor-init.IncludeStyle + value: llvm + - key: performance-no-automatic-move.AllowedTypes + value: '' + - key: performance-type-promotion-in-math-fn.IncludeStyle + value: llvm + - key: performance-unnecessary-copy-initialization.AllowedTypes + value: '' + - key: performance-unnecessary-value-param.AllowedTypes + value: '' + - key: performance-unnecessary-value-param.IncludeStyle + value: llvm + - key: portability-restrict-system-includes.Includes + value: '*' + - key: portability-simd-intrinsics.Std + value: '' + - key: portability-simd-intrinsics.Suggest + value: '0' - key: readability-braces-around-statements.ShortStatementLines value: '0' + - key: readability-else-after-return.WarnOnConditionVariables + value: 'true' + - key: readability-else-after-return.WarnOnUnfixable + value: 'true' + - key: readability-function-size.BranchThreshold + value: '4294967295' + - key: readability-function-size.LineThreshold + value: '4294967295' + - key: readability-function-size.NestingThreshold + value: '4294967295' + - key: readability-function-size.ParameterThreshold + value: '4294967295' + - key: readability-function-size.StatementThreshold + value: '800' + - key: readability-function-size.VariableThreshold + value: '4294967295' + - key: readability-implicit-bool-conversion.AllowIntegerConditions + value: 'false' + - key: readability-implicit-bool-conversion.AllowPointerConditions + value: 'false' + - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros + value: 'true' + - key: readability-inconsistent-declaration-parameter-name.Strict + value: 'false' + - key: readability-magic-numbers.IgnoreAllFloatingPointValues + value: 'false' + - key: readability-magic-numbers.IgnoreBitFieldsWidths + value: 'true' + - key: readability-magic-numbers.IgnorePowersOf2IntegerValues + value: 'false' + - key: readability-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: readability-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: readability-qualified-auto.AddConstToQualified + value: 'true' + - key: readability-redundant-declaration.IgnoreMacros + value: 'true' + - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors + value: 'false' + - key: readability-redundant-smartptr-get.IgnoreMacros + value: 'true' + - key: readability-redundant-string-init.StringNames + value: '::std::basic_string' + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: 'false' + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: 'false' + - key: readability-simplify-subscript-expr.Types + value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' + - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold + value: '3' + - key: readability-uppercase-literal-suffix.IgnoreMacros + value: 'true' + - key: readability-uppercase-literal-suffix.NewSuffixes + value: '' + - key: zircon-temporary-objects.Names + value: '' +# allow x,y,z single letter names, to be used for coordinates + - key: readability-identifier-length.IgnoredVariableNames + value: '^[xyz]|m0|m1|_$' +... From cf65b19c89bf711c624feba2b872ce54f773a608 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Mon, 7 Jul 2025 18:10:21 +0200 Subject: [PATCH 21/45] Refactor serial API in header files for consistency and clarity; update status codes to use camel case naming convention and adjust clang-tidy checks for improved code quality. --- .clang-tidy | 2 ++ include/cpp_core/serial.h | 60 ++++++++++++++++----------------- include/cpp_core/status_codes.h | 28 +++++++-------- include/cpp_core/version.h.in | 2 +- 4 files changed, 47 insertions(+), 45 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 6d8f532..3ddf761 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -14,6 +14,8 @@ Checks: '*, -llvmlibc-*, -readability-convert-member-functions-to-static, -boost-use-ranges, + -google-objc-function-naming, + -google-objc-global-variable-declaration, -performance-enum-size' WarningsAsErrors: '' HeaderFilterRegex: '^(?!magic_enum).*$' diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 94ae551..796c553 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -19,36 +19,34 @@ extern "C" #endif // Inline definition to keep the library header-only - inline MODULE_API void getVersion(cpp_core::Version* out) + inline MODULE_API void getVersion(cpp_core::Version *out) { if (out != nullptr) { - *out = cpp_core::VERSION; + *out = cpp_core::kVersion; } } // Basic serial API - MODULE_API intptr_t - serialOpen(void* port, int baudrate, int dataBits, int parity /*0-none,1-even,2-odd*/ = 0, int stopBits /*0-1bit,2-2bit*/ = 0); + MODULE_API auto serialOpen(void *port, int baudrate, int data_bits, int parity /*0-none,1-even,2-odd*/ = 0, + int stop_bits /*0-1bit,2-2bit*/ = 0) -> intptr_t; MODULE_API void serialClose(int64_t handle); - MODULE_API int serialRead(int64_t handle, void* buffer, int bufferSize, int timeout /*ms*/, int multiplier); + MODULE_API auto serialRead(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier) -> int; - MODULE_API int serialReadUntil(int64_t handle, void* buffer, int bufferSize, int timeout, int multiplier, void* untilChar); + MODULE_API auto serialReadUntil(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier, + void *until_char) -> int; - MODULE_API int serialWrite(int64_t handle, const void* buffer, int bufferSize, int timeout, int multiplier); + MODULE_API auto serialWrite(int64_t handle, const void *buffer, int buffer_size, int timeout_ms, int multiplier) + -> int; // Enumerate ports; callback gets simple COM name first (e.g. "COM3"), // followed by the full device path and further meta-data. - MODULE_API int serialGetPortsInfo(void (*function)(const char* port, - const char* path, - const char* manufacturer, - const char* serialNumber, - const char* pnpId, - const char* locationId, - const char* productId, - const char* vendorId)); + MODULE_API auto serialGetPortsInfo(void (*function)(const char *port, const char *path, const char *manufacturer, + const char *serial_number, const char *pnp_id, + const char *location_id, const char *product_id, + const char *vendor_id)) -> int; MODULE_API void serialClearBufferIn(int64_t handle); MODULE_API void serialClearBufferOut(int64_t handle); @@ -56,32 +54,34 @@ extern "C" MODULE_API void serialAbortWrite(int64_t handle); // Optional callback hooks (can be nullptr) - extern void (*on_read_callback)(int bytes); - extern void (*on_write_callback)(int bytes); - extern void (*on_error_callback)(int errorCode, const char* message); + extern void (*on_read_callback)(int bytes_read); + extern void (*on_write_callback)(int bytes_written); + extern void (*on_error_callback)(int error_code, const char *message); - MODULE_API void serialOnRead(void (*func)(int bytes)); - MODULE_API void serialOnWrite(void (*func)(int bytes)); - MODULE_API void serialOnError(void (*func)(int code, const char* message)); + MODULE_API void serialOnRead(void (*func)(int bytes_read)); + MODULE_API void serialOnWrite(void (*func)(int bytes_written)); + MODULE_API void serialOnError(void (*func)(int error_code, const char *message)); - MODULE_API int serialReadLine(int64_t handle, void* buffer, int bufferSize, int timeoutMs); + MODULE_API auto serialReadLine(int64_t handle, void *buffer, int buffer_size, int timeout_ms) -> int; - MODULE_API int serialWriteLine(int64_t handle, const void* buffer, int bufferSize, int timeoutMs); + MODULE_API auto serialWriteLine(int64_t handle, const void *buffer, int buffer_size, int timeout_ms) -> int; - MODULE_API int serialReadUntilSequence(int64_t handle, void* buffer, int bufferSize, int timeoutMs, void* sequence); + MODULE_API auto serialReadUntilSequence(int64_t handle, void *buffer, int buffer_size, int timeout_ms, + void *sequence) -> int; - MODULE_API int serialReadFrame(int64_t handle, void* buffer, int bufferSize, int timeoutMs, char startByte, char endByte); + MODULE_API auto serialReadFrame(int64_t handle, void *buffer, int buffer_size, int timeout_ms, char start_byte, + char end_byte) -> int; // Byte statistics - MODULE_API int64_t serialOutBytesTotal(int64_t handle); - MODULE_API int64_t serialInBytesTotal(int64_t handle); + MODULE_API auto serialOutBytesTotal(int64_t handle) -> int64_t; + MODULE_API auto serialInBytesTotal(int64_t handle) -> int64_t; // Drain pending TX bytes (wait until sent) - MODULE_API int serialDrain(int64_t handle); + MODULE_API auto serialDrain(int64_t handle) -> int; // Bytes currently queued in the driver buffers - MODULE_API int serialInBytesWaiting(int64_t handle); - MODULE_API int serialOutBytesWaiting(int64_t handle); + MODULE_API auto serialInBytesWaiting(int64_t handle) -> int; + MODULE_API auto serialOutBytesWaiting(int64_t handle) -> int; #ifdef __cplusplus } diff --git a/include/cpp_core/status_codes.h b/include/cpp_core/status_codes.h index 3619f2f..46c5bc3 100644 --- a/include/cpp_core/status_codes.h +++ b/include/cpp_core/status_codes.h @@ -4,19 +4,19 @@ namespace cpp_core { enum class StatusCodes { - SUCCESS = 0, - CLOSE_HANDLE_ERROR = -1, - INVALID_HANDLE_ERROR = -2, - READ_ERROR = -3, - WRITE_ERROR = -4, - GET_STATE_ERROR = -5, - SET_STATE_ERROR = -6, - SET_TIMEOUT_ERROR = -7, - BUFFER_ERROR = -8, - NOT_FOUND_ERROR = -9, - CLEAR_BUFFER_IN_ERROR = -10, - CLEAR_BUFFER_OUT_ERROR = -11, - ABORT_READ_ERROR = -12, - ABORT_WRITE_ERROR = -13, + kSuccess = 0, + kCloseHandleError = -1, + kInvalidHandleError = -2, + kReadError = -3, + kWriteError = -4, + kGetStateError = -5, + kSetStateError = -6, + kSetTimeoutError = -7, + kBufferError = -8, + kNotFoundError = -9, + kClearBufferInError = -10, + kClearBufferOutError = -11, + kAbortReadError = -12, + kAbortWriteError = -13, }; } // namespace cpp_core diff --git a/include/cpp_core/version.h.in b/include/cpp_core/version.h.in index b02de82..4b398fc 100644 --- a/include/cpp_core/version.h.in +++ b/include/cpp_core/version.h.in @@ -12,6 +12,6 @@ struct Version // Generated at configure time. Parent project can override the numbers via // -DCPP_CORE_VERSION_XXX=... or CPM OPTIONS -inline constexpr Version VERSION{@CPP_CORE_VERSION_MAJOR@U, @CPP_CORE_VERSION_MINOR@U, @CPP_CORE_VERSION_PATCH@U}; +inline constexpr Version kVersion{@CPP_CORE_VERSION_MAJOR@U, @CPP_CORE_VERSION_MINOR@U, @CPP_CORE_VERSION_PATCH@U}; } // namespace cpp_core From cc4426265be2fb083fb4531b92fc6fad6b6102c7 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Mon, 7 Jul 2025 18:20:32 +0200 Subject: [PATCH 22/45] Enhance serial API documentation in header file with detailed function descriptions, parameter explanations, and usage examples for improved clarity and usability. --- include/cpp_core/serial.h | 230 +++++++++++++++++++++++++++++++++++--- 1 file changed, 213 insertions(+), 17 deletions(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 796c553..434c190 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -17,8 +17,16 @@ extern "C" { #endif - - // Inline definition to keep the library header-only + /** + * @brief Retrieve the compile-time version number of the cpp_core library. + * + * Fills the provided Version structure with the current compile-time version + * of the library. If the pointer is nullptr the function returns immediately + * without performing any action. + * + * @param[out] out Pointer to a cpp_core::Version object that will receive the + * version information. + */ inline MODULE_API void getVersion(cpp_core::Version *out) { if (out != nullptr) @@ -27,60 +35,248 @@ extern "C" } } - // Basic serial API - MODULE_API auto serialOpen(void *port, int baudrate, int data_bits, int parity /*0-none,1-even,2-odd*/ = 0, - int stop_bits /*0-1bit,2-2bit*/ = 0) -> intptr_t; + /** + * @brief Open a serial port with the given parameters. + * + * @param port Platform-specific identifier of the serial port (e.g. + * "COM3" on Windows or "/dev/ttyUSB0" on POSIX systems). + * @param baudrate Desired baud rate in bits per second. + * @param data_bits Number of data bits (typically 5–8). + * @param parity Parity mode: 0 = none, 1 = even, 2 = odd. + * @param stop_bits Stop-bit configuration: 0 = 1 stop bit, 2 = 2 stop bits. + * @return Opaque handle to the opened port on success; a negative + * value indicates failure. + */ + MODULE_API auto serialOpen(void *port, int baudrate, int data_bits, int parity = 0, int stop_bits = 0) -> intptr_t; + /** + * @brief Close a previously opened serial port. + * + * @param handle Handle returned by serialOpen(). + */ MODULE_API void serialClose(int64_t handle); + /** + * @brief Read bytes from the serial port. + * + * Attempts to read up to @p buffer_size bytes into @p buffer. The call blocks + * for at most @p timeout_ms for the first byte and for @p timeout_ms * + * @p multiplier for subsequent bytes. + * + * @param handle Port handle returned by serialOpen(). + * @param buffer Destination buffer that will receive the data. + * @param buffer_size Size of @p buffer in bytes. + * @param timeout_ms Timeout for the first byte in milliseconds. + * @param multiplier Factor applied to the timeout for each additional byte. + * @return Number of bytes actually read, or a negative value on + * error. + */ MODULE_API auto serialRead(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier) -> int; + /** + * @brief Read bytes until a specific terminator character is encountered. + * + * Behaves like serialRead() but stops reading when the character pointed to by + * @p until_char is read (the terminator is included in the output). + * + * @param handle Port handle returned by serialOpen(). + * @param buffer Destination buffer. + * @param buffer_size Size of the destination buffer in bytes. + * @param timeout_ms Timeout for the first byte in milliseconds. + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @param until_char Pointer to the terminator character. + * @return Number of bytes read (including the terminator), or a + * negative value on error. + */ MODULE_API auto serialReadUntil(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier, void *until_char) -> int; + /** + * @brief Write raw bytes to the serial port. + * + * @param handle Port handle returned by serialOpen(). + * @param buffer Pointer to the data to transmit. + * @param buffer_size Number of bytes to send. + * @param timeout_ms Timeout for the first byte in milliseconds. + * @param multiplier Factor applied to the timeout for each additional byte. + * @return Number of bytes actually written, or a negative value on + * error. + */ MODULE_API auto serialWrite(int64_t handle, const void *buffer, int buffer_size, int timeout_ms, int multiplier) -> int; - // Enumerate ports; callback gets simple COM name first (e.g. "COM3"), - // followed by the full device path and further meta-data. + /** + * @brief Enumerate all available serial ports on the system. + * + * The supplied callback is invoked once for every discovered port and receives + * detailed information about the device. + * + * @param function Callback that is called for each port. The parameters are: + * - port: Short port name (e.g. "COM3"). + * - path: Full device path. + * - manufacturer: Manufacturer string (may be nullptr). + * - serial_number: Device serial number (may be nullptr). + * - pnp_id: Plug-and-play identifier (may be nullptr). + * - location_id: Device location (may be nullptr). + * - product_id: USB product ID string (may be nullptr). + * - vendor_id: USB vendor ID string (may be nullptr). + * @return Number of ports found; a negative value indicates error. + */ MODULE_API auto serialGetPortsInfo(void (*function)(const char *port, const char *path, const char *manufacturer, const char *serial_number, const char *pnp_id, const char *location_id, const char *product_id, const char *vendor_id)) -> int; + /** + * @brief Clear (flush) the device's input buffer. + * + * @param handle Port handle. + */ MODULE_API void serialClearBufferIn(int64_t handle); + + /** + * @brief Clear (flush) the device's output buffer. + * + * @param handle Port handle. + */ MODULE_API void serialClearBufferOut(int64_t handle); + + /** + * @brief Abort a blocking read operation running on another thread. + * + * @param handle Port handle. + */ MODULE_API void serialAbortRead(int64_t handle); + + /** + * @brief Abort a blocking write operation running on another thread. + * + * @param handle Port handle. + */ MODULE_API void serialAbortWrite(int64_t handle); - // Optional callback hooks (can be nullptr) - extern void (*on_read_callback)(int bytes_read); - extern void (*on_write_callback)(int bytes_written); - extern void (*on_error_callback)(int error_code, const char *message); + /** + * @brief Register a callback that is invoked whenever bytes are read. + * + * Passing nullptr disables the callback. + * + * @param callback Pointer to a function receiving the number of bytes that + * have been read. + */ + MODULE_API void serialSetReadCallback(void (*callback)(int bytes_read)); - MODULE_API void serialOnRead(void (*func)(int bytes_read)); - MODULE_API void serialOnWrite(void (*func)(int bytes_written)); - MODULE_API void serialOnError(void (*func)(int error_code, const char *message)); + /** + * @brief Register a callback that is invoked whenever bytes are written. + * + * Passing nullptr disables the callback. + * + * @param callback Pointer to a function receiving the number of bytes that + * have been written. + */ + MODULE_API void serialSetWriteCallback(void (*callback)(int bytes_written)); + /** + * @brief Register a callback that is invoked whenever an error occurs. + * + * Passing nullptr disables the callback. + * + * @param callback Pointer to a function receiving an error code and a + * textual description. + */ + MODULE_API void serialSetErrorCallback(void (*callback)(int error_code, const char *message)); + + /** + * @brief Read a line terminated by a newline character ("\n"). + * + * @param handle Port handle. + * @param buffer Destination buffer. + * @param buffer_size Size of the destination buffer in bytes. + * @param timeout_ms Maximum time to wait for the line in milliseconds. + * @return Number of bytes read (including the newline), or a + * negative value on error. + */ MODULE_API auto serialReadLine(int64_t handle, void *buffer, int buffer_size, int timeout_ms) -> int; + /** + * @brief Write a buffer followed by a newline character ("\n"). + * + * @param handle Port handle. + * @param buffer Data to transmit. + * @param buffer_size Number of bytes in @p buffer. + * @param timeout_ms Maximum time to wait for the transmission in + * milliseconds. + * @return Number of bytes actually written, or a negative value on + * error. + */ MODULE_API auto serialWriteLine(int64_t handle, const void *buffer, int buffer_size, int timeout_ms) -> int; + /** + * @brief Read until a specific byte sequence is encountered. + * + * @param handle Port handle. + * @param buffer Destination buffer. + * @param buffer_size Size of the destination buffer in bytes. + * @param timeout_ms Timeout for the first byte in milliseconds. + * @param sequence Pointer to the byte sequence that terminates the read. + * @return Number of bytes read (including the terminating + * sequence), or a negative value on error. + */ MODULE_API auto serialReadUntilSequence(int64_t handle, void *buffer, int buffer_size, int timeout_ms, void *sequence) -> int; + /** + * @brief Read a frame delimited by start and end bytes. + * + * @param handle Port handle. + * @param buffer Destination buffer. + * @param buffer_size Size of the destination buffer in bytes. + * @param timeout_ms Maximum time to wait for the frame in milliseconds. + * @param start_byte Byte that marks the beginning of the frame. + * @param end_byte Byte that marks the end of the frame. + * @return Number of bytes in the frame (including delimiters), or + * a negative value on error. + */ MODULE_API auto serialReadFrame(int64_t handle, void *buffer, int buffer_size, int timeout_ms, char start_byte, char end_byte) -> int; - // Byte statistics + /** + * @brief Total number of bytes transmitted since the port was opened. + * + * @param handle Port handle. + * @return Total number of bytes written. + */ MODULE_API auto serialOutBytesTotal(int64_t handle) -> int64_t; + + /** + * @brief Total number of bytes received since the port was opened. + * + * @param handle Port handle. + * @return Total number of bytes read. + */ MODULE_API auto serialInBytesTotal(int64_t handle) -> int64_t; - // Drain pending TX bytes (wait until sent) + /** + * @brief Block until all queued bytes have been transmitted. + * + * @param handle Port handle. + * @return 0 on success, negative value on error. + */ MODULE_API auto serialDrain(int64_t handle) -> int; - // Bytes currently queued in the driver buffers + /** + * @brief Number of bytes currently waiting in the driver's input buffer. + * + * @param handle Port handle. + * @return Number of bytes available for immediate reading. + */ MODULE_API auto serialInBytesWaiting(int64_t handle) -> int; + + /** + * @brief Number of bytes currently waiting in the driver's output buffer. + * + * @param handle Port handle. + * @return Number of bytes pending transmission. + */ MODULE_API auto serialOutBytesWaiting(int64_t handle) -> int; #ifdef __cplusplus From 769fd36bcdc15c8f1e5b40ba5e5a23dbc6fb67c6 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Tue, 8 Jul 2025 08:59:13 +0200 Subject: [PATCH 23/45] Update include/cpp_core/serial.h Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/serial.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 434c190..6df558d 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -186,7 +186,7 @@ extern "C" MODULE_API void serialSetErrorCallback(void (*callback)(int error_code, const char *message)); /** - * @brief Read a line terminated by a newline character ("\n"). + * @brief Read a line terminated by a newline character ("\n"). This function keeps reading until the newline character is found or the timeout is reached. * * @param handle Port handle. * @param buffer Destination buffer. From 557d9c2c96e9ba091d5f8f3e2e770e275769884e Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Tue, 8 Jul 2025 09:21:00 +0200 Subject: [PATCH 24/45] Delete docs/deno_ffi.md --- docs/deno_ffi.md | 159 ----------------------------------------------- 1 file changed, 159 deletions(-) delete mode 100644 docs/deno_ffi.md diff --git a/docs/deno_ffi.md b/docs/deno_ffi.md deleted file mode 100644 index c0740a0..0000000 --- a/docs/deno_ffi.md +++ /dev/null @@ -1,159 +0,0 @@ -# Using cpp-core from Deno via FFI - -This guide shows how to consume the **cpp-core** serial API from [Deno](https://deno.land) using the built-in FFI interface. The same principles apply to Node-FFI, Python ctypes and Rust `libloading`. - -> Make sure you have read the [library overview](overview.md) first. - ---- - -## Prerequisites - -1. **Deno ≥ 1.41** (older versions lack callback support) -2. A shared library built from **cpp-bindings-linux** / **cpp-bindings-windows** (these repos compile cpp-core for you) -3. Basic understanding of TypeScript and native pointers - -### Building the shared library - -```bash -# inside the cpp-bindings-linux (or cpp-bindings-windows) repository -cmake -B build -DCMAKE_BUILD_TYPE=Release -cmake --build build --config Release - -# copy / rename so Deno can find it next to the script -cp build/libcpp_core.so ./libserial.so # Linux example -``` - -On Windows the file will be called `cpp_core.dll`, on macOS `libcpp_core.dylib`. - ---- - -## 1. Describe the symbols - -Create a file `serial.ts` next to your Deno script: - -```ts -// serial.ts – symbol table for Deno.dlopen -export const symbols = { - serialOpen: { - parameters: ["pointer", "i32", "i32", "i32", "i32"] as const, - result: "i64", - }, - serialClose: { parameters: ["i64"] as const, result: "void" }, - serialReadLine: { - parameters: ["i64", "pointer", "i32", "i32"] as const, - result: "i32", - }, - serialWriteLine: { - parameters: ["i64", "pointer", "i32", "i32"] as const, - result: "i32", - }, - // Optional callbacks (Deno ≥ 1.41) - serialOnError: { parameters: ["pointer"] as const, result: "void" }, -} as const; -``` - ---- - -## 2. Open the library - -```ts -import { symbols } from "./serial.ts"; - -const lib = Deno.dlopen("./libserial.so", symbols); -``` - -`lib.symbols` now exposes plain JavaScript functions that forward to C. - ---- - -## 3. Helpers for strings & buffers - -Most serial functions expect **C-style null-terminated strings** (aka `char*`). A simple utility makes the conversion easier: - -```ts -// cstr.ts -export function cstr(text: string) { - const buf = new TextEncoder().encode(text + "\0"); - return [buf, Deno.UnsafePointer.of(buf) as Deno.PointerValue] as const; -} -``` - ---- - -## 4. Complete echo example - -```ts -// echo.ts -import { symbols } from "./serial.ts"; -import { cstr } from "./cstr.ts"; - -const lib = Deno.dlopen("./libserial.so", symbols); - -// Open port -const [portBuf, portPtr] = cstr("/dev/ttyUSB0"); -const handle = lib.symbols.serialOpen(portPtr, 115200, 8, 0, 0); -if (handle <= 0n) throw new Error(`open failed: ${handle}`); - -// Send a line -const [msgBuf, msgPtr] = cstr("Hello from Deno!"); -lib.symbols.serialWriteLine(handle, msgPtr, msgBuf.length - 1, 1000); - -// Receive until newline (max 256 bytes) -const readBuf = new Uint8Array(256); -const bytes = lib.symbols.serialReadLine(handle, Deno.UnsafePointer.of(readBuf), readBuf.length, 1000); - -if (bytes > 0) { - console.log(new TextDecoder().decode(readBuf.subarray(0, bytes))); -} - -lib.symbols.serialClose(handle); -lib.close(); -``` - -Run it: - -```bash -deno run --allow-ffi --allow-read echo.ts -``` - ---- - -## 5. Registering callbacks - -Deno FFI supports **C→JS callbacks** through `Deno.UnsafeCallback`: - -```ts -// error_callback.ts -import { symbols } from "./serial.ts"; -const lib = Deno.dlopen("./libserial.so", symbols); - -const onError = new Deno.UnsafeCallback( - { parameters: ["i32", "pointer"], result: "void" } as const, - (code: number, msgPtr: Deno.PointerValue) => { - const msg = new Deno.UnsafePointerView(msgPtr).getCString(); - console.error(`serial error ${code}: ${msg}`); - }, -); - -lib.symbols.serialOnError(onError.pointer); -``` - -Remember to `onError.close()` and `lib.close()` when shutting down to free native resources. - ---- - -## 6. Troubleshooting - -| Symptom | Solution | -|---------|----------| -| `TypeError: ffi symbol not found` | Verify the exact exported name (no C++ mangling). Use `nm -D libserial.so` on Linux. | -| `BadResource: attempted to call a non-function` | The parameters array/order does **not** match the C prototype. | -| Timeouts (`READ_ERROR` −3) | Increase `timeoutMs` or ensure the device actually sends data. | - ---- - -## Links & further reading - -* Back to [Overview](overview.md) -* Full [C API reference](api_reference.md) -* Deno FFI docs: https://docs.deno.com/runtime/manual/runtime/ffi From 6a01906d8434a402113668ad623f1a4d5f9c5a4c Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Tue, 8 Jul 2025 09:21:26 +0200 Subject: [PATCH 25/45] Apply suggestion from @Mqxx Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a55577..ef81d3c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# cpp-core +# C++ Core Header-only C++ helper library that provides small, cross-platform utilities and a centrally maintained **Version** struct shared by the *cpp-bindings-linux*, *cpp-bindings-windows* and *cpp-bindings-macos* repositories. From a4043ecbfef18966c9a0126446b2bf31f026f712 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Tue, 8 Jul 2025 09:21:42 +0200 Subject: [PATCH 26/45] Delete docs/api_reference.md --- docs/api_reference.md | 129 ------------------------------------------ 1 file changed, 129 deletions(-) delete mode 100644 docs/api_reference.md diff --git a/docs/api_reference.md b/docs/api_reference.md deleted file mode 100644 index 1a14da8..0000000 --- a/docs/api_reference.md +++ /dev/null @@ -1,129 +0,0 @@ -# C API Reference - -**Scope** – Public interface of `libcpp_unix_bindings` / `libcpp_windows_bindings` (C-linkable). -*Linux fully supported · Windows fully supported* - -Every function is declared in `src/serial.h` and follows the same -convention: **positive / non-zero** ⇒ success, **≤ 0** ⇒ failure (maps to -`StatusCodes`). - ---- - -## 1 · Connection - -```c -intptr_t serialOpen(void* port, int baud, int dataBits, - int parity /*0-none·1-even·2-odd*/, - int stopBits /*0-1bit·2-2bit*/); - -void serialClose(int64_t handle); -``` - -*Linux*: `port` is a NULL-terminated path like `/dev/ttyUSB0` or -`/dev/tty.SLAB_USBtoUART`. -*Windows*: use `"COM3"`, `"\\.\\COM12"`, etc. (to be implemented). - ---- - -## 2 · Basic I/O - -```c -int serialRead (int64_t handle, void* buf, int len, int timeoutMs, int mult); -int serialWrite(int64_t handle, const void* buf, int len, int timeoutMs, int mult); - -int serialReadUntil(int64_t handle, void* buf, int len, - int timeoutMs, int mult, void* untilCharPtr); -``` - -*mult* is a polling multiplier (usually **1**). `serialReadUntil` stops **after** -the delimiter byte has been copied into *buf*. - ---- - -## 3 · Convenience helpers - -```c -int serialReadLine (int64_t h, void* buf, int len, int timeoutMs); // until '\n' -int serialWriteLine(int64_t h, const void* buf, int len, int timeoutMs); // appends '\n' - -int serialReadUntilSequence(int64_t h, void* buf, int len, - int timeoutMs, void* sequencePtr); - -int serialReadFrame(int64_t h, void* buf, int len, int timeoutMs, - char startByte, char endByte); -``` - ---- - -## 4 · Statistics & Buffer control - -```c -int64_t serialInBytesTotal (int64_t handle); // cumulative RX -int64_t serialOutBytesTotal(int64_t handle); // cumulative TX - -int serialInBytesWaiting (int64_t handle); // queued in driver -int serialOutBytesWaiting(int64_t handle); - -int serialDrain(int64_t handle); // wait for TX empty - -void serialClearBufferIn (int64_t handle); -void serialClearBufferOut(int64_t handle); - -void serialAbortRead (int64_t handle); -void serialAbortWrite(int64_t handle); -``` - ---- - -## 5 · Port enumeration & Callbacks - -```c -// Enumerate available ports. For each port the callback receives: -// portPath, aliasPath, manufacturer, serialNumber, pnpId, -// locationId, productId, vendorId -int serialGetPortsInfo(void (*cb)(const char*, const char*, const char*, - const char*, const char*, const char*, - const char*, const char*)); - -void serialOnError(void (*cb)(int code, const char* msg)); -void serialOnRead (void (*cb)(int bytes)); -void serialOnWrite(void (*cb)(int bytes)); -``` - -*Linux*: implementation scans `/dev/serial/by-id` if present, otherwise falls -back to common tty names. -*Windows*: will iterate over available COM ports. - ---- - -## 6 · StatusCodes - -```c++ -enum class StatusCodes : int { - SUCCESS = 0, - CLOSE_HANDLE_ERROR = -1, - INVALID_HANDLE_ERROR = -2, - READ_ERROR = -3, - WRITE_ERROR = -4, - GET_STATE_ERROR = -5, - SET_STATE_ERROR = -6, - SET_TIMEOUT_ERROR = -7, - BUFFER_ERROR = -8, - NOT_FOUND_ERROR = -9, - CLEAR_BUFFER_IN_ERROR = -10, - CLEAR_BUFFER_OUT_ERROR = -11, - ABORT_READ_ERROR = -12, - ABORT_WRITE_ERROR = -13 -}; -``` - ---- - -### Error-handling idiom - -```c -int rv = serialWrite(h, data, len, 500, 1); -if (rv <= 0) { - // handle error – detailed info via registered onError callback (if any) -} -``` From f8ed4f0007c277efab9e646fa048f3445b6ac2f7 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Tue, 8 Jul 2025 09:22:28 +0200 Subject: [PATCH 27/45] Delete include/cpp_core/helpers.h --- include/cpp_core/helpers.h | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 include/cpp_core/helpers.h diff --git a/include/cpp_core/helpers.h b/include/cpp_core/helpers.h deleted file mode 100644 index d3b8cbc..0000000 --- a/include/cpp_core/helpers.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -namespace cpp_core -{ - -} // namespace cpp_core From ab7f65b171139bde836c61b937e21153ad8683ea Mon Sep 17 00:00:00 2001 From: Katze719 Date: Tue, 8 Jul 2025 19:14:49 +0200 Subject: [PATCH 28/45] Update project to require C++23, reflecting changes in CMakeLists.txt, README.md, and overview documentation. --- CMakeLists.txt | 4 ++-- README.md | 6 ++---- docs/overview.md | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 33a346a..835f635 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,8 +28,8 @@ target_include_directories(cpp_core INTERFACE $ $) -# Require C++17 -target_compile_features(cpp_core INTERFACE cxx_std_17) +# Require C++23 +target_compile_features(cpp_core INTERFACE cxx_std_23) # Install rules -------------------------------------------------------------- include(GNUInstallDirs) diff --git a/README.md b/README.md index ef81d3c..eb13a08 100644 --- a/README.md +++ b/README.md @@ -11,10 +11,8 @@ Header-only C++ helper library that provides small, cross-platform utilities and ## Documentation * 📄 **[Overview](docs/overview.md)** – architecture, build & quick start. -* 📜 **[C API Reference](docs/api_reference.md)** – parameter-by-parameter reference of every exported function. -* ⚡ **[Deno FFI Guide](docs/deno_ffi.md)** – step-by-step instructions plus full TypeScript examples. -* C++17, zero runtime dependencies +* C++23, zero runtime dependencies * Delivered as an INTERFACE target `cpp_core::cpp_core` * Fetchable via [CPM.cmake](https://github.com/cpm-cmake/CPM.cmake) or regular `find_package` @@ -23,7 +21,7 @@ Header-only C++ helper library that provides small, cross-platform utilities and ## Requirements * CMake ≥ 3.14 -* A C++17 compatible compiler (GCC 10+, Clang 11+, MSVC 2019+) +* A C++23 compatible compiler (GCC 13+, Clang 16+, MSVC 2022+) --- diff --git a/docs/overview.md b/docs/overview.md index f8de987..d69985c 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -1,6 +1,6 @@ # cpp-core – Library Overview -Welcome to **cpp-core**, a header-only, cross-platform C++17 helper library that bundles utilities frequently needed in systems programming and embedded scenarios. Besides multiple compile-time helpers it exposes a fully-featured **C API for serial communication**, making the library consumable from virtually any language (Rust, Python, Deno, …). +Welcome to **cpp-core**, a header-only, cross-platform C++23 helper library that bundles utilities frequently needed in systems programming and embedded scenarios. Besides multiple compile-time helpers it exposes a fully-featured **C API for serial communication**, making the library consumable from virtually any language (Rust, Python, Deno, …). > ⚠️ **Looking for a ready-to-use shared library?** Build one of the platform bindings instead of cpp-core itself: > • Windows → [cpp-bindings-windows](https://github.com/Serial-IO/cpp-bindings-windows) From 59d9d0d1298aa6aa027cf9e99443324cfcf3865e Mon Sep 17 00:00:00 2001 From: Katze719 Date: Tue, 8 Jul 2025 19:40:12 +0200 Subject: [PATCH 29/45] Refine serial API documentation in header file for clarity and consistency. Update function descriptions, parameter details, and improve overall readability. --- include/cpp_core/serial.h | 276 +++++++++++++++++++++++--------------- 1 file changed, 165 insertions(+), 111 deletions(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 6df558d..9ee1173 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -18,14 +18,13 @@ extern "C" { #endif /** - * @brief Retrieve the compile-time version number of the cpp_core library. + * @brief Copy the compile-time version of the cpp_core library. * - * Fills the provided Version structure with the current compile-time version - * of the library. If the pointer is nullptr the function returns immediately - * without performing any action. + * Writes the version baked into the library at build-time to the structure + * pointed to by @p out. If @p out is `nullptr` the call is a no-op. * - * @param[out] out Pointer to a cpp_core::Version object that will receive the - * version information. + * @param[out] out Pointer to a `cpp_core::Version` structure that receives + * the version information. May be `nullptr`. */ inline MODULE_API void getVersion(cpp_core::Version *out) { @@ -36,57 +35,72 @@ extern "C" } /** - * @brief Open a serial port with the given parameters. - * - * @param port Platform-specific identifier of the serial port (e.g. - * "COM3" on Windows or "/dev/ttyUSB0" on POSIX systems). - * @param baudrate Desired baud rate in bits per second. - * @param data_bits Number of data bits (typically 5–8). - * @param parity Parity mode: 0 = none, 1 = even, 2 = odd. - * @param stop_bits Stop-bit configuration: 0 = 1 stop bit, 2 = 2 stop bits. - * @return Opaque handle to the opened port on success; a negative - * value indicates failure. + * @brief Open and configure a serial port. + * + * The function attempts to open the device referenced by @p port and applies + * the given line settings. The pointer is interpreted as + * • `const char*` on POSIX and + * • `const wchar_t*` on Windows. + * + * @param port Null-terminated device identifier (e.g. "COM3", + * "/dev/ttyUSB0"). Passing `nullptr` results in + * ::cpp_core::StatusCodes::kNotFoundError. + * @param baudrate Desired baud rate in bit/s (≥ 300). + * @param data_bits Number of data bits (5–8). + * @param parity 0 = none, 1 = even, 2 = odd. + * @param stop_bits 0 = 1 stop bit, 2 = 2 stop bits. + * @return A positive opaque handle on success or a negative value + * from ::cpp_core::StatusCodes on failure. */ MODULE_API auto serialOpen(void *port, int baudrate, int data_bits, int parity = 0, int stop_bits = 0) -> intptr_t; /** * @brief Close a previously opened serial port. * - * @param handle Handle returned by serialOpen(). + * The handle becomes invalid after the call. Passing an already invalid + * (≤ 0) handle is a no-op. + * + * @param handle Handle obtained from serialOpen(). + * @return 0 on success or a negative error code on failure. */ - MODULE_API void serialClose(int64_t handle); + MODULE_API auto serialClose(int64_t handle) -> int; /** - * @brief Read bytes from the serial port. - * - * Attempts to read up to @p buffer_size bytes into @p buffer. The call blocks - * for at most @p timeout_ms for the first byte and for @p timeout_ms * - * @p multiplier for subsequent bytes. - * - * @param handle Port handle returned by serialOpen(). - * @param buffer Destination buffer that will receive the data. - * @param buffer_size Size of @p buffer in bytes. - * @param timeout_ms Timeout for the first byte in milliseconds. - * @param multiplier Factor applied to the timeout for each additional byte. - * @return Number of bytes actually read, or a negative value on - * error. + * @brief Read raw bytes from the serial port. + * + * The call blocks for at most @p timeout_ms milliseconds while waiting for + * the FIRST byte. For every subsequent byte the individual timeout is + * calculated as `timeout_ms * multiplier`. + * + * @param handle Port handle. + * @param buffer Destination buffer (must not be `nullptr`). + * @param buffer_size Size of @p buffer in bytes (> 0). + * @param timeout_ms Base timeout per byte in milliseconds (applied to the + * first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to @p timeout_ms for every byte after + * the first. 0 -> return immediately after the first byte. + * @return Bytes read (0 on timeout) or a negative error code. */ MODULE_API auto serialRead(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier) -> int; /** - * @brief Read bytes until a specific terminator character is encountered. + * @brief Read bytes until a terminator character appears. * - * Behaves like serialRead() but stops reading when the character pointed to by - * @p until_char is read (the terminator is included in the output). + * Semantics are identical to serialRead() but reading stops as soon as the + * byte pointed to by @p until_char has been received. The terminator is part + * of the returned data. * - * @param handle Port handle returned by serialOpen(). + * @param handle Port handle. * @param buffer Destination buffer. - * @param buffer_size Size of the destination buffer in bytes. - * @param timeout_ms Timeout for the first byte in milliseconds. - * @param multiplier Factor applied to the timeout for subsequent bytes. - * @param until_char Pointer to the terminator character. - * @return Number of bytes read (including the terminator), or a - * negative value on error. + * @param buffer_size Capacity of @p buffer in bytes. + * @param timeout_ms Base timeout per byte in milliseconds (applied to the + * first byte as-is; each additional byte uses + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for every additional byte. + * @param until_char Pointer to the terminator character (must not be `nullptr`). + * @return Bytes read (including the terminator), 0 on timeout + * or a negative error code. */ MODULE_API auto serialReadUntil(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier, void *until_char) -> int; @@ -94,13 +108,17 @@ extern "C" /** * @brief Write raw bytes to the serial port. * - * @param handle Port handle returned by serialOpen(). - * @param buffer Pointer to the data to transmit. - * @param buffer_size Number of bytes to send. - * @param timeout_ms Timeout for the first byte in milliseconds. - * @param multiplier Factor applied to the timeout for each additional byte. - * @return Number of bytes actually written, or a negative value on - * error. + * Timeout handling mirrors serialRead(): @p timeout_ms applies to the first + * byte, `timeout_ms * multiplier` to every subsequent one. + * + * @param handle Port handle. + * @param buffer Data to transmit (must not be `nullptr`). + * @param buffer_size Number of bytes in @p buffer (> 0). + * @param timeout_ms Base timeout per byte in milliseconds (applied to the + * first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @return Bytes written (may be 0 on timeout) or a negative error code. */ MODULE_API auto serialWrite(int64_t handle, const void *buffer, int buffer_size, int timeout_ms, int multiplier) -> int; @@ -108,19 +126,11 @@ extern "C" /** * @brief Enumerate all available serial ports on the system. * - * The supplied callback is invoked once for every discovered port and receives - * detailed information about the device. - * - * @param function Callback that is called for each port. The parameters are: - * - port: Short port name (e.g. "COM3"). - * - path: Full device path. - * - manufacturer: Manufacturer string (may be nullptr). - * - serial_number: Device serial number (may be nullptr). - * - pnp_id: Plug-and-play identifier (may be nullptr). - * - location_id: Device location (may be nullptr). - * - product_id: USB product ID string (may be nullptr). - * - vendor_id: USB vendor ID string (may be nullptr). - * @return Number of ports found; a negative value indicates error. + * The supplied callback is invoked once for every discovered port. All string + * parameters may be `nullptr` if the information is unknown. + * + * @param function Callback receiving port information. + * @return Number of ports found or a negative error code. */ MODULE_API auto serialGetPortsInfo(void (*function)(const char *port, const char *path, const char *manufacturer, const char *serial_number, const char *pnp_id, @@ -130,6 +140,9 @@ extern "C" /** * @brief Clear (flush) the device's input buffer. * + * Discards every byte the driver has already received but the application + * has not yet read. + * * @param handle Port handle. */ MODULE_API void serialClearBufferIn(int64_t handle); @@ -137,19 +150,28 @@ extern "C" /** * @brief Clear (flush) the device's output buffer. * + * Blocks until all queued bytes have been transmitted and then discards any + * remaining data. + * * @param handle Port handle. */ MODULE_API void serialClearBufferOut(int64_t handle); /** - * @brief Abort a blocking read operation running on another thread. + * @brief Abort a blocking read operation running in a different thread. + * + * The target read function returns immediately with + * ::cpp_core::StatusCodes::kAbortReadError. * * @param handle Port handle. */ MODULE_API void serialAbortRead(int64_t handle); /** - * @brief Abort a blocking write operation running on another thread. + * @brief Abort a blocking write operation running in a different thread. + * + * The target write function returns immediately with + * ::cpp_core::StatusCodes::kAbortWriteError. * * @param handle Port handle. */ @@ -158,86 +180,81 @@ extern "C" /** * @brief Register a callback that is invoked whenever bytes are read. * - * Passing nullptr disables the callback. + * Pass `nullptr` to disable the callback. * - * @param callback Pointer to a function receiving the number of bytes that - * have been read. + * @param callback Function receiving the number of bytes that have just been read. */ MODULE_API void serialSetReadCallback(void (*callback)(int bytes_read)); /** * @brief Register a callback that is invoked whenever bytes are written. * - * Passing nullptr disables the callback. + * Pass `nullptr` to disable the callback. * - * @param callback Pointer to a function receiving the number of bytes that - * have been written. + * @param callback Function receiving the number of bytes that have just been written. */ MODULE_API void serialSetWriteCallback(void (*callback)(int bytes_written)); /** * @brief Register a callback that is invoked whenever an error occurs. * - * Passing nullptr disables the callback. + * Pass `nullptr` to disable the callback. * - * @param callback Pointer to a function receiving an error code and a - * textual description. + * @param callback Function receiving the error code and a textual description. */ MODULE_API void serialSetErrorCallback(void (*callback)(int error_code, const char *message)); /** - * @brief Read a line terminated by a newline character ("\n"). This function keeps reading until the newline character is found or the timeout is reached. + * @brief Read a single line terminated by '\n'. + * + * Timeout handling is identical to serialRead(); the newline character is + * included in the returned data. * * @param handle Port handle. * @param buffer Destination buffer. - * @param buffer_size Size of the destination buffer in bytes. - * @param timeout_ms Maximum time to wait for the line in milliseconds. - * @return Number of bytes read (including the newline), or a - * negative value on error. + * @param buffer_size Capacity of @p buffer in bytes. + * @param timeout_ms Base timeout per byte in milliseconds (applied to the + * first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @return Bytes read (0 on timeout) or a negative error code. */ - MODULE_API auto serialReadLine(int64_t handle, void *buffer, int buffer_size, int timeout_ms) -> int; + MODULE_API auto serialReadLine(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier) + -> int; /** - * @brief Write a buffer followed by a newline character ("\n"). + * @brief Write a buffer followed by a '\n' byte. + * + * Convenience helper around serialWrite(). * * @param handle Port handle. * @param buffer Data to transmit. * @param buffer_size Number of bytes in @p buffer. - * @param timeout_ms Maximum time to wait for the transmission in - * milliseconds. - * @return Number of bytes actually written, or a negative value on - * error. + * @param timeout_ms Base timeout per byte in milliseconds (applied to the + * first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @return Bytes written or a negative error code. */ MODULE_API auto serialWriteLine(int64_t handle, const void *buffer, int buffer_size, int timeout_ms) -> int; /** - * @brief Read until a specific byte sequence is encountered. + * @brief Read until a specific byte sequence appears. * - * @param handle Port handle. - * @param buffer Destination buffer. - * @param buffer_size Size of the destination buffer in bytes. - * @param timeout_ms Timeout for the first byte in milliseconds. - * @param sequence Pointer to the byte sequence that terminates the read. - * @return Number of bytes read (including the terminating - * sequence), or a negative value on error. - */ - MODULE_API auto serialReadUntilSequence(int64_t handle, void *buffer, int buffer_size, int timeout_ms, - void *sequence) -> int; - - /** - * @brief Read a frame delimited by start and end bytes. + * Works like serialReadUntil() but supports an arbitrary terminator string. + * The terminator is included in the returned data. * * @param handle Port handle. * @param buffer Destination buffer. - * @param buffer_size Size of the destination buffer in bytes. - * @param timeout_ms Maximum time to wait for the frame in milliseconds. - * @param start_byte Byte that marks the beginning of the frame. - * @param end_byte Byte that marks the end of the frame. - * @return Number of bytes in the frame (including delimiters), or - * a negative value on error. + * @param buffer_size Capacity of @p buffer in bytes. + * @param timeout_ms Base timeout per byte in milliseconds (first byte + * uses this value; each additional byte uses + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @param sequence Pointer to the terminating byte sequence (must not be `nullptr`). + * @return Bytes read (including the terminator) or a negative error code. */ - MODULE_API auto serialReadFrame(int64_t handle, void *buffer, int buffer_size, int timeout_ms, char start_byte, - char end_byte) -> int; + MODULE_API auto serialReadUntilSequence(int64_t handle, void *buffer, int buffer_size, int timeout_ms, + int multiplier, void *sequence) -> int; /** * @brief Total number of bytes transmitted since the port was opened. @@ -256,26 +273,63 @@ extern "C" MODULE_API auto serialInBytesTotal(int64_t handle) -> int64_t; /** - * @brief Block until all queued bytes have been transmitted. + * @brief Wait until the operating-system driver has physically sent every queued byte. + * + * The function blocks the *calling thread* until the device driver reports + * that the transmit FIFO is **empty** – i.e. all bytes handed to previous + * `serialWrite*` calls have been shifted out on the wire. It does *not* + * flush higher-level protocol buffers you may have implemented yourself. + * + * Typical use-case: ensure a complete command frame has left the UART + * before toggling RTS/DTR or powering down the device. + * + * @code{.c} + * // Send a frame and make sure it actually hits the line + * serialWrite(h, frame, frame_len, 50, 1); + * if (serialDrain(h) < 0) { + * fprintf(stderr, "drain failed\n"); + * } + * @endcode * * @param handle Port handle. - * @return 0 on success, negative value on error. + * @return 0 on success; negative ::cpp_core::StatusCodes value on error + * (e.g. kInvalidHandleError). */ MODULE_API auto serialDrain(int64_t handle) -> int; /** - * @brief Number of bytes currently waiting in the driver's input buffer. + * @brief Query how many bytes can be read *immediately* without blocking. + * + * The number reflects the size of the driver's RX FIFO **after** accounting + * for data already consumed by the application. A value of `0` therefore + * means a read call would have to wait for the next byte to arrive. + * + * @code{.c} + * int pending = serialInBytesWaiting(h); + * if (pending > 0) { + * serialRead(h, buf, pending, 0, 1); // non-blocking read + * } + * @endcode * * @param handle Port handle. - * @return Number of bytes available for immediate reading. + * @return Bytes available for instant reading or a negative error code. */ MODULE_API auto serialInBytesWaiting(int64_t handle) -> int; /** - * @brief Number of bytes currently waiting in the driver's output buffer. + * @brief Return the number of bytes that have been accepted by the driver but not yet sent. + * + * Useful for gauging transmission progress in the background or for pacing + * further writes to avoid unbounded buffering. + * + * @code{.c} + * while (serialOutBytesWaiting(h) > 0) { + * usleep(1000); // wait 1 ms and poll again + * } + * @endcode * * @param handle Port handle. - * @return Number of bytes pending transmission. + * @return Bytes still waiting in the TX FIFO or a negative error code. */ MODULE_API auto serialOutBytesWaiting(int64_t handle) -> int; From a1aee339da77d303eea03bb57faea614a2f902a4 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Tue, 8 Jul 2025 19:54:32 +0200 Subject: [PATCH 30/45] Update CMake configuration files: rename cpp_coreConfig.cmake.in to cpp_core_config.cmake.in and add initial content for package configuration. --- CMakeLists.txt | 2 +- cmake/{cpp_coreConfig.cmake.in => cpp_core_config.cmake.in} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename cmake/{cpp_coreConfig.cmake.in => cpp_core_config.cmake.in} (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 835f635..933f7d5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,7 +49,7 @@ write_basic_package_version_file( COMPATIBILITY SameMajorVersion) configure_package_config_file( - ${CMAKE_CURRENT_LIST_DIR}/cmake/cpp_coreConfig.cmake.in + ${CMAKE_CURRENT_LIST_DIR}/cmake/cpp_core_config.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cpp_coreConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cpp_core) diff --git a/cmake/cpp_coreConfig.cmake.in b/cmake/cpp_core_config.cmake.in similarity index 100% rename from cmake/cpp_coreConfig.cmake.in rename to cmake/cpp_core_config.cmake.in From 9fc44a98321f56b150c3ba39205edf871a85ef73 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Tue, 8 Jul 2025 19:59:31 +0200 Subject: [PATCH 31/45] Enhance serialWriteLine function signature in serial.h to include a multiplier parameter for timeout adjustments. Update documentation for clarity on function behavior and parameter details. --- include/cpp_core/serial.h | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 9ee1173..2d60edc 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -225,17 +225,20 @@ extern "C" /** * @brief Write a buffer followed by a '\n' byte. * - * Convenience helper around serialWrite(). + * Convenience wrapper that adds the line-feed for you and then calls + * `serialWrite()`. * * @param handle Port handle. * @param buffer Data to transmit. * @param buffer_size Number of bytes in @p buffer. - * @param timeout_ms Base timeout per byte in milliseconds (applied to the - * first byte as-is; subsequent bytes use - * `timeout_ms * multiplier`). - * @return Bytes written or a negative error code. + * @param timeout_ms Base timeout per byte in milliseconds. + * @param multiplier Factor applied to the timeout for bytes after the + * first. + * @return Bytes written (including the newline) or a negative + * error code. */ - MODULE_API auto serialWriteLine(int64_t handle, const void *buffer, int buffer_size, int timeout_ms) -> int; + MODULE_API auto serialWriteLine(int64_t handle, const void *buffer, int buffer_size, int timeout_ms, int multiplier) + -> int; /** * @brief Read until a specific byte sequence appears. From 99f439438c7796dc8fc46046581b298a0f823603 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Tue, 8 Jul 2025 20:45:02 +0200 Subject: [PATCH 32/45] Refactor serial API function signatures in serial.h for improved readability by formatting parameters across multiple lines. Update .clang-format to enforce new alignment and formatting rules. --- .clang-format | 8 ++-- include/cpp_core/serial.h | 86 +++++++++++++++++++++++++++++++-------- 2 files changed, 74 insertions(+), 20 deletions(-) diff --git a/.clang-format b/.clang-format index ed08e49..7ff10ef 100644 --- a/.clang-format +++ b/.clang-format @@ -2,10 +2,12 @@ Language: Cpp # BasedOnStyle: Microsoft AccessModifierOffset: -2 -AlignAfterOpenBracket: Align +AlignAfterOpenBracket: BlockIndent AlignEscapedNewlines: Right AlignOperands: Align AlignTrailingComments: true +AlignConsecutiveAssignments: true +AlignConsecutiveDeclarations: true AllowAllArgumentsOnNextLine: true AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true @@ -22,8 +24,8 @@ AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: MultiLine AttributeMacros: - __capability -BinPackArguments: true -BinPackParameters: true +BinPackArguments: false +BinPackParameters: AlwaysOnePerLine BraceWrapping: AfterCaseLabel: false AfterClass: true diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 2d60edc..2545a60 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -52,7 +52,13 @@ extern "C" * @return A positive opaque handle on success or a negative value * from ::cpp_core::StatusCodes on failure. */ - MODULE_API auto serialOpen(void *port, int baudrate, int data_bits, int parity = 0, int stop_bits = 0) -> intptr_t; + MODULE_API auto serialOpen( + void *port, + int baudrate, + int data_bits, + int parity = 0, + int stop_bits = 0 + ) -> intptr_t; /** * @brief Close a previously opened serial port. @@ -82,7 +88,13 @@ extern "C" * the first. 0 -> return immediately after the first byte. * @return Bytes read (0 on timeout) or a negative error code. */ - MODULE_API auto serialRead(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier) -> int; + MODULE_API auto serialRead( + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier + ) -> int; /** * @brief Read bytes until a terminator character appears. @@ -102,8 +114,14 @@ extern "C" * @return Bytes read (including the terminator), 0 on timeout * or a negative error code. */ - MODULE_API auto serialReadUntil(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier, - void *until_char) -> int; + MODULE_API auto serialReadUntil( + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier, + void *until_char + ) -> int; /** * @brief Write raw bytes to the serial port. @@ -120,8 +138,13 @@ extern "C" * @param multiplier Factor applied to the timeout for subsequent bytes. * @return Bytes written (may be 0 on timeout) or a negative error code. */ - MODULE_API auto serialWrite(int64_t handle, const void *buffer, int buffer_size, int timeout_ms, int multiplier) - -> int; + MODULE_API auto serialWrite( + int64_t handle, + const void *buffer, + int buffer_size, + int timeout_ms, + int multiplier + ) -> int; /** * @brief Enumerate all available serial ports on the system. @@ -132,10 +155,18 @@ extern "C" * @param function Callback receiving port information. * @return Number of ports found or a negative error code. */ - MODULE_API auto serialGetPortsInfo(void (*function)(const char *port, const char *path, const char *manufacturer, - const char *serial_number, const char *pnp_id, - const char *location_id, const char *product_id, - const char *vendor_id)) -> int; + MODULE_API auto serialGetPortsInfo( + void (*function)( + const char *port, + const char *path, + const char *manufacturer, + const char *serial_number, + const char *pnp_id, + const char *location_id, + const char *product_id, + const char *vendor_id + ) + ) -> int; /** * @brief Clear (flush) the device's input buffer. @@ -202,7 +233,12 @@ extern "C" * * @param callback Function receiving the error code and a textual description. */ - MODULE_API void serialSetErrorCallback(void (*callback)(int error_code, const char *message)); + MODULE_API void serialSetErrorCallback( + void (*callback)( + int error_code, + const char *message + ) + ); /** * @brief Read a single line terminated by '\n'. @@ -219,8 +255,13 @@ extern "C" * @param multiplier Factor applied to the timeout for subsequent bytes. * @return Bytes read (0 on timeout) or a negative error code. */ - MODULE_API auto serialReadLine(int64_t handle, void *buffer, int buffer_size, int timeout_ms, int multiplier) - -> int; + MODULE_API auto serialReadLine( + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier + ) -> int; /** * @brief Write a buffer followed by a '\n' byte. @@ -237,8 +278,13 @@ extern "C" * @return Bytes written (including the newline) or a negative * error code. */ - MODULE_API auto serialWriteLine(int64_t handle, const void *buffer, int buffer_size, int timeout_ms, int multiplier) - -> int; + MODULE_API auto serialWriteLine( + int64_t handle, + const void *buffer, + int buffer_size, + int timeout_ms, + int multiplier + ) -> int; /** * @brief Read until a specific byte sequence appears. @@ -256,8 +302,14 @@ extern "C" * @param sequence Pointer to the terminating byte sequence (must not be `nullptr`). * @return Bytes read (including the terminator) or a negative error code. */ - MODULE_API auto serialReadUntilSequence(int64_t handle, void *buffer, int buffer_size, int timeout_ms, - int multiplier, void *sequence) -> int; + MODULE_API auto serialReadUntilSequence( + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier, + void *sequence + ) -> int; /** * @brief Total number of bytes transmitted since the port was opened. From b4957bb10d610cb9b9f34681f4db149a185c464b Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Wed, 9 Jul 2025 07:47:11 +0200 Subject: [PATCH 33/45] Update include/cpp_core/serial.h Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/serial.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 2545a60..d9cfa11 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -39,8 +39,8 @@ extern "C" * * The function attempts to open the device referenced by @p port and applies * the given line settings. The pointer is interpreted as - * • `const char*` on POSIX and - * • `const wchar_t*` on Windows. + * - `const char*` on POSIX and + * - `const wchar_t*` on Windows. * * @param port Null-terminated device identifier (e.g. "COM3", * "/dev/ttyUSB0"). Passing `nullptr` results in From 26ac28a7c0b720cc9a80113593285eca377e7278 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Wed, 9 Jul 2025 07:47:38 +0200 Subject: [PATCH 34/45] Update include/cpp_core/serial.h Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/serial.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index d9cfa11..43b5f4b 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -347,8 +347,7 @@ extern "C" * @endcode * * @param handle Port handle. - * @return 0 on success; negative ::cpp_core::StatusCodes value on error - * (e.g. kInvalidHandleError). + * @return 0 on success; negative ::cpp_core::StatusCodes value on error. */ MODULE_API auto serialDrain(int64_t handle) -> int; From 3eab2c16d902f64bfe1e0caa055e24f1e99bf98d Mon Sep 17 00:00:00 2001 From: Katze719 Date: Wed, 9 Jul 2025 20:20:25 +0200 Subject: [PATCH 35/45] Add umbrella header and modular API for cpp_core library - Introduced `cpp_core.h` as an umbrella header to simplify access to the cpp_core library's public C/C++ API. - Created `module_api.h` for platform-specific export definitions. - Refactored `serial.h` to include modular interface headers for better organization and maintainability. - Added multiple interface headers for serial operations, including functions for reading, writing, and managing serial ports. This update enhances the library's structure and usability for developers. --- include/cpp_core.h | 17 + include/cpp_core/interface/get_version.h | 29 ++ .../cpp_core/interface/serial_abort_read.h | 22 + .../cpp_core/interface/serial_abort_write.h | 22 + .../interface/serial_clear_buffer_in.h | 22 + .../interface/serial_clear_buffer_out.h | 22 + include/cpp_core/interface/serial_close.h | 23 + include/cpp_core/interface/serial_drain.h | 36 ++ .../interface/serial_get_ports_info.h | 33 ++ .../interface/serial_in_bytes_total.h | 20 + .../interface/serial_in_bytes_waiting.h | 31 ++ include/cpp_core/interface/serial_open.h | 38 ++ .../interface/serial_out_bytes_total.h | 20 + .../interface/serial_out_bytes_waiting.h | 29 ++ include/cpp_core/interface/serial_read.h | 37 ++ include/cpp_core/interface/serial_read_line.h | 35 ++ .../cpp_core/interface/serial_read_until.h | 39 ++ .../interface/serial_read_until_sequence.h | 37 ++ .../interface/serial_set_error_callback.h | 25 ++ .../interface/serial_set_read_callback.h | 20 + .../interface/serial_set_write_callback.h | 20 + include/cpp_core/interface/serial_write.h | 35 ++ .../cpp_core/interface/serial_write_line.h | 35 ++ include/cpp_core/module_api.h | 11 + include/cpp_core/serial.h | 414 ++---------------- 25 files changed, 683 insertions(+), 389 deletions(-) create mode 100644 include/cpp_core.h create mode 100644 include/cpp_core/interface/get_version.h create mode 100644 include/cpp_core/interface/serial_abort_read.h create mode 100644 include/cpp_core/interface/serial_abort_write.h create mode 100644 include/cpp_core/interface/serial_clear_buffer_in.h create mode 100644 include/cpp_core/interface/serial_clear_buffer_out.h create mode 100644 include/cpp_core/interface/serial_close.h create mode 100644 include/cpp_core/interface/serial_drain.h create mode 100644 include/cpp_core/interface/serial_get_ports_info.h create mode 100644 include/cpp_core/interface/serial_in_bytes_total.h create mode 100644 include/cpp_core/interface/serial_in_bytes_waiting.h create mode 100644 include/cpp_core/interface/serial_open.h create mode 100644 include/cpp_core/interface/serial_out_bytes_total.h create mode 100644 include/cpp_core/interface/serial_out_bytes_waiting.h create mode 100644 include/cpp_core/interface/serial_read.h create mode 100644 include/cpp_core/interface/serial_read_line.h create mode 100644 include/cpp_core/interface/serial_read_until.h create mode 100644 include/cpp_core/interface/serial_read_until_sequence.h create mode 100644 include/cpp_core/interface/serial_set_error_callback.h create mode 100644 include/cpp_core/interface/serial_set_read_callback.h create mode 100644 include/cpp_core/interface/serial_set_write_callback.h create mode 100644 include/cpp_core/interface/serial_write.h create mode 100644 include/cpp_core/interface/serial_write_line.h create mode 100644 include/cpp_core/module_api.h diff --git a/include/cpp_core.h b/include/cpp_core.h new file mode 100644 index 0000000..7ecd117 --- /dev/null +++ b/include/cpp_core.h @@ -0,0 +1,17 @@ +#pragma once + +/* + * cpp_core.h — Umbrella header for the cpp_core library + * + * Include this single file to gain access to the complete public C/C++ API + * of the cpp_core runtime. Internally it forwards to the individual header + * units located in the cpp_core/ sub-directory so fine-grained includes continue + * to work as before. Prefer including the specific headers you actually need + * in translation units with strict compile-time requirements; however for + * quick prototyping and high-level application code, this umbrella header + * offers the most convenient entry point. + */ + +#include "cpp_core/serial.h" +#include "cpp_core/status_codes.h" +#include "cpp_core/version.h" diff --git a/include/cpp_core/interface/get_version.h b/include/cpp_core/interface/get_version.h new file mode 100644 index 0000000..5bf77aa --- /dev/null +++ b/include/cpp_core/interface/get_version.h @@ -0,0 +1,29 @@ +#pragma once +#include "../module_api.h" +#include "../version.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Copy the compile-time version of the cpp_core library. + * + * Writes the version baked into the library at build-time to the structure + * pointed to by @p out. If @p out is `nullptr` the call is a no-op. + * + * @param[out] out Pointer to a `cpp_core::Version` structure that receives + * the version information. May be `nullptr`. + */ + inline MODULE_API void getVersion(cpp_core::Version *out) + { + if (out != nullptr) + { + *out = cpp_core::kVersion; + } + } + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_abort_read.h b/include/cpp_core/interface/serial_abort_read.h new file mode 100644 index 0000000..264477f --- /dev/null +++ b/include/cpp_core/interface/serial_abort_read.h @@ -0,0 +1,22 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Abort a blocking read operation running in a different thread. + * + * The target read function returns immediately with + * ::cpp_core::StatusCodes::kAbortReadError. + * + * @param handle Port handle. + */ + MODULE_API void serialAbortRead(int64_t handle); + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_abort_write.h b/include/cpp_core/interface/serial_abort_write.h new file mode 100644 index 0000000..52740ca --- /dev/null +++ b/include/cpp_core/interface/serial_abort_write.h @@ -0,0 +1,22 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Abort a blocking write operation running in a different thread. + * + * The target write function returns immediately with + * ::cpp_core::StatusCodes::kAbortWriteError. + * + * @param handle Port handle. + */ + MODULE_API void serialAbortWrite(int64_t handle); + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_clear_buffer_in.h b/include/cpp_core/interface/serial_clear_buffer_in.h new file mode 100644 index 0000000..20497ca --- /dev/null +++ b/include/cpp_core/interface/serial_clear_buffer_in.h @@ -0,0 +1,22 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Clear (flush) the device's input buffer. + * + * Discards every byte the driver has already received but the application + * has not yet read. + * + * @param handle Port handle. + */ + MODULE_API void serialClearBufferIn(int64_t handle); + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_clear_buffer_out.h b/include/cpp_core/interface/serial_clear_buffer_out.h new file mode 100644 index 0000000..6737597 --- /dev/null +++ b/include/cpp_core/interface/serial_clear_buffer_out.h @@ -0,0 +1,22 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Clear (flush) the device's output buffer. + * + * Blocks until all queued bytes have been transmitted and then discards any + * remaining data. + * + * @param handle Port handle. + */ + MODULE_API void serialClearBufferOut(int64_t handle); + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_close.h b/include/cpp_core/interface/serial_close.h new file mode 100644 index 0000000..ca79fbb --- /dev/null +++ b/include/cpp_core/interface/serial_close.h @@ -0,0 +1,23 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Close a previously opened serial port. + * + * The handle becomes invalid after the call. Passing an already invalid + * (≤ 0) handle is a no-op. + * + * @param handle Handle obtained from serialOpen(). + * @return 0 on success or a negative error code on failure. + */ + MODULE_API auto serialClose(int64_t handle) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_drain.h b/include/cpp_core/interface/serial_drain.h new file mode 100644 index 0000000..bc2b6d6 --- /dev/null +++ b/include/cpp_core/interface/serial_drain.h @@ -0,0 +1,36 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Wait until the operating-system driver has physically sent every queued byte. + * + * The function blocks the *calling thread* until the device driver reports + * that the transmit FIFO is **empty** – i.e. all bytes handed to previous + * `serialWrite*` calls have been shifted out on the wire. It does *not* + * flush higher-level protocol buffers you may have implemented yourself. + * + * Typical use-case: ensure a complete command frame has left the UART + * before toggling RTS/DTR or powering down the device. + * + * @code{.c} + * // Send a frame and make sure it actually hits the line + * serialWrite(h, frame, frame_len, 50, 1); + * if (serialDrain(h) < 0) { + * fprintf(stderr, "drain failed\n"); + * } + * @endcode + * + * @param handle Port handle. + * @return 0 on success; negative ::cpp_core::StatusCodes value on error. + */ + MODULE_API auto serialDrain(int64_t handle) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_get_ports_info.h b/include/cpp_core/interface/serial_get_ports_info.h new file mode 100644 index 0000000..20318dc --- /dev/null +++ b/include/cpp_core/interface/serial_get_ports_info.h @@ -0,0 +1,33 @@ +#pragma once +#include "../module_api.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Enumerate all available serial ports on the system. + * + * The supplied callback is invoked once for every discovered port. All string + * parameters may be `nullptr` if the information is unknown. + * + * @param function Callback receiving port information. + * @return Number of ports found or a negative error code. + */ + MODULE_API auto serialGetPortsInfo( + void (*function)( + const char *port, + const char *path, + const char *manufacturer, + const char *serial_number, + const char *pnp_id, + const char *location_id, + const char *product_id, + const char *vendor_id + ) + ) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_in_bytes_total.h b/include/cpp_core/interface/serial_in_bytes_total.h new file mode 100644 index 0000000..b4b892e --- /dev/null +++ b/include/cpp_core/interface/serial_in_bytes_total.h @@ -0,0 +1,20 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Total number of bytes received since the port was opened. + * + * @param handle Port handle. + * @return Total number of bytes read. + */ + MODULE_API auto serialInBytesTotal(int64_t handle) -> int64_t; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_in_bytes_waiting.h b/include/cpp_core/interface/serial_in_bytes_waiting.h new file mode 100644 index 0000000..ea9bdaf --- /dev/null +++ b/include/cpp_core/interface/serial_in_bytes_waiting.h @@ -0,0 +1,31 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Query how many bytes can be read *immediately* without blocking. + * + * The number reflects the size of the driver's RX FIFO **after** accounting + * for data already consumed by the application. A value of `0` therefore + * means a read call would have to wait for the next byte to arrive. + * + * @code{.c} + * int pending = serialInBytesWaiting(h); + * if (pending > 0) { + * serialRead(h, buf, pending, 0, 1); // non-blocking read + * } + * @endcode + * + * @param handle Port handle. + * @return Bytes available for instant reading or a negative error code. + */ + MODULE_API auto serialInBytesWaiting(int64_t handle) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_open.h b/include/cpp_core/interface/serial_open.h new file mode 100644 index 0000000..1345b6d --- /dev/null +++ b/include/cpp_core/interface/serial_open.h @@ -0,0 +1,38 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Open and configure a serial port. + * + * The function attempts to open the device referenced by @p port and applies + * the given line settings. The pointer is interpreted as + * - `const char*` on POSIX and + * - `const wchar_t*` on Windows. + * + * @param port Null-terminated device identifier (e.g. "COM3", + * "/dev/ttyUSB0"). Passing `nullptr` results in + * ::cpp_core::StatusCodes::kNotFoundError. + * @param baudrate Desired baud rate in bit/s (≥ 300). + * @param data_bits Number of data bits (5–8). + * @param parity 0 = none, 1 = even, 2 = odd. + * @param stop_bits 0 = 1 stop bit, 2 = 2 stop bits. + * @return A positive opaque handle on success or a negative value + * from ::cpp_core::StatusCodes on failure. + */ + MODULE_API auto serialOpen( + void *port, + int baudrate, + int data_bits, + int parity = 0, + int stop_bits = 0 + ) -> intptr_t; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_out_bytes_total.h b/include/cpp_core/interface/serial_out_bytes_total.h new file mode 100644 index 0000000..f34725c --- /dev/null +++ b/include/cpp_core/interface/serial_out_bytes_total.h @@ -0,0 +1,20 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Total number of bytes transmitted since the port was opened. + * + * @param handle Port handle. + * @return Total number of bytes written. + */ + MODULE_API auto serialOutBytesTotal(int64_t handle) -> int64_t; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_out_bytes_waiting.h b/include/cpp_core/interface/serial_out_bytes_waiting.h new file mode 100644 index 0000000..5d283fe --- /dev/null +++ b/include/cpp_core/interface/serial_out_bytes_waiting.h @@ -0,0 +1,29 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Return the number of bytes that have been accepted by the driver but not yet sent. + * + * Useful for gauging transmission progress in the background or for pacing + * further writes to avoid unbounded buffering. + * + * @code{.c} + * while (serialOutBytesWaiting(h) > 0) { + * usleep(1000); // wait 1 ms and poll again + * } + * @endcode + * + * @param handle Port handle. + * @return Bytes still waiting in the TX FIFO or a negative error code. + */ + MODULE_API auto serialOutBytesWaiting(int64_t handle) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_read.h b/include/cpp_core/interface/serial_read.h new file mode 100644 index 0000000..a160cb2 --- /dev/null +++ b/include/cpp_core/interface/serial_read.h @@ -0,0 +1,37 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Read raw bytes from the serial port. + * + * The call blocks for at most @p timeout_ms milliseconds while waiting for + * the FIRST byte. For every subsequent byte the individual timeout is + * calculated as `timeout_ms * multiplier`. + * + * @param handle Port handle. + * @param buffer Destination buffer (must not be `nullptr`). + * @param buffer_size Size of @p buffer in bytes (> 0). + * @param timeout_ms Base timeout per byte in milliseconds (applied to the + * first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to @p timeout_ms for every byte after + * the first. 0 -> return immediately after the first byte. + * @return Bytes read (0 on timeout) or a negative error code. + */ + MODULE_API auto serialRead( + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier + ) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_read_line.h b/include/cpp_core/interface/serial_read_line.h new file mode 100644 index 0000000..d68f606 --- /dev/null +++ b/include/cpp_core/interface/serial_read_line.h @@ -0,0 +1,35 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Read a single line terminated by '\n'. + * + * Timeout handling is identical to serialRead(); the newline character is + * included in the returned data. + * + * @param handle Port handle. + * @param buffer Destination buffer. + * @param buffer_size Capacity of @p buffer in bytes. + * @param timeout_ms Base timeout per byte in milliseconds (applied to the + * first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @return Bytes read (0 on timeout) or a negative error code. + */ + MODULE_API auto serialReadLine( + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier + ) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_read_until.h b/include/cpp_core/interface/serial_read_until.h new file mode 100644 index 0000000..ad3f902 --- /dev/null +++ b/include/cpp_core/interface/serial_read_until.h @@ -0,0 +1,39 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Read bytes until a terminator character appears. + * + * Semantics are identical to serialRead() but reading stops as soon as the + * byte pointed to by @p until_char has been received. The terminator is part + * of the returned data. + * + * @param handle Port handle. + * @param buffer Destination buffer. + * @param buffer_size Capacity of @p buffer in bytes. + * @param timeout_ms Base timeout per byte in milliseconds (applied to the + * first byte as-is; each additional byte uses + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for every additional byte. + * @param until_char Pointer to the terminator character (must not be `nullptr`). + * @return Bytes read (including the terminator), 0 on timeout + * or a negative error code. + */ + MODULE_API auto serialReadUntil( + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier, + void *until_char + ) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_read_until_sequence.h b/include/cpp_core/interface/serial_read_until_sequence.h new file mode 100644 index 0000000..8369b8e --- /dev/null +++ b/include/cpp_core/interface/serial_read_until_sequence.h @@ -0,0 +1,37 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Read until a specific byte sequence appears. + * + * Works like serialReadUntil() but supports an arbitrary terminator string. + * The terminator is included in the returned data. + * + * @param handle Port handle. + * @param buffer Destination buffer. + * @param buffer_size Capacity of @p buffer in bytes. + * @param timeout_ms Base timeout per byte in milliseconds (first byte + * uses this value; each additional byte uses + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @param sequence Pointer to the terminating byte sequence (must not be `nullptr`). + * @return Bytes read (including the terminator) or a negative error code. + */ + MODULE_API auto serialReadUntilSequence( + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier, + void *sequence + ) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_set_error_callback.h b/include/cpp_core/interface/serial_set_error_callback.h new file mode 100644 index 0000000..e636ccf --- /dev/null +++ b/include/cpp_core/interface/serial_set_error_callback.h @@ -0,0 +1,25 @@ +#pragma once +#include "../module_api.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Register a callback that is invoked whenever an error occurs. + * + * Pass `nullptr` to disable the callback. + * + * @param callback Function receiving the error code and a textual description. + */ + MODULE_API void serialSetErrorCallback( + void (*callback)( + int error_code, + const char *message + ) + ); + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_set_read_callback.h b/include/cpp_core/interface/serial_set_read_callback.h new file mode 100644 index 0000000..6e548e9 --- /dev/null +++ b/include/cpp_core/interface/serial_set_read_callback.h @@ -0,0 +1,20 @@ +#pragma once +#include "../module_api.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Register a callback that is invoked whenever bytes are read. + * + * Pass `nullptr` to disable the callback. + * + * @param callback Function receiving the number of bytes that have just been read. + */ + MODULE_API void serialSetReadCallback(void (*callback)(int bytes_read)); + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_set_write_callback.h b/include/cpp_core/interface/serial_set_write_callback.h new file mode 100644 index 0000000..4470090 --- /dev/null +++ b/include/cpp_core/interface/serial_set_write_callback.h @@ -0,0 +1,20 @@ +#pragma once +#include "../module_api.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Register a callback that is invoked whenever bytes are written. + * + * Pass `nullptr` to disable the callback. + * + * @param callback Function receiving the number of bytes that have just been written. + */ + MODULE_API void serialSetWriteCallback(void (*callback)(int bytes_written)); + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_write.h b/include/cpp_core/interface/serial_write.h new file mode 100644 index 0000000..1a559d8 --- /dev/null +++ b/include/cpp_core/interface/serial_write.h @@ -0,0 +1,35 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Write raw bytes to the serial port. + * + * Timeout handling mirrors serialRead(): @p timeout_ms applies to the first + * byte, `timeout_ms * multiplier` to every subsequent one. + * + * @param handle Port handle. + * @param buffer Data to transmit (must not be `nullptr`). + * @param buffer_size Number of bytes in @p buffer (> 0). + * @param timeout_ms Base timeout per byte in milliseconds (applied to the + * first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @return Bytes written (may be 0 on timeout) or a negative error code. + */ + MODULE_API auto serialWrite( + int64_t handle, + const void *buffer, + int buffer_size, + int timeout_ms, + int multiplier + ) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/interface/serial_write_line.h b/include/cpp_core/interface/serial_write_line.h new file mode 100644 index 0000000..14f6e25 --- /dev/null +++ b/include/cpp_core/interface/serial_write_line.h @@ -0,0 +1,35 @@ +#pragma once +#include "../module_api.h" +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief Write a buffer followed by a '\n' byte. + * + * Convenience wrapper that adds the line-feed for you and then calls + * `serialWrite()`. + * + * @param handle Port handle. + * @param buffer Data to transmit. + * @param buffer_size Number of bytes in @p buffer. + * @param timeout_ms Base timeout per byte in milliseconds. + * @param multiplier Factor applied to the timeout for bytes after the + * first. + * @return Bytes written (including the newline) or a negative + * error code. + */ + MODULE_API auto serialWriteLine( + int64_t handle, + const void *buffer, + int buffer_size, + int timeout_ms, + int multiplier + ) -> int; + +#ifdef __cplusplus +} +#endif diff --git a/include/cpp_core/module_api.h b/include/cpp_core/module_api.h new file mode 100644 index 0000000..11d7116 --- /dev/null +++ b/include/cpp_core/module_api.h @@ -0,0 +1,11 @@ +#pragma once + +#if defined(_WIN32) || defined(__CYGWIN__) +#ifdef cpp_windows_bindings_EXPORTS +#define MODULE_API __declspec(dllexport) +#else +#define MODULE_API __declspec(dllimport) +#endif +#else +#define MODULE_API __attribute__((visibility("default"))) +#endif diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 43b5f4b..3f3ecad 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -1,392 +1,28 @@ #pragma once -#include "version.h" - -#include - -#if defined(_WIN32) || defined(__CYGWIN__) -#ifdef cpp_windows_bindings_EXPORTS -#define MODULE_API __declspec(dllexport) -#else -#define MODULE_API __declspec(dllimport) -#endif -#else -#define MODULE_API __attribute__((visibility("default"))) -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif - /** - * @brief Copy the compile-time version of the cpp_core library. - * - * Writes the version baked into the library at build-time to the structure - * pointed to by @p out. If @p out is `nullptr` the call is a no-op. - * - * @param[out] out Pointer to a `cpp_core::Version` structure that receives - * the version information. May be `nullptr`. - */ - inline MODULE_API void getVersion(cpp_core::Version *out) - { - if (out != nullptr) - { - *out = cpp_core::kVersion; - } - } - - /** - * @brief Open and configure a serial port. - * - * The function attempts to open the device referenced by @p port and applies - * the given line settings. The pointer is interpreted as - * - `const char*` on POSIX and - * - `const wchar_t*` on Windows. - * - * @param port Null-terminated device identifier (e.g. "COM3", - * "/dev/ttyUSB0"). Passing `nullptr` results in - * ::cpp_core::StatusCodes::kNotFoundError. - * @param baudrate Desired baud rate in bit/s (≥ 300). - * @param data_bits Number of data bits (5–8). - * @param parity 0 = none, 1 = even, 2 = odd. - * @param stop_bits 0 = 1 stop bit, 2 = 2 stop bits. - * @return A positive opaque handle on success or a negative value - * from ::cpp_core::StatusCodes on failure. - */ - MODULE_API auto serialOpen( - void *port, - int baudrate, - int data_bits, - int parity = 0, - int stop_bits = 0 - ) -> intptr_t; - - /** - * @brief Close a previously opened serial port. - * - * The handle becomes invalid after the call. Passing an already invalid - * (≤ 0) handle is a no-op. - * - * @param handle Handle obtained from serialOpen(). - * @return 0 on success or a negative error code on failure. - */ - MODULE_API auto serialClose(int64_t handle) -> int; - - /** - * @brief Read raw bytes from the serial port. - * - * The call blocks for at most @p timeout_ms milliseconds while waiting for - * the FIRST byte. For every subsequent byte the individual timeout is - * calculated as `timeout_ms * multiplier`. - * - * @param handle Port handle. - * @param buffer Destination buffer (must not be `nullptr`). - * @param buffer_size Size of @p buffer in bytes (> 0). - * @param timeout_ms Base timeout per byte in milliseconds (applied to the - * first byte as-is; subsequent bytes use - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to @p timeout_ms for every byte after - * the first. 0 -> return immediately after the first byte. - * @return Bytes read (0 on timeout) or a negative error code. - */ - MODULE_API auto serialRead( - int64_t handle, - void *buffer, - int buffer_size, - int timeout_ms, - int multiplier - ) -> int; - - /** - * @brief Read bytes until a terminator character appears. - * - * Semantics are identical to serialRead() but reading stops as soon as the - * byte pointed to by @p until_char has been received. The terminator is part - * of the returned data. - * - * @param handle Port handle. - * @param buffer Destination buffer. - * @param buffer_size Capacity of @p buffer in bytes. - * @param timeout_ms Base timeout per byte in milliseconds (applied to the - * first byte as-is; each additional byte uses - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to the timeout for every additional byte. - * @param until_char Pointer to the terminator character (must not be `nullptr`). - * @return Bytes read (including the terminator), 0 on timeout - * or a negative error code. - */ - MODULE_API auto serialReadUntil( - int64_t handle, - void *buffer, - int buffer_size, - int timeout_ms, - int multiplier, - void *until_char - ) -> int; - - /** - * @brief Write raw bytes to the serial port. - * - * Timeout handling mirrors serialRead(): @p timeout_ms applies to the first - * byte, `timeout_ms * multiplier` to every subsequent one. - * - * @param handle Port handle. - * @param buffer Data to transmit (must not be `nullptr`). - * @param buffer_size Number of bytes in @p buffer (> 0). - * @param timeout_ms Base timeout per byte in milliseconds (applied to the - * first byte as-is; subsequent bytes use - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to the timeout for subsequent bytes. - * @return Bytes written (may be 0 on timeout) or a negative error code. - */ - MODULE_API auto serialWrite( - int64_t handle, - const void *buffer, - int buffer_size, - int timeout_ms, - int multiplier - ) -> int; - - /** - * @brief Enumerate all available serial ports on the system. - * - * The supplied callback is invoked once for every discovered port. All string - * parameters may be `nullptr` if the information is unknown. - * - * @param function Callback receiving port information. - * @return Number of ports found or a negative error code. - */ - MODULE_API auto serialGetPortsInfo( - void (*function)( - const char *port, - const char *path, - const char *manufacturer, - const char *serial_number, - const char *pnp_id, - const char *location_id, - const char *product_id, - const char *vendor_id - ) - ) -> int; - - /** - * @brief Clear (flush) the device's input buffer. - * - * Discards every byte the driver has already received but the application - * has not yet read. - * - * @param handle Port handle. - */ - MODULE_API void serialClearBufferIn(int64_t handle); - - /** - * @brief Clear (flush) the device's output buffer. - * - * Blocks until all queued bytes have been transmitted and then discards any - * remaining data. - * - * @param handle Port handle. - */ - MODULE_API void serialClearBufferOut(int64_t handle); - - /** - * @brief Abort a blocking read operation running in a different thread. - * - * The target read function returns immediately with - * ::cpp_core::StatusCodes::kAbortReadError. - * - * @param handle Port handle. - */ - MODULE_API void serialAbortRead(int64_t handle); - /** - * @brief Abort a blocking write operation running in a different thread. - * - * The target write function returns immediately with - * ::cpp_core::StatusCodes::kAbortWriteError. - * - * @param handle Port handle. - */ - MODULE_API void serialAbortWrite(int64_t handle); - - /** - * @brief Register a callback that is invoked whenever bytes are read. - * - * Pass `nullptr` to disable the callback. - * - * @param callback Function receiving the number of bytes that have just been read. - */ - MODULE_API void serialSetReadCallback(void (*callback)(int bytes_read)); - - /** - * @brief Register a callback that is invoked whenever bytes are written. - * - * Pass `nullptr` to disable the callback. - * - * @param callback Function receiving the number of bytes that have just been written. - */ - MODULE_API void serialSetWriteCallback(void (*callback)(int bytes_written)); - - /** - * @brief Register a callback that is invoked whenever an error occurs. - * - * Pass `nullptr` to disable the callback. - * - * @param callback Function receiving the error code and a textual description. - */ - MODULE_API void serialSetErrorCallback( - void (*callback)( - int error_code, - const char *message - ) - ); - - /** - * @brief Read a single line terminated by '\n'. - * - * Timeout handling is identical to serialRead(); the newline character is - * included in the returned data. - * - * @param handle Port handle. - * @param buffer Destination buffer. - * @param buffer_size Capacity of @p buffer in bytes. - * @param timeout_ms Base timeout per byte in milliseconds (applied to the - * first byte as-is; subsequent bytes use - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to the timeout for subsequent bytes. - * @return Bytes read (0 on timeout) or a negative error code. - */ - MODULE_API auto serialReadLine( - int64_t handle, - void *buffer, - int buffer_size, - int timeout_ms, - int multiplier - ) -> int; - - /** - * @brief Write a buffer followed by a '\n' byte. - * - * Convenience wrapper that adds the line-feed for you and then calls - * `serialWrite()`. - * - * @param handle Port handle. - * @param buffer Data to transmit. - * @param buffer_size Number of bytes in @p buffer. - * @param timeout_ms Base timeout per byte in milliseconds. - * @param multiplier Factor applied to the timeout for bytes after the - * first. - * @return Bytes written (including the newline) or a negative - * error code. - */ - MODULE_API auto serialWriteLine( - int64_t handle, - const void *buffer, - int buffer_size, - int timeout_ms, - int multiplier - ) -> int; - - /** - * @brief Read until a specific byte sequence appears. - * - * Works like serialReadUntil() but supports an arbitrary terminator string. - * The terminator is included in the returned data. - * - * @param handle Port handle. - * @param buffer Destination buffer. - * @param buffer_size Capacity of @p buffer in bytes. - * @param timeout_ms Base timeout per byte in milliseconds (first byte - * uses this value; each additional byte uses - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to the timeout for subsequent bytes. - * @param sequence Pointer to the terminating byte sequence (must not be `nullptr`). - * @return Bytes read (including the terminator) or a negative error code. - */ - MODULE_API auto serialReadUntilSequence( - int64_t handle, - void *buffer, - int buffer_size, - int timeout_ms, - int multiplier, - void *sequence - ) -> int; - - /** - * @brief Total number of bytes transmitted since the port was opened. - * - * @param handle Port handle. - * @return Total number of bytes written. - */ - MODULE_API auto serialOutBytesTotal(int64_t handle) -> int64_t; - - /** - * @brief Total number of bytes received since the port was opened. - * - * @param handle Port handle. - * @return Total number of bytes read. - */ - MODULE_API auto serialInBytesTotal(int64_t handle) -> int64_t; - - /** - * @brief Wait until the operating-system driver has physically sent every queued byte. - * - * The function blocks the *calling thread* until the device driver reports - * that the transmit FIFO is **empty** – i.e. all bytes handed to previous - * `serialWrite*` calls have been shifted out on the wire. It does *not* - * flush higher-level protocol buffers you may have implemented yourself. - * - * Typical use-case: ensure a complete command frame has left the UART - * before toggling RTS/DTR or powering down the device. - * - * @code{.c} - * // Send a frame and make sure it actually hits the line - * serialWrite(h, frame, frame_len, 50, 1); - * if (serialDrain(h) < 0) { - * fprintf(stderr, "drain failed\n"); - * } - * @endcode - * - * @param handle Port handle. - * @return 0 on success; negative ::cpp_core::StatusCodes value on error. - */ - MODULE_API auto serialDrain(int64_t handle) -> int; - - /** - * @brief Query how many bytes can be read *immediately* without blocking. - * - * The number reflects the size of the driver's RX FIFO **after** accounting - * for data already consumed by the application. A value of `0` therefore - * means a read call would have to wait for the next byte to arrive. - * - * @code{.c} - * int pending = serialInBytesWaiting(h); - * if (pending > 0) { - * serialRead(h, buf, pending, 0, 1); // non-blocking read - * } - * @endcode - * - * @param handle Port handle. - * @return Bytes available for instant reading or a negative error code. - */ - MODULE_API auto serialInBytesWaiting(int64_t handle) -> int; - - /** - * @brief Return the number of bytes that have been accepted by the driver but not yet sent. - * - * Useful for gauging transmission progress in the background or for pacing - * further writes to avoid unbounded buffering. - * - * @code{.c} - * while (serialOutBytesWaiting(h) > 0) { - * usleep(1000); // wait 1 ms and poll again - * } - * @endcode - * - * @param handle Port handle. - * @return Bytes still waiting in the TX FIFO or a negative error code. - */ - MODULE_API auto serialOutBytesWaiting(int64_t handle) -> int; +#include "module_api.h" +#include "version.h" -#ifdef __cplusplus -} -#endif +// Aggregated interface headers +#include "interface/get_version.h" +#include "interface/serial_abort_read.h" +#include "interface/serial_abort_write.h" +#include "interface/serial_clear_buffer_in.h" +#include "interface/serial_clear_buffer_out.h" +#include "interface/serial_close.h" +#include "interface/serial_drain.h" +#include "interface/serial_get_ports_info.h" +#include "interface/serial_in_bytes_total.h" +#include "interface/serial_in_bytes_waiting.h" +#include "interface/serial_open.h" +#include "interface/serial_out_bytes_total.h" +#include "interface/serial_out_bytes_waiting.h" +#include "interface/serial_read.h" +#include "interface/serial_read_line.h" +#include "interface/serial_read_until.h" +#include "interface/serial_read_until_sequence.h" +#include "interface/serial_set_error_callback.h" +#include "interface/serial_set_read_callback.h" +#include "interface/serial_set_write_callback.h" +#include "interface/serial_write.h" +#include "interface/serial_write_line.h" From 27ee3a7c2d5915c10b55dcf06eed829516511fa5 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Wed, 9 Jul 2025 20:43:08 +0200 Subject: [PATCH 36/45] Refactor formatting and documentation in cpp_core interface headers - Updated .clang-format to disable alignment of trailing comments. - Reformatted enum values in status_codes.h for improved readability. - Enhanced documentation comments across multiple interface headers to ensure consistent formatting and clarity, particularly in parameter descriptions and return values. These changes aim to improve code readability and maintainability throughout the cpp_core library. --- .clang-format | 2 +- include/cpp_core/interface/get_version.h | 4 +-- include/cpp_core/interface/serial_close.h | 2 +- include/cpp_core/interface/serial_drain.h | 2 +- .../interface/serial_get_ports_info.h | 2 +- .../interface/serial_in_bytes_total.h | 2 +- .../interface/serial_in_bytes_waiting.h | 2 +- include/cpp_core/interface/serial_open.h | 16 +++++------- .../interface/serial_out_bytes_total.h | 2 +- .../interface/serial_out_bytes_waiting.h | 2 +- include/cpp_core/interface/serial_read.h | 17 ++++++------ include/cpp_core/interface/serial_read_line.h | 15 +++++------ .../cpp_core/interface/serial_read_until.h | 18 ++++++------- .../interface/serial_read_until_sequence.h | 17 ++++++------ include/cpp_core/interface/serial_write.h | 15 +++++------ .../cpp_core/interface/serial_write_line.h | 14 +++++----- include/cpp_core/status_codes.h | 26 +++++++++---------- 17 files changed, 74 insertions(+), 84 deletions(-) diff --git a/.clang-format b/.clang-format index 7ff10ef..86cbf0d 100644 --- a/.clang-format +++ b/.clang-format @@ -5,7 +5,7 @@ AccessModifierOffset: -2 AlignAfterOpenBracket: BlockIndent AlignEscapedNewlines: Right AlignOperands: Align -AlignTrailingComments: true +AlignTrailingComments: false AlignConsecutiveAssignments: true AlignConsecutiveDeclarations: true AllowAllArgumentsOnNextLine: true diff --git a/include/cpp_core/interface/get_version.h b/include/cpp_core/interface/get_version.h index 5bf77aa..1092b1b 100644 --- a/include/cpp_core/interface/get_version.h +++ b/include/cpp_core/interface/get_version.h @@ -13,8 +13,8 @@ extern "C" * Writes the version baked into the library at build-time to the structure * pointed to by @p out. If @p out is `nullptr` the call is a no-op. * - * @param[out] out Pointer to a `cpp_core::Version` structure that receives - * the version information. May be `nullptr`. + * @param[out] out Pointer to a `cpp_core::Version` structure that receives the version information. May be + * `nullptr`. */ inline MODULE_API void getVersion(cpp_core::Version *out) { diff --git a/include/cpp_core/interface/serial_close.h b/include/cpp_core/interface/serial_close.h index ca79fbb..1acfd8a 100644 --- a/include/cpp_core/interface/serial_close.h +++ b/include/cpp_core/interface/serial_close.h @@ -14,7 +14,7 @@ extern "C" * (≤ 0) handle is a no-op. * * @param handle Handle obtained from serialOpen(). - * @return 0 on success or a negative error code on failure. + * @return 0 on success or a negative error code on failure. */ MODULE_API auto serialClose(int64_t handle) -> int; diff --git a/include/cpp_core/interface/serial_drain.h b/include/cpp_core/interface/serial_drain.h index bc2b6d6..46be1ed 100644 --- a/include/cpp_core/interface/serial_drain.h +++ b/include/cpp_core/interface/serial_drain.h @@ -27,7 +27,7 @@ extern "C" * @endcode * * @param handle Port handle. - * @return 0 on success; negative ::cpp_core::StatusCodes value on error. + * @return 0 on success; negative ::cpp_core::StatusCodes value on error. */ MODULE_API auto serialDrain(int64_t handle) -> int; diff --git a/include/cpp_core/interface/serial_get_ports_info.h b/include/cpp_core/interface/serial_get_ports_info.h index 20318dc..57ac634 100644 --- a/include/cpp_core/interface/serial_get_ports_info.h +++ b/include/cpp_core/interface/serial_get_ports_info.h @@ -13,7 +13,7 @@ extern "C" * parameters may be `nullptr` if the information is unknown. * * @param function Callback receiving port information. - * @return Number of ports found or a negative error code. + * @return Number of ports found or a negative error code. */ MODULE_API auto serialGetPortsInfo( void (*function)( diff --git a/include/cpp_core/interface/serial_in_bytes_total.h b/include/cpp_core/interface/serial_in_bytes_total.h index b4b892e..2570645 100644 --- a/include/cpp_core/interface/serial_in_bytes_total.h +++ b/include/cpp_core/interface/serial_in_bytes_total.h @@ -11,7 +11,7 @@ extern "C" * @brief Total number of bytes received since the port was opened. * * @param handle Port handle. - * @return Total number of bytes read. + * @return Total number of bytes read. */ MODULE_API auto serialInBytesTotal(int64_t handle) -> int64_t; diff --git a/include/cpp_core/interface/serial_in_bytes_waiting.h b/include/cpp_core/interface/serial_in_bytes_waiting.h index ea9bdaf..0d1a5ba 100644 --- a/include/cpp_core/interface/serial_in_bytes_waiting.h +++ b/include/cpp_core/interface/serial_in_bytes_waiting.h @@ -22,7 +22,7 @@ extern "C" * @endcode * * @param handle Port handle. - * @return Bytes available for instant reading or a negative error code. + * @return Bytes available for instant reading or a negative error code. */ MODULE_API auto serialInBytesWaiting(int64_t handle) -> int; diff --git a/include/cpp_core/interface/serial_open.h b/include/cpp_core/interface/serial_open.h index 1345b6d..7eb4c91 100644 --- a/include/cpp_core/interface/serial_open.h +++ b/include/cpp_core/interface/serial_open.h @@ -15,15 +15,13 @@ extern "C" * - `const char*` on POSIX and * - `const wchar_t*` on Windows. * - * @param port Null-terminated device identifier (e.g. "COM3", - * "/dev/ttyUSB0"). Passing `nullptr` results in - * ::cpp_core::StatusCodes::kNotFoundError. - * @param baudrate Desired baud rate in bit/s (≥ 300). - * @param data_bits Number of data bits (5–8). - * @param parity 0 = none, 1 = even, 2 = odd. - * @param stop_bits 0 = 1 stop bit, 2 = 2 stop bits. - * @return A positive opaque handle on success or a negative value - * from ::cpp_core::StatusCodes on failure. + * @param port Null-terminated device identifier (e.g. "COM3", "/dev/ttyUSB0"). Passing `nullptr` results in + * ::cpp_core::StatusCodes::kNotFoundError. + * @param baudrate Desired baud rate in bit/s (≥ 300). + * @param data_bits Number of data bits (5–8). + * @param parity 0 = none, 1 = even, 2 = odd. + * @param stop_bits 0 = 1 stop bit, 2 = 2 stop bits. + * @return A positive opaque handle on success or a negative value from ::cpp_core::StatusCodes on failure. */ MODULE_API auto serialOpen( void *port, diff --git a/include/cpp_core/interface/serial_out_bytes_total.h b/include/cpp_core/interface/serial_out_bytes_total.h index f34725c..7a9f1c4 100644 --- a/include/cpp_core/interface/serial_out_bytes_total.h +++ b/include/cpp_core/interface/serial_out_bytes_total.h @@ -11,7 +11,7 @@ extern "C" * @brief Total number of bytes transmitted since the port was opened. * * @param handle Port handle. - * @return Total number of bytes written. + * @return Total number of bytes written. */ MODULE_API auto serialOutBytesTotal(int64_t handle) -> int64_t; diff --git a/include/cpp_core/interface/serial_out_bytes_waiting.h b/include/cpp_core/interface/serial_out_bytes_waiting.h index 5d283fe..9db6d6c 100644 --- a/include/cpp_core/interface/serial_out_bytes_waiting.h +++ b/include/cpp_core/interface/serial_out_bytes_waiting.h @@ -20,7 +20,7 @@ extern "C" * @endcode * * @param handle Port handle. - * @return Bytes still waiting in the TX FIFO or a negative error code. + * @return Bytes still waiting in the TX FIFO or a negative error code. */ MODULE_API auto serialOutBytesWaiting(int64_t handle) -> int; diff --git a/include/cpp_core/interface/serial_read.h b/include/cpp_core/interface/serial_read.h index a160cb2..9b13ea4 100644 --- a/include/cpp_core/interface/serial_read.h +++ b/include/cpp_core/interface/serial_read.h @@ -14,15 +14,14 @@ extern "C" * the FIRST byte. For every subsequent byte the individual timeout is * calculated as `timeout_ms * multiplier`. * - * @param handle Port handle. - * @param buffer Destination buffer (must not be `nullptr`). - * @param buffer_size Size of @p buffer in bytes (> 0). - * @param timeout_ms Base timeout per byte in milliseconds (applied to the - * first byte as-is; subsequent bytes use - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to @p timeout_ms for every byte after - * the first. 0 -> return immediately after the first byte. - * @return Bytes read (0 on timeout) or a negative error code. + * @param handle Port handle. + * @param buffer Destination buffer (must not be `nullptr`). + * @param buffer_size Size of @p buffer in bytes (> 0). + * @param timeout_ms Base timeout per byte in milliseconds (applied to the first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to @p timeout_ms for every byte after the first. 0 -> return immediately after + * the first byte. + * @return Bytes read (0 on timeout) or a negative error code. */ MODULE_API auto serialRead( int64_t handle, diff --git a/include/cpp_core/interface/serial_read_line.h b/include/cpp_core/interface/serial_read_line.h index d68f606..9b169e9 100644 --- a/include/cpp_core/interface/serial_read_line.h +++ b/include/cpp_core/interface/serial_read_line.h @@ -13,14 +13,13 @@ extern "C" * Timeout handling is identical to serialRead(); the newline character is * included in the returned data. * - * @param handle Port handle. - * @param buffer Destination buffer. - * @param buffer_size Capacity of @p buffer in bytes. - * @param timeout_ms Base timeout per byte in milliseconds (applied to the - * first byte as-is; subsequent bytes use - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to the timeout for subsequent bytes. - * @return Bytes read (0 on timeout) or a negative error code. + * @param handle Port handle. + * @param buffer Destination buffer. + * @param buffer_size Capacity of @p buffer in bytes. + * @param timeout_ms Base timeout per byte in milliseconds (applied to the first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @return Bytes read (0 on timeout) or a negative error code. */ MODULE_API auto serialReadLine( int64_t handle, diff --git a/include/cpp_core/interface/serial_read_until.h b/include/cpp_core/interface/serial_read_until.h index ad3f902..87d451b 100644 --- a/include/cpp_core/interface/serial_read_until.h +++ b/include/cpp_core/interface/serial_read_until.h @@ -14,16 +14,14 @@ extern "C" * byte pointed to by @p until_char has been received. The terminator is part * of the returned data. * - * @param handle Port handle. - * @param buffer Destination buffer. - * @param buffer_size Capacity of @p buffer in bytes. - * @param timeout_ms Base timeout per byte in milliseconds (applied to the - * first byte as-is; each additional byte uses - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to the timeout for every additional byte. - * @param until_char Pointer to the terminator character (must not be `nullptr`). - * @return Bytes read (including the terminator), 0 on timeout - * or a negative error code. + * @param handle Port handle. + * @param buffer Destination buffer. + * @param buffer_size Capacity of @p buffer in bytes. + * @param timeout_ms Base timeout per byte in milliseconds (applied to the first byte as-is; each additional byte + * uses `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for every additional byte. + * @param until_char Pointer to the terminator character (must not be `nullptr`). + * @return Bytes read (including the terminator), 0 on timeout or a negative error code. */ MODULE_API auto serialReadUntil( int64_t handle, diff --git a/include/cpp_core/interface/serial_read_until_sequence.h b/include/cpp_core/interface/serial_read_until_sequence.h index 8369b8e..6147481 100644 --- a/include/cpp_core/interface/serial_read_until_sequence.h +++ b/include/cpp_core/interface/serial_read_until_sequence.h @@ -13,15 +13,14 @@ extern "C" * Works like serialReadUntil() but supports an arbitrary terminator string. * The terminator is included in the returned data. * - * @param handle Port handle. - * @param buffer Destination buffer. - * @param buffer_size Capacity of @p buffer in bytes. - * @param timeout_ms Base timeout per byte in milliseconds (first byte - * uses this value; each additional byte uses - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to the timeout for subsequent bytes. - * @param sequence Pointer to the terminating byte sequence (must not be `nullptr`). - * @return Bytes read (including the terminator) or a negative error code. + * @param handle Port handle. + * @param buffer Destination buffer. + * @param buffer_size Capacity of @p buffer in bytes. + * @param timeout_ms Base timeout per byte in milliseconds (first byte uses this value; each additional byte uses + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @param sequence Pointer to the terminating byte sequence (must not be `nullptr`). + * @return Bytes read (including the terminator) or a negative error code. */ MODULE_API auto serialReadUntilSequence( int64_t handle, diff --git a/include/cpp_core/interface/serial_write.h b/include/cpp_core/interface/serial_write.h index 1a559d8..62fb8b7 100644 --- a/include/cpp_core/interface/serial_write.h +++ b/include/cpp_core/interface/serial_write.h @@ -13,14 +13,13 @@ extern "C" * Timeout handling mirrors serialRead(): @p timeout_ms applies to the first * byte, `timeout_ms * multiplier` to every subsequent one. * - * @param handle Port handle. - * @param buffer Data to transmit (must not be `nullptr`). - * @param buffer_size Number of bytes in @p buffer (> 0). - * @param timeout_ms Base timeout per byte in milliseconds (applied to the - * first byte as-is; subsequent bytes use - * `timeout_ms * multiplier`). - * @param multiplier Factor applied to the timeout for subsequent bytes. - * @return Bytes written (may be 0 on timeout) or a negative error code. + * @param handle Port handle. + * @param buffer Data to transmit (must not be `nullptr`). + * @param buffer_size Number of bytes in @p buffer (> 0). + * @param timeout_ms Base timeout per byte in milliseconds (applied to the first byte as-is; subsequent bytes use + * `timeout_ms * multiplier`). + * @param multiplier Factor applied to the timeout for subsequent bytes. + * @return Bytes written (may be 0 on timeout) or a negative error code. */ MODULE_API auto serialWrite( int64_t handle, diff --git a/include/cpp_core/interface/serial_write_line.h b/include/cpp_core/interface/serial_write_line.h index 14f6e25..612dc82 100644 --- a/include/cpp_core/interface/serial_write_line.h +++ b/include/cpp_core/interface/serial_write_line.h @@ -13,14 +13,12 @@ extern "C" * Convenience wrapper that adds the line-feed for you and then calls * `serialWrite()`. * - * @param handle Port handle. - * @param buffer Data to transmit. - * @param buffer_size Number of bytes in @p buffer. - * @param timeout_ms Base timeout per byte in milliseconds. - * @param multiplier Factor applied to the timeout for bytes after the - * first. - * @return Bytes written (including the newline) or a negative - * error code. + * @param handle Port handle. + * @param buffer Data to transmit. + * @param buffer_size Number of bytes in @p buffer. + * @param timeout_ms Base timeout per byte in milliseconds. + * @param multiplier Factor applied to the timeout for bytes after the first. + * @return Bytes written (including the newline) or a negative error code. */ MODULE_API auto serialWriteLine( int64_t handle, diff --git a/include/cpp_core/status_codes.h b/include/cpp_core/status_codes.h index 46c5bc3..11b45c9 100644 --- a/include/cpp_core/status_codes.h +++ b/include/cpp_core/status_codes.h @@ -4,19 +4,19 @@ namespace cpp_core { enum class StatusCodes { - kSuccess = 0, - kCloseHandleError = -1, - kInvalidHandleError = -2, - kReadError = -3, - kWriteError = -4, - kGetStateError = -5, - kSetStateError = -6, - kSetTimeoutError = -7, - kBufferError = -8, - kNotFoundError = -9, - kClearBufferInError = -10, + kSuccess = 0, + kCloseHandleError = -1, + kInvalidHandleError = -2, + kReadError = -3, + kWriteError = -4, + kGetStateError = -5, + kSetStateError = -6, + kSetTimeoutError = -7, + kBufferError = -8, + kNotFoundError = -9, + kClearBufferInError = -10, kClearBufferOutError = -11, - kAbortReadError = -12, - kAbortWriteError = -13, + kAbortReadError = -12, + kAbortWriteError = -13, }; } // namespace cpp_core From 4bbad79a01885e28f7e12f549c5e0f9b6e0a28b3 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Wed, 9 Jul 2025 22:51:50 +0200 Subject: [PATCH 37/45] Remove serialWriteLine function and its header from cpp_core library - Deleted the `serial_write_line.h` header file, which contained the `serialWriteLine` function definition. - Updated `serial.h` to remove the inclusion of the deleted header. This change streamlines the serial API by eliminating an unused function, enhancing maintainability. --- .../cpp_core/interface/serial_write_line.h | 33 ------------------- include/cpp_core/serial.h | 1 - 2 files changed, 34 deletions(-) delete mode 100644 include/cpp_core/interface/serial_write_line.h diff --git a/include/cpp_core/interface/serial_write_line.h b/include/cpp_core/interface/serial_write_line.h deleted file mode 100644 index 612dc82..0000000 --- a/include/cpp_core/interface/serial_write_line.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once -#include "../module_api.h" -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - - /** - * @brief Write a buffer followed by a '\n' byte. - * - * Convenience wrapper that adds the line-feed for you and then calls - * `serialWrite()`. - * - * @param handle Port handle. - * @param buffer Data to transmit. - * @param buffer_size Number of bytes in @p buffer. - * @param timeout_ms Base timeout per byte in milliseconds. - * @param multiplier Factor applied to the timeout for bytes after the first. - * @return Bytes written (including the newline) or a negative error code. - */ - MODULE_API auto serialWriteLine( - int64_t handle, - const void *buffer, - int buffer_size, - int timeout_ms, - int multiplier - ) -> int; - -#ifdef __cplusplus -} -#endif diff --git a/include/cpp_core/serial.h b/include/cpp_core/serial.h index 3f3ecad..e7e142a 100644 --- a/include/cpp_core/serial.h +++ b/include/cpp_core/serial.h @@ -25,4 +25,3 @@ #include "interface/serial_set_read_callback.h" #include "interface/serial_set_write_callback.h" #include "interface/serial_write.h" -#include "interface/serial_write_line.h" From 6c124eb07f1d0ec3f44605308d8922fa3a83e368 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Thu, 10 Jul 2025 09:13:56 +0200 Subject: [PATCH 38/45] Update include/cpp_core/interface/serial_get_ports_info.h Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/interface/serial_get_ports_info.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/cpp_core/interface/serial_get_ports_info.h b/include/cpp_core/interface/serial_get_ports_info.h index 57ac634..d890a1b 100644 --- a/include/cpp_core/interface/serial_get_ports_info.h +++ b/include/cpp_core/interface/serial_get_ports_info.h @@ -16,7 +16,7 @@ extern "C" * @return Number of ports found or a negative error code. */ MODULE_API auto serialGetPortsInfo( - void (*function)( + void (*callback_fn)( const char *port, const char *path, const char *manufacturer, From a3460c8c0a95d2a4144a48cc40bdee292fd861a5 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Thu, 10 Jul 2025 09:18:02 +0200 Subject: [PATCH 39/45] Update include/cpp_core/interface/serial_set_error_callback.h Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/interface/serial_set_error_callback.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/cpp_core/interface/serial_set_error_callback.h b/include/cpp_core/interface/serial_set_error_callback.h index e636ccf..bc86d70 100644 --- a/include/cpp_core/interface/serial_set_error_callback.h +++ b/include/cpp_core/interface/serial_set_error_callback.h @@ -14,7 +14,7 @@ extern "C" * @param callback Function receiving the error code and a textual description. */ MODULE_API void serialSetErrorCallback( - void (*callback)( + void (*callback_fn)( int error_code, const char *message ) From a7ed56436684dce9ea6f1842ca277c9dc4ca3971 Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Thu, 10 Jul 2025 09:18:25 +0200 Subject: [PATCH 40/45] Update include/cpp_core/interface/serial_set_read_callback.h Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/interface/serial_set_read_callback.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/cpp_core/interface/serial_set_read_callback.h b/include/cpp_core/interface/serial_set_read_callback.h index 6e548e9..2b45ae0 100644 --- a/include/cpp_core/interface/serial_set_read_callback.h +++ b/include/cpp_core/interface/serial_set_read_callback.h @@ -13,7 +13,7 @@ extern "C" * * @param callback Function receiving the number of bytes that have just been read. */ - MODULE_API void serialSetReadCallback(void (*callback)(int bytes_read)); + MODULE_API void serialSetReadCallback(void (*callback_fn)(int bytes_read)); #ifdef __cplusplus } From fe273d8f03d11017adc6a135f5e1930c995a504f Mon Sep 17 00:00:00 2001 From: Katze719 <38188106+Katze719@users.noreply.github.com> Date: Thu, 10 Jul 2025 09:18:38 +0200 Subject: [PATCH 41/45] Update include/cpp_core/interface/serial_set_write_callback.h Co-authored-by: Mqx <62719703+Mqxx@users.noreply.github.com> --- include/cpp_core/interface/serial_set_write_callback.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/cpp_core/interface/serial_set_write_callback.h b/include/cpp_core/interface/serial_set_write_callback.h index 4470090..a521e40 100644 --- a/include/cpp_core/interface/serial_set_write_callback.h +++ b/include/cpp_core/interface/serial_set_write_callback.h @@ -13,7 +13,7 @@ extern "C" * * @param callback Function receiving the number of bytes that have just been written. */ - MODULE_API void serialSetWriteCallback(void (*callback)(int bytes_written)); + MODULE_API void serialSetWriteCallback(void (*callback_fn)(int bytes_written)); #ifdef __cplusplus } From 1bd6256a1336c9e620e2a414f12051392c03137a Mon Sep 17 00:00:00 2001 From: Katze719 Date: Thu, 10 Jul 2025 16:46:25 +0200 Subject: [PATCH 42/45] Add error callback support to serial interface functions - Introduced `ErrorCallbackT` type and added error callback parameter to multiple serial interface functions, enhancing error handling capabilities. - Updated documentation to reflect changes in return values and parameters across various headers, ensuring clarity and consistency. This update improves the robustness of the serial API by allowing users to handle errors more effectively. --- include/cpp_core.h | 1 + include/cpp_core/error_callback.h | 15 +++++++++++++++ include/cpp_core/interface/serial_abort_read.h | 7 ++++++- include/cpp_core/interface/serial_abort_write.h | 7 ++++++- .../cpp_core/interface/serial_clear_buffer_in.h | 7 ++++++- .../cpp_core/interface/serial_clear_buffer_out.h | 7 ++++++- include/cpp_core/interface/serial_close.h | 6 +++++- include/cpp_core/interface/serial_drain.h | 6 +++++- .../cpp_core/interface/serial_get_ports_info.h | 4 +++- .../cpp_core/interface/serial_in_bytes_total.h | 2 +- .../cpp_core/interface/serial_in_bytes_waiting.h | 6 +++++- include/cpp_core/interface/serial_open.h | 12 +++++++----- .../cpp_core/interface/serial_out_bytes_total.h | 2 +- .../cpp_core/interface/serial_out_bytes_waiting.h | 6 +++++- include/cpp_core/interface/serial_read.h | 12 +++++++----- include/cpp_core/interface/serial_read_line.h | 12 +++++++----- include/cpp_core/interface/serial_read_until.h | 14 ++++++++------ .../interface/serial_read_until_sequence.h | 14 ++++++++------ .../interface/serial_set_error_callback.h | 8 ++------ include/cpp_core/interface/serial_write.h | 12 +++++++----- 20 files changed, 111 insertions(+), 49 deletions(-) create mode 100644 include/cpp_core/error_callback.h diff --git a/include/cpp_core.h b/include/cpp_core.h index 7ecd117..1f50732 100644 --- a/include/cpp_core.h +++ b/include/cpp_core.h @@ -12,6 +12,7 @@ * offers the most convenient entry point. */ +#include "cpp_core/error_callback.h" #include "cpp_core/serial.h" #include "cpp_core/status_codes.h" #include "cpp_core/version.h" diff --git a/include/cpp_core/error_callback.h b/include/cpp_core/error_callback.h new file mode 100644 index 0000000..3217320 --- /dev/null +++ b/include/cpp_core/error_callback.h @@ -0,0 +1,15 @@ +#pragma once + +#ifdef __cplusplus +extern "C" +{ +#endif + + using ErrorCallbackT = void (*)( + int error_code, + const char *message + ); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/include/cpp_core/interface/serial_abort_read.h b/include/cpp_core/interface/serial_abort_read.h index 264477f..99b153d 100644 --- a/include/cpp_core/interface/serial_abort_read.h +++ b/include/cpp_core/interface/serial_abort_read.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -14,8 +15,12 @@ extern "C" * ::cpp_core::StatusCodes::kAbortReadError. * * @param handle Port handle. + * @return 0 on success or a negative error code on failure. */ - MODULE_API void serialAbortRead(int64_t handle); + MODULE_API auto serialAbortRead( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_abort_write.h b/include/cpp_core/interface/serial_abort_write.h index 52740ca..a0797b4 100644 --- a/include/cpp_core/interface/serial_abort_write.h +++ b/include/cpp_core/interface/serial_abort_write.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -14,8 +15,12 @@ extern "C" * ::cpp_core::StatusCodes::kAbortWriteError. * * @param handle Port handle. + * @return 0 on success or a negative error code on failure. */ - MODULE_API void serialAbortWrite(int64_t handle); + MODULE_API auto serialAbortWrite( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_clear_buffer_in.h b/include/cpp_core/interface/serial_clear_buffer_in.h index 20497ca..a5699ec 100644 --- a/include/cpp_core/interface/serial_clear_buffer_in.h +++ b/include/cpp_core/interface/serial_clear_buffer_in.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -14,8 +15,12 @@ extern "C" * has not yet read. * * @param handle Port handle. + * @return 0 on success or a negative error code on failure. */ - MODULE_API void serialClearBufferIn(int64_t handle); + MODULE_API auto serialClearBufferIn( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_clear_buffer_out.h b/include/cpp_core/interface/serial_clear_buffer_out.h index 6737597..04bf044 100644 --- a/include/cpp_core/interface/serial_clear_buffer_out.h +++ b/include/cpp_core/interface/serial_clear_buffer_out.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -14,8 +15,12 @@ extern "C" * remaining data. * * @param handle Port handle. + * @return 0 on success or a negative error code on failure. */ - MODULE_API void serialClearBufferOut(int64_t handle); + MODULE_API auto serialClearBufferOut( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_close.h b/include/cpp_core/interface/serial_close.h index 1acfd8a..996be6a 100644 --- a/include/cpp_core/interface/serial_close.h +++ b/include/cpp_core/interface/serial_close.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -16,7 +17,10 @@ extern "C" * @param handle Handle obtained from serialOpen(). * @return 0 on success or a negative error code on failure. */ - MODULE_API auto serialClose(int64_t handle) -> int; + MODULE_API auto serialClose( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_drain.h b/include/cpp_core/interface/serial_drain.h index 46be1ed..71cd328 100644 --- a/include/cpp_core/interface/serial_drain.h +++ b/include/cpp_core/interface/serial_drain.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -29,7 +30,10 @@ extern "C" * @param handle Port handle. * @return 0 on success; negative ::cpp_core::StatusCodes value on error. */ - MODULE_API auto serialDrain(int64_t handle) -> int; + MODULE_API auto serialDrain( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_get_ports_info.h b/include/cpp_core/interface/serial_get_ports_info.h index d890a1b..1a726cf 100644 --- a/include/cpp_core/interface/serial_get_ports_info.h +++ b/include/cpp_core/interface/serial_get_ports_info.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #ifdef __cplusplus @@ -25,7 +26,8 @@ extern "C" const char *location_id, const char *product_id, const char *vendor_id - ) + ), + ErrorCallbackT error_callback = nullptr ) -> int; #ifdef __cplusplus diff --git a/include/cpp_core/interface/serial_in_bytes_total.h b/include/cpp_core/interface/serial_in_bytes_total.h index 2570645..483fa84 100644 --- a/include/cpp_core/interface/serial_in_bytes_total.h +++ b/include/cpp_core/interface/serial_in_bytes_total.h @@ -11,7 +11,7 @@ extern "C" * @brief Total number of bytes received since the port was opened. * * @param handle Port handle. - * @return Total number of bytes read. + * @return Total number of bytes read or a negative error code. */ MODULE_API auto serialInBytesTotal(int64_t handle) -> int64_t; diff --git a/include/cpp_core/interface/serial_in_bytes_waiting.h b/include/cpp_core/interface/serial_in_bytes_waiting.h index 0d1a5ba..31ad403 100644 --- a/include/cpp_core/interface/serial_in_bytes_waiting.h +++ b/include/cpp_core/interface/serial_in_bytes_waiting.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -24,7 +25,10 @@ extern "C" * @param handle Port handle. * @return Bytes available for instant reading or a negative error code. */ - MODULE_API auto serialInBytesWaiting(int64_t handle) -> int; + MODULE_API auto serialInBytesWaiting( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_open.h b/include/cpp_core/interface/serial_open.h index 7eb4c91..511aa34 100644 --- a/include/cpp_core/interface/serial_open.h +++ b/include/cpp_core/interface/serial_open.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -24,11 +25,12 @@ extern "C" * @return A positive opaque handle on success or a negative value from ::cpp_core::StatusCodes on failure. */ MODULE_API auto serialOpen( - void *port, - int baudrate, - int data_bits, - int parity = 0, - int stop_bits = 0 + void *port, + int baudrate, + int data_bits, + int parity = 0, + int stop_bits = 0, + ErrorCallbackT error_callback = nullptr ) -> intptr_t; #ifdef __cplusplus diff --git a/include/cpp_core/interface/serial_out_bytes_total.h b/include/cpp_core/interface/serial_out_bytes_total.h index 7a9f1c4..712e3ce 100644 --- a/include/cpp_core/interface/serial_out_bytes_total.h +++ b/include/cpp_core/interface/serial_out_bytes_total.h @@ -11,7 +11,7 @@ extern "C" * @brief Total number of bytes transmitted since the port was opened. * * @param handle Port handle. - * @return Total number of bytes written. + * @return Total number of bytes written or a negative error code. */ MODULE_API auto serialOutBytesTotal(int64_t handle) -> int64_t; diff --git a/include/cpp_core/interface/serial_out_bytes_waiting.h b/include/cpp_core/interface/serial_out_bytes_waiting.h index 9db6d6c..14aaaf5 100644 --- a/include/cpp_core/interface/serial_out_bytes_waiting.h +++ b/include/cpp_core/interface/serial_out_bytes_waiting.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -22,7 +23,10 @@ extern "C" * @param handle Port handle. * @return Bytes still waiting in the TX FIFO or a negative error code. */ - MODULE_API auto serialOutBytesWaiting(int64_t handle) -> int; + MODULE_API auto serialOutBytesWaiting( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_read.h b/include/cpp_core/interface/serial_read.h index 9b13ea4..a2cacd0 100644 --- a/include/cpp_core/interface/serial_read.h +++ b/include/cpp_core/interface/serial_read.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -24,11 +25,12 @@ extern "C" * @return Bytes read (0 on timeout) or a negative error code. */ MODULE_API auto serialRead( - int64_t handle, - void *buffer, - int buffer_size, - int timeout_ms, - int multiplier + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier, + ErrorCallbackT error_callback = nullptr ) -> int; #ifdef __cplusplus diff --git a/include/cpp_core/interface/serial_read_line.h b/include/cpp_core/interface/serial_read_line.h index 9b169e9..059de43 100644 --- a/include/cpp_core/interface/serial_read_line.h +++ b/include/cpp_core/interface/serial_read_line.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -22,11 +23,12 @@ extern "C" * @return Bytes read (0 on timeout) or a negative error code. */ MODULE_API auto serialReadLine( - int64_t handle, - void *buffer, - int buffer_size, - int timeout_ms, - int multiplier + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier, + ErrorCallbackT error_callback = nullptr ) -> int; #ifdef __cplusplus diff --git a/include/cpp_core/interface/serial_read_until.h b/include/cpp_core/interface/serial_read_until.h index 87d451b..2d553dd 100644 --- a/include/cpp_core/interface/serial_read_until.h +++ b/include/cpp_core/interface/serial_read_until.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -24,12 +25,13 @@ extern "C" * @return Bytes read (including the terminator), 0 on timeout or a negative error code. */ MODULE_API auto serialReadUntil( - int64_t handle, - void *buffer, - int buffer_size, - int timeout_ms, - int multiplier, - void *until_char + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier, + void *until_char, + ErrorCallbackT error_callback = nullptr ) -> int; #ifdef __cplusplus diff --git a/include/cpp_core/interface/serial_read_until_sequence.h b/include/cpp_core/interface/serial_read_until_sequence.h index 6147481..e5ebf81 100644 --- a/include/cpp_core/interface/serial_read_until_sequence.h +++ b/include/cpp_core/interface/serial_read_until_sequence.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -23,12 +24,13 @@ extern "C" * @return Bytes read (including the terminator) or a negative error code. */ MODULE_API auto serialReadUntilSequence( - int64_t handle, - void *buffer, - int buffer_size, - int timeout_ms, - int multiplier, - void *sequence + int64_t handle, + void *buffer, + int buffer_size, + int timeout_ms, + int multiplier, + void *sequence, + ErrorCallbackT error_callback = nullptr ) -> int; #ifdef __cplusplus diff --git a/include/cpp_core/interface/serial_set_error_callback.h b/include/cpp_core/interface/serial_set_error_callback.h index bc86d70..e4c143e 100644 --- a/include/cpp_core/interface/serial_set_error_callback.h +++ b/include/cpp_core/interface/serial_set_error_callback.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #ifdef __cplusplus @@ -13,12 +14,7 @@ extern "C" * * @param callback Function receiving the error code and a textual description. */ - MODULE_API void serialSetErrorCallback( - void (*callback_fn)( - int error_code, - const char *message - ) - ); + MODULE_API void serialSetErrorCallback(ErrorCallbackT error_callback); #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_write.h b/include/cpp_core/interface/serial_write.h index 62fb8b7..13c32b2 100644 --- a/include/cpp_core/interface/serial_write.h +++ b/include/cpp_core/interface/serial_write.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -22,11 +23,12 @@ extern "C" * @return Bytes written (may be 0 on timeout) or a negative error code. */ MODULE_API auto serialWrite( - int64_t handle, - const void *buffer, - int buffer_size, - int timeout_ms, - int multiplier + int64_t handle, + const void *buffer, + int buffer_size, + int timeout_ms, + int multiplier, + ErrorCallbackT error_callback = nullptr ) -> int; #ifdef __cplusplus From bb57b7c87143f83e52aff3299b9f91633aa594a1 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Thu, 10 Jul 2025 16:55:22 +0200 Subject: [PATCH 43/45] Add optional error callback parameter to serial interface functions - Enhanced multiple serial interface functions by adding an optional `error_callback` parameter, allowing users to handle errors more effectively. - Updated documentation across various headers to reflect the new parameter, ensuring clarity and consistency. This change improves the robustness of the serial API by providing better error handling capabilities. --- include/cpp_core/interface/serial_abort_read.h | 1 + include/cpp_core/interface/serial_abort_write.h | 1 + include/cpp_core/interface/serial_clear_buffer_in.h | 1 + include/cpp_core/interface/serial_clear_buffer_out.h | 1 + include/cpp_core/interface/serial_close.h | 1 + include/cpp_core/interface/serial_drain.h | 1 + include/cpp_core/interface/serial_get_ports_info.h | 3 ++- include/cpp_core/interface/serial_in_bytes_total.h | 7 ++++++- include/cpp_core/interface/serial_in_bytes_waiting.h | 1 + include/cpp_core/interface/serial_open.h | 1 + include/cpp_core/interface/serial_out_bytes_total.h | 7 ++++++- include/cpp_core/interface/serial_out_bytes_waiting.h | 1 + include/cpp_core/interface/serial_read.h | 1 + include/cpp_core/interface/serial_read_line.h | 1 + include/cpp_core/interface/serial_read_until.h | 1 + include/cpp_core/interface/serial_read_until_sequence.h | 1 + include/cpp_core/interface/serial_set_error_callback.h | 3 ++- include/cpp_core/interface/serial_write.h | 1 + 18 files changed, 30 insertions(+), 4 deletions(-) diff --git a/include/cpp_core/interface/serial_abort_read.h b/include/cpp_core/interface/serial_abort_read.h index 99b153d..5e00720 100644 --- a/include/cpp_core/interface/serial_abort_read.h +++ b/include/cpp_core/interface/serial_abort_read.h @@ -15,6 +15,7 @@ extern "C" * ::cpp_core::StatusCodes::kAbortReadError. * * @param handle Port handle. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return 0 on success or a negative error code on failure. */ MODULE_API auto serialAbortRead( diff --git a/include/cpp_core/interface/serial_abort_write.h b/include/cpp_core/interface/serial_abort_write.h index a0797b4..7f4e3fa 100644 --- a/include/cpp_core/interface/serial_abort_write.h +++ b/include/cpp_core/interface/serial_abort_write.h @@ -15,6 +15,7 @@ extern "C" * ::cpp_core::StatusCodes::kAbortWriteError. * * @param handle Port handle. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return 0 on success or a negative error code on failure. */ MODULE_API auto serialAbortWrite( diff --git a/include/cpp_core/interface/serial_clear_buffer_in.h b/include/cpp_core/interface/serial_clear_buffer_in.h index a5699ec..64fcfa3 100644 --- a/include/cpp_core/interface/serial_clear_buffer_in.h +++ b/include/cpp_core/interface/serial_clear_buffer_in.h @@ -15,6 +15,7 @@ extern "C" * has not yet read. * * @param handle Port handle. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return 0 on success or a negative error code on failure. */ MODULE_API auto serialClearBufferIn( diff --git a/include/cpp_core/interface/serial_clear_buffer_out.h b/include/cpp_core/interface/serial_clear_buffer_out.h index 04bf044..e686a68 100644 --- a/include/cpp_core/interface/serial_clear_buffer_out.h +++ b/include/cpp_core/interface/serial_clear_buffer_out.h @@ -15,6 +15,7 @@ extern "C" * remaining data. * * @param handle Port handle. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return 0 on success or a negative error code on failure. */ MODULE_API auto serialClearBufferOut( diff --git a/include/cpp_core/interface/serial_close.h b/include/cpp_core/interface/serial_close.h index 996be6a..149fa1b 100644 --- a/include/cpp_core/interface/serial_close.h +++ b/include/cpp_core/interface/serial_close.h @@ -15,6 +15,7 @@ extern "C" * (≤ 0) handle is a no-op. * * @param handle Handle obtained from serialOpen(). + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return 0 on success or a negative error code on failure. */ MODULE_API auto serialClose( diff --git a/include/cpp_core/interface/serial_drain.h b/include/cpp_core/interface/serial_drain.h index 71cd328..7f9115e 100644 --- a/include/cpp_core/interface/serial_drain.h +++ b/include/cpp_core/interface/serial_drain.h @@ -28,6 +28,7 @@ extern "C" * @endcode * * @param handle Port handle. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return 0 on success; negative ::cpp_core::StatusCodes value on error. */ MODULE_API auto serialDrain( diff --git a/include/cpp_core/interface/serial_get_ports_info.h b/include/cpp_core/interface/serial_get_ports_info.h index 1a726cf..a1287b2 100644 --- a/include/cpp_core/interface/serial_get_ports_info.h +++ b/include/cpp_core/interface/serial_get_ports_info.h @@ -13,7 +13,8 @@ extern "C" * The supplied callback is invoked once for every discovered port. All string * parameters may be `nullptr` if the information is unknown. * - * @param function Callback receiving port information. + * @param callback_fn Callback receiving port information. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Number of ports found or a negative error code. */ MODULE_API auto serialGetPortsInfo( diff --git a/include/cpp_core/interface/serial_in_bytes_total.h b/include/cpp_core/interface/serial_in_bytes_total.h index 483fa84..2cce953 100644 --- a/include/cpp_core/interface/serial_in_bytes_total.h +++ b/include/cpp_core/interface/serial_in_bytes_total.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -11,9 +12,13 @@ extern "C" * @brief Total number of bytes received since the port was opened. * * @param handle Port handle. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Total number of bytes read or a negative error code. */ - MODULE_API auto serialInBytesTotal(int64_t handle) -> int64_t; + MODULE_API auto serialInBytesTotal( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int64_t; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_in_bytes_waiting.h b/include/cpp_core/interface/serial_in_bytes_waiting.h index 31ad403..b0a9006 100644 --- a/include/cpp_core/interface/serial_in_bytes_waiting.h +++ b/include/cpp_core/interface/serial_in_bytes_waiting.h @@ -23,6 +23,7 @@ extern "C" * @endcode * * @param handle Port handle. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Bytes available for instant reading or a negative error code. */ MODULE_API auto serialInBytesWaiting( diff --git a/include/cpp_core/interface/serial_open.h b/include/cpp_core/interface/serial_open.h index 511aa34..1ba0fa1 100644 --- a/include/cpp_core/interface/serial_open.h +++ b/include/cpp_core/interface/serial_open.h @@ -22,6 +22,7 @@ extern "C" * @param data_bits Number of data bits (5–8). * @param parity 0 = none, 1 = even, 2 = odd. * @param stop_bits 0 = 1 stop bit, 2 = 2 stop bits. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return A positive opaque handle on success or a negative value from ::cpp_core::StatusCodes on failure. */ MODULE_API auto serialOpen( diff --git a/include/cpp_core/interface/serial_out_bytes_total.h b/include/cpp_core/interface/serial_out_bytes_total.h index 712e3ce..3c7f814 100644 --- a/include/cpp_core/interface/serial_out_bytes_total.h +++ b/include/cpp_core/interface/serial_out_bytes_total.h @@ -1,4 +1,5 @@ #pragma once +#include "../error_callback.h" #include "../module_api.h" #include @@ -11,9 +12,13 @@ extern "C" * @brief Total number of bytes transmitted since the port was opened. * * @param handle Port handle. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Total number of bytes written or a negative error code. */ - MODULE_API auto serialOutBytesTotal(int64_t handle) -> int64_t; + MODULE_API auto serialOutBytesTotal( + int64_t handle, + ErrorCallbackT error_callback = nullptr + ) -> int64_t; #ifdef __cplusplus } diff --git a/include/cpp_core/interface/serial_out_bytes_waiting.h b/include/cpp_core/interface/serial_out_bytes_waiting.h index 14aaaf5..b388c86 100644 --- a/include/cpp_core/interface/serial_out_bytes_waiting.h +++ b/include/cpp_core/interface/serial_out_bytes_waiting.h @@ -21,6 +21,7 @@ extern "C" * @endcode * * @param handle Port handle. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Bytes still waiting in the TX FIFO or a negative error code. */ MODULE_API auto serialOutBytesWaiting( diff --git a/include/cpp_core/interface/serial_read.h b/include/cpp_core/interface/serial_read.h index a2cacd0..6feaf33 100644 --- a/include/cpp_core/interface/serial_read.h +++ b/include/cpp_core/interface/serial_read.h @@ -22,6 +22,7 @@ extern "C" * `timeout_ms * multiplier`). * @param multiplier Factor applied to @p timeout_ms for every byte after the first. 0 -> return immediately after * the first byte. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Bytes read (0 on timeout) or a negative error code. */ MODULE_API auto serialRead( diff --git a/include/cpp_core/interface/serial_read_line.h b/include/cpp_core/interface/serial_read_line.h index 059de43..45cd56c 100644 --- a/include/cpp_core/interface/serial_read_line.h +++ b/include/cpp_core/interface/serial_read_line.h @@ -20,6 +20,7 @@ extern "C" * @param timeout_ms Base timeout per byte in milliseconds (applied to the first byte as-is; subsequent bytes use * `timeout_ms * multiplier`). * @param multiplier Factor applied to the timeout for subsequent bytes. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Bytes read (0 on timeout) or a negative error code. */ MODULE_API auto serialReadLine( diff --git a/include/cpp_core/interface/serial_read_until.h b/include/cpp_core/interface/serial_read_until.h index 2d553dd..229b8b8 100644 --- a/include/cpp_core/interface/serial_read_until.h +++ b/include/cpp_core/interface/serial_read_until.h @@ -22,6 +22,7 @@ extern "C" * uses `timeout_ms * multiplier`). * @param multiplier Factor applied to the timeout for every additional byte. * @param until_char Pointer to the terminator character (must not be `nullptr`). + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Bytes read (including the terminator), 0 on timeout or a negative error code. */ MODULE_API auto serialReadUntil( diff --git a/include/cpp_core/interface/serial_read_until_sequence.h b/include/cpp_core/interface/serial_read_until_sequence.h index e5ebf81..1aef162 100644 --- a/include/cpp_core/interface/serial_read_until_sequence.h +++ b/include/cpp_core/interface/serial_read_until_sequence.h @@ -21,6 +21,7 @@ extern "C" * `timeout_ms * multiplier`). * @param multiplier Factor applied to the timeout for subsequent bytes. * @param sequence Pointer to the terminating byte sequence (must not be `nullptr`). + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Bytes read (including the terminator) or a negative error code. */ MODULE_API auto serialReadUntilSequence( diff --git a/include/cpp_core/interface/serial_set_error_callback.h b/include/cpp_core/interface/serial_set_error_callback.h index e4c143e..46e28a2 100644 --- a/include/cpp_core/interface/serial_set_error_callback.h +++ b/include/cpp_core/interface/serial_set_error_callback.h @@ -12,7 +12,8 @@ extern "C" * * Pass `nullptr` to disable the callback. * - * @param callback Function receiving the error code and a textual description. + * @param error_callback Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. Gets + * invoked on any error. */ MODULE_API void serialSetErrorCallback(ErrorCallbackT error_callback); diff --git a/include/cpp_core/interface/serial_write.h b/include/cpp_core/interface/serial_write.h index 13c32b2..281267d 100644 --- a/include/cpp_core/interface/serial_write.h +++ b/include/cpp_core/interface/serial_write.h @@ -20,6 +20,7 @@ extern "C" * @param timeout_ms Base timeout per byte in milliseconds (applied to the first byte as-is; subsequent bytes use * `timeout_ms * multiplier`). * @param multiplier Factor applied to the timeout for subsequent bytes. + * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. * @return Bytes written (may be 0 on timeout) or a negative error code. */ MODULE_API auto serialWrite( From 9ff2e5acf2332ecf52243df88a1d3eb791eb20ee Mon Sep 17 00:00:00 2001 From: Katze719 Date: Thu, 10 Jul 2025 21:38:47 +0200 Subject: [PATCH 44/45] Update .gitignore and CMakeLists.txt; refine documentation in serial interface headers - Added `.cache/` to `.gitignore` to exclude cache files from version control. - Removed unnecessary whitespace in `CMakeLists.txt` for cleaner formatting. - Clarified return value documentation in `serial_drain.h` and `serial_open.h` to improve understanding of function outcomes. These changes enhance project organization and improve code documentation clarity. --- .gitignore | 2 +- CMakeLists.txt | 2 +- include/cpp_core/interface/serial_drain.h | 2 +- include/cpp_core/interface/serial_open.h | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 12d6de1..8d5694f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ include/cpp_core/version.h build/ - +.cache/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 933f7d5..6fabd8e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -61,4 +61,4 @@ install(EXPORT cpp_coreTargets install(FILES ${CMAKE_CURRENT_BINARY_DIR}/cpp_coreConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/cpp_coreConfigVersion.cmake - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cpp_core) + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cpp_core) diff --git a/include/cpp_core/interface/serial_drain.h b/include/cpp_core/interface/serial_drain.h index 7f9115e..36018e6 100644 --- a/include/cpp_core/interface/serial_drain.h +++ b/include/cpp_core/interface/serial_drain.h @@ -29,7 +29,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return 0 on success; negative ::cpp_core::StatusCodes value on error. + * @return 0 on success or a negative error code on failure. */ MODULE_API auto serialDrain( int64_t handle, diff --git a/include/cpp_core/interface/serial_open.h b/include/cpp_core/interface/serial_open.h index 1ba0fa1..684a37d 100644 --- a/include/cpp_core/interface/serial_open.h +++ b/include/cpp_core/interface/serial_open.h @@ -17,13 +17,13 @@ extern "C" * - `const wchar_t*` on Windows. * * @param port Null-terminated device identifier (e.g. "COM3", "/dev/ttyUSB0"). Passing `nullptr` results in - * ::cpp_core::StatusCodes::kNotFoundError. + * a failure. * @param baudrate Desired baud rate in bit/s (≥ 300). * @param data_bits Number of data bits (5–8). * @param parity 0 = none, 1 = even, 2 = odd. * @param stop_bits 0 = 1 stop bit, 2 = 2 stop bits. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return A positive opaque handle on success or a negative value from ::cpp_core::StatusCodes on failure. + * @return A positive opaque handle on success or a negative value on failure. */ MODULE_API auto serialOpen( void *port, From 719f80bb2a8ba82f4a1e9c2bf7f48c1d1a209170 Mon Sep 17 00:00:00 2001 From: Katze719 Date: Thu, 10 Jul 2025 21:48:28 +0200 Subject: [PATCH 45/45] Clarify return value documentation in serial interface headers - Updated return value descriptions in multiple serial interface header files to specify that negative error codes are derived from ::cpp_core::StatusCodes. This change enhances clarity and consistency in the documentation. These updates improve the understanding of function outcomes across the serial API. --- include/cpp_core/interface/serial_abort_read.h | 2 +- include/cpp_core/interface/serial_abort_write.h | 2 +- include/cpp_core/interface/serial_clear_buffer_in.h | 2 +- include/cpp_core/interface/serial_clear_buffer_out.h | 2 +- include/cpp_core/interface/serial_close.h | 2 +- include/cpp_core/interface/serial_drain.h | 2 +- include/cpp_core/interface/serial_get_ports_info.h | 2 +- include/cpp_core/interface/serial_in_bytes_total.h | 2 +- include/cpp_core/interface/serial_in_bytes_waiting.h | 2 +- include/cpp_core/interface/serial_open.h | 2 +- include/cpp_core/interface/serial_out_bytes_total.h | 2 +- include/cpp_core/interface/serial_out_bytes_waiting.h | 2 +- include/cpp_core/interface/serial_read.h | 2 +- include/cpp_core/interface/serial_read_line.h | 2 +- include/cpp_core/interface/serial_read_until.h | 3 ++- include/cpp_core/interface/serial_read_until_sequence.h | 2 +- include/cpp_core/interface/serial_write.h | 2 +- 17 files changed, 18 insertions(+), 17 deletions(-) diff --git a/include/cpp_core/interface/serial_abort_read.h b/include/cpp_core/interface/serial_abort_read.h index 5e00720..7925546 100644 --- a/include/cpp_core/interface/serial_abort_read.h +++ b/include/cpp_core/interface/serial_abort_read.h @@ -16,7 +16,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return 0 on success or a negative error code on failure. + * @return 0 on success or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialAbortRead( int64_t handle, diff --git a/include/cpp_core/interface/serial_abort_write.h b/include/cpp_core/interface/serial_abort_write.h index 7f4e3fa..f5c3d0c 100644 --- a/include/cpp_core/interface/serial_abort_write.h +++ b/include/cpp_core/interface/serial_abort_write.h @@ -16,7 +16,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return 0 on success or a negative error code on failure. + * @return 0 on success or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialAbortWrite( int64_t handle, diff --git a/include/cpp_core/interface/serial_clear_buffer_in.h b/include/cpp_core/interface/serial_clear_buffer_in.h index 64fcfa3..8723016 100644 --- a/include/cpp_core/interface/serial_clear_buffer_in.h +++ b/include/cpp_core/interface/serial_clear_buffer_in.h @@ -16,7 +16,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return 0 on success or a negative error code on failure. + * @return 0 on success or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialClearBufferIn( int64_t handle, diff --git a/include/cpp_core/interface/serial_clear_buffer_out.h b/include/cpp_core/interface/serial_clear_buffer_out.h index e686a68..3a8fcc5 100644 --- a/include/cpp_core/interface/serial_clear_buffer_out.h +++ b/include/cpp_core/interface/serial_clear_buffer_out.h @@ -16,7 +16,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return 0 on success or a negative error code on failure. + * @return 0 on success or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialClearBufferOut( int64_t handle, diff --git a/include/cpp_core/interface/serial_close.h b/include/cpp_core/interface/serial_close.h index 149fa1b..55b4e94 100644 --- a/include/cpp_core/interface/serial_close.h +++ b/include/cpp_core/interface/serial_close.h @@ -16,7 +16,7 @@ extern "C" * * @param handle Handle obtained from serialOpen(). * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return 0 on success or a negative error code on failure. + * @return 0 on success or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialClose( int64_t handle, diff --git a/include/cpp_core/interface/serial_drain.h b/include/cpp_core/interface/serial_drain.h index 36018e6..7e1f2bc 100644 --- a/include/cpp_core/interface/serial_drain.h +++ b/include/cpp_core/interface/serial_drain.h @@ -29,7 +29,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return 0 on success or a negative error code on failure. + * @return 0 on success or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialDrain( int64_t handle, diff --git a/include/cpp_core/interface/serial_get_ports_info.h b/include/cpp_core/interface/serial_get_ports_info.h index a1287b2..665f981 100644 --- a/include/cpp_core/interface/serial_get_ports_info.h +++ b/include/cpp_core/interface/serial_get_ports_info.h @@ -15,7 +15,7 @@ extern "C" * * @param callback_fn Callback receiving port information. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Number of ports found or a negative error code. + * @return Number of ports found or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialGetPortsInfo( void (*callback_fn)( diff --git a/include/cpp_core/interface/serial_in_bytes_total.h b/include/cpp_core/interface/serial_in_bytes_total.h index 2cce953..330a530 100644 --- a/include/cpp_core/interface/serial_in_bytes_total.h +++ b/include/cpp_core/interface/serial_in_bytes_total.h @@ -13,7 +13,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Total number of bytes read or a negative error code. + * @return Total number of bytes read or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialInBytesTotal( int64_t handle, diff --git a/include/cpp_core/interface/serial_in_bytes_waiting.h b/include/cpp_core/interface/serial_in_bytes_waiting.h index b0a9006..cf3adae 100644 --- a/include/cpp_core/interface/serial_in_bytes_waiting.h +++ b/include/cpp_core/interface/serial_in_bytes_waiting.h @@ -24,7 +24,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Bytes available for instant reading or a negative error code. + * @return Bytes available for instant reading or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialInBytesWaiting( int64_t handle, diff --git a/include/cpp_core/interface/serial_open.h b/include/cpp_core/interface/serial_open.h index 684a37d..0388f2a 100644 --- a/include/cpp_core/interface/serial_open.h +++ b/include/cpp_core/interface/serial_open.h @@ -23,7 +23,7 @@ extern "C" * @param parity 0 = none, 1 = even, 2 = odd. * @param stop_bits 0 = 1 stop bit, 2 = 2 stop bits. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return A positive opaque handle on success or a negative value on failure. + * @return A positive opaque handle on success or a negative value from ::cpp_core::StatusCodes on failure. */ MODULE_API auto serialOpen( void *port, diff --git a/include/cpp_core/interface/serial_out_bytes_total.h b/include/cpp_core/interface/serial_out_bytes_total.h index 3c7f814..a29336e 100644 --- a/include/cpp_core/interface/serial_out_bytes_total.h +++ b/include/cpp_core/interface/serial_out_bytes_total.h @@ -13,7 +13,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Total number of bytes written or a negative error code. + * @return Total number of bytes written or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialOutBytesTotal( int64_t handle, diff --git a/include/cpp_core/interface/serial_out_bytes_waiting.h b/include/cpp_core/interface/serial_out_bytes_waiting.h index b388c86..14fc6ee 100644 --- a/include/cpp_core/interface/serial_out_bytes_waiting.h +++ b/include/cpp_core/interface/serial_out_bytes_waiting.h @@ -22,7 +22,7 @@ extern "C" * * @param handle Port handle. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Bytes still waiting in the TX FIFO or a negative error code. + * @return Bytes still waiting in the TX FIFO or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialOutBytesWaiting( int64_t handle, diff --git a/include/cpp_core/interface/serial_read.h b/include/cpp_core/interface/serial_read.h index 6feaf33..1d1a1fb 100644 --- a/include/cpp_core/interface/serial_read.h +++ b/include/cpp_core/interface/serial_read.h @@ -23,7 +23,7 @@ extern "C" * @param multiplier Factor applied to @p timeout_ms for every byte after the first. 0 -> return immediately after * the first byte. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Bytes read (0 on timeout) or a negative error code. + * @return Bytes read (0 on timeout) or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialRead( int64_t handle, diff --git a/include/cpp_core/interface/serial_read_line.h b/include/cpp_core/interface/serial_read_line.h index 45cd56c..62db720 100644 --- a/include/cpp_core/interface/serial_read_line.h +++ b/include/cpp_core/interface/serial_read_line.h @@ -21,7 +21,7 @@ extern "C" * `timeout_ms * multiplier`). * @param multiplier Factor applied to the timeout for subsequent bytes. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Bytes read (0 on timeout) or a negative error code. + * @return Bytes read (0 on timeout) or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialReadLine( int64_t handle, diff --git a/include/cpp_core/interface/serial_read_until.h b/include/cpp_core/interface/serial_read_until.h index 229b8b8..ea276ac 100644 --- a/include/cpp_core/interface/serial_read_until.h +++ b/include/cpp_core/interface/serial_read_until.h @@ -23,7 +23,8 @@ extern "C" * @param multiplier Factor applied to the timeout for every additional byte. * @param until_char Pointer to the terminator character (must not be `nullptr`). * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Bytes read (including the terminator), 0 on timeout or a negative error code. + * @return Bytes read (including the terminator), 0 on timeout or a negative error code from ::cpp_core::StatusCodes + * on error. */ MODULE_API auto serialReadUntil( int64_t handle, diff --git a/include/cpp_core/interface/serial_read_until_sequence.h b/include/cpp_core/interface/serial_read_until_sequence.h index 1aef162..ff346c1 100644 --- a/include/cpp_core/interface/serial_read_until_sequence.h +++ b/include/cpp_core/interface/serial_read_until_sequence.h @@ -22,7 +22,7 @@ extern "C" * @param multiplier Factor applied to the timeout for subsequent bytes. * @param sequence Pointer to the terminating byte sequence (must not be `nullptr`). * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Bytes read (including the terminator) or a negative error code. + * @return Bytes read (including the terminator) or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialReadUntilSequence( int64_t handle, diff --git a/include/cpp_core/interface/serial_write.h b/include/cpp_core/interface/serial_write.h index 281267d..3945dcb 100644 --- a/include/cpp_core/interface/serial_write.h +++ b/include/cpp_core/interface/serial_write.h @@ -21,7 +21,7 @@ extern "C" * `timeout_ms * multiplier`). * @param multiplier Factor applied to the timeout for subsequent bytes. * @param error_callback [optional] Callback to invoke on error. Defined in error_callback.h. Default is `nullptr`. - * @return Bytes written (may be 0 on timeout) or a negative error code. + * @return Bytes written (may be 0 on timeout) or a negative error code from ::cpp_core::StatusCodes on error. */ MODULE_API auto serialWrite( int64_t handle,