diff --git a/docs/index.rst b/docs/index.rst index e35c841d..6007e6f8 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -43,6 +43,7 @@ For a detailed concept and architectural design, please refer to the :doc:`time_ :caption: Contents: features/index + manuals/index Project Layout -------------- diff --git a/docs/manuals/.gitkeep b/docs/manuals/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/manuals/examples/basic_clocks.rst b/docs/manuals/examples/basic_clocks.rst new file mode 100644 index 00000000..47d900e0 --- /dev/null +++ b/docs/manuals/examples/basic_clocks.rst @@ -0,0 +1,280 @@ +.. ******************************************************************************* + Copyright (c) 2026 Contributors to the Eclipse Foundation + + See the NOTICE file(s) distributed with this work for additional + information regarding copyright ownership. + + This program and the accompanying materials are made available under the + terms of the Apache License Version 2.0 which is available at + https://www.apache.org/licenses/LICENSE-2.0 + + SPDX-License-Identifier: Apache-2.0 + ******************************************************************************* + +Basic Clock Examples +==================== + +Overview +-------- + +Three examples demonstrate the basic SCORE clock types: ``system_time``, ``steady_time``, +and ``high_res_steady_time``. All follow an identical pattern - a periodic time printer +that outputs time values once per second until interrupted. + +These examples show the fundamental pattern for using SCORE time APIs and can serve as +starting points for applications requiring simple time reading. + +Common Implementation Pattern +----------------------------- + +All three examples share the same structure: + +**Handler Class** + Wrapper around ``Clock::GetInstance()`` that provides a clean ``GetCurrentTime()`` + method returning a ``TimeReport`` struct. + +**Main Program** + - Signal handling for graceful shutdown (SIGINT/SIGTERM) + - Loop reading time every second + - Simple text output with sequence numbers + - Consistent error handling + +**Unit Tests** + Demonstrate mocking with ``ScopedClockOverride`` for dependency injection. + +Building and Running +-------------------- + +.. code-block:: bash + + # Build any of the basic examples + bazel build //examples/time/system_time + bazel build //examples/time/steady_time + bazel build //examples/time/high_res_steady_time + + # Run examples + bazel run //examples/time/system_time + bazel run //examples/time/steady_time + bazel run //examples/time/high_res_steady_time + + # Run tests + bazel test //examples/time/system_time/src:system_time_handler_test + bazel test //examples/time/steady_time/src:steady_time_handler_test + bazel test //examples/time/high_res_steady_time/src:high_res_steady_time_handler_test + +Example Output +-------------- + +Each example prints time in a similar format: + +**System Time:** + +.. code-block:: text + + SystemTime printer started. Press Ctrl+C to stop. + [0] unix=1720184400.123456789 s + [1] unix=1720184401.234567890 s + [2] unix=1720184402.345678901 s + ... + +**Steady Time:** + +.. code-block:: text + + SteadyTime printer started. Press Ctrl+C to stop. + [0] monotonic=12345.123456789 s + [1] monotonic=12346.234567890 s + [2] monotonic=12347.345678901 s + ... + +**High-Resolution Steady Time:** + +.. code-block:: text + + HighResSteadyTime printer started. Press Ctrl+C to stop. + [0] time=12345.123456789 s + [1] time=12346.234567890 s + [2] time=12347.345678901 s + ... + +Code Structure +-------------- + +Each example follows this pattern: + +**Handler Header** (``*_time_handler.h``): + +.. code-block:: cpp + + struct TimeReport { + std::int64_t time_field_ns{0}; // Field name varies by clock type + }; + + class TimeHandler { + public: + TimeReport GetCurrentTime() const noexcept { + const auto snapshot = ClockType::GetInstance().Now(); + return TimeReport{snapshot.TimePointNs().count()}; + } + }; + +**Main Program** (``main.cpp``): + +.. code-block:: cpp + + volatile std::sig_atomic_t gShutdownRequested{0}; + extern "C" void HandleSignal(int) noexcept { gShutdownRequested = 1; } + + int main() { + signal(SIGINT, HandleSignal); + signal(SIGTERM, HandleSignal); + + HandlerType handler; + std::uint64_t seq{0}; + + while (gShutdownRequested == 0) { + const auto report = handler.GetCurrentTime(); + PrintReport(report, seq++); + std::this_thread::sleep_for(std::chrono::seconds{1}); + } + return 0; + } + +Testing Pattern +--------------- + +All examples use the same mocking approach: + +.. code-block:: cpp + + TEST(HandlerTest, GetCurrentTime) { + auto mock = std::make_shared(); + score::time::test_utils::ScopedClockOverride guard{mock}; + + EXPECT_CALL(*mock, Now()).WillOnce(Return(test_snapshot)); + + HandlerType handler; + const auto report = handler.GetCurrentTime(); + + EXPECT_EQ(expected_value, report.time_field_ns); + } + +.. note:: + + Tests using ``ScopedClockOverride`` must declare ``tags = ["exclusive", "unit"]`` + in their Bazel BUILD file to prevent parallel execution conflicts. + +Bazel Build Setup +----------------- + +Understanding the dependency structure helps when adapting these examples for your application. + +Target Structure +~~~~~~~~~~~~~~~~ + +Each example has three Bazel targets in ``examples/time//src/BUILD``: + +.. code-block:: python + + cc_library( + name = "time_handler", + hdrs = ["system_time_handler.h"], + deps = ["//score/time/system_time:interface"], # Header-only dep + ) + + cc_binary( + name = "system_time", + srcs = ["main.cpp"], + deps = [ + ":time_handler", + "//score/time/system_time", # Production backend + ], + ) + + cc_test( + name = "system_time_handler_test", + srcs = ["system_time_handler_test.cpp"], + tags = ["exclusive", "unit"], # Required for ScopedClockOverride + deps = [ + ":time_handler", + "//score/time/system_time:system_time_mock", # Mock backend + "@googletest//:gtest", + "@googletest//:gtest_main", + ], + ) + +Dependency Layers +~~~~~~~~~~~~~~~~~ + +**Handler Library** (``time_handler``): + - Header-only wrapper around SCORE clock API + - Depends on ``:interface`` target (types only, no implementation) + - Can be tested without linking production backend + +**Binary** (``system_time``, ``steady_time``, ``high_res_steady_time``): + - Links production backend (``//score/time/``) + - Depends on handler library + - Minimal dependencies for deployment + +**Test** (``*_handler_test``): + - Links mock backend (``//score/time/:*_mock``) + - Uses ``ScopedClockOverride`` for dependency injection + - **Must** have ``tags = ["exclusive", "unit"]`` to prevent parallel test conflicts + +Key Dependency Targets +~~~~~~~~~~~~~~~~~~~~~~ + +For each clock type (``system_time``, ``steady_time``, ``high_res_steady_time``): + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Target + - Purpose + * - ``//score/time/:interface`` + - Header-only, types and tag definitions + * - ``//score/time/`` + - Production backend implementation + * - ``//score/time/:_mock`` + - GMock test double for unit testing + +Adapting for Your Application +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To use these patterns in your code: + +1. **Production code** depends on ``:interface`` for headers, production target for binary: + + .. code-block:: python + + cc_library( + name = "my_component", + hdrs = ["my_component.h"], + deps = ["//score/time/steady_time:interface"], + ) + + cc_binary( + name = "my_app", + deps = [ + ":my_component", + "//score/time/steady_time", # Link production backend + ], + ) + +2. **Tests** depend on ``:interface`` and ``*_mock``: + + .. code-block:: python + + cc_test( + name = "my_component_test", + tags = ["exclusive", "unit"], # Required! + deps = [ + ":my_component", + "//score/time/steady_time:steady_time_mock", + "@googletest//:gtest_main", + ], + ) + +This layering keeps compile times fast (interface-only deps) and enables testing without +runtime dependencies. diff --git a/docs/manuals/examples/index.rst b/docs/manuals/examples/index.rst new file mode 100644 index 00000000..2c05373b --- /dev/null +++ b/docs/manuals/examples/index.rst @@ -0,0 +1,64 @@ +.. + # ******************************************************************************* + # Copyright (c) 2026 Contributors to the Eclipse Foundation + # + # See the NOTICE file(s) distributed with this work for additional + # information regarding copyright ownership. + # + # This program and the accompanying materials are made available under the + # terms of the Apache License Version 2.0 which is available at + # https://www.apache.org/licenses/LICENSE-2.0 + # + # SPDX-License-Identifier: Apache-2.0 + # ******************************************************************************* + +Examples User Manual +==================== + +This manual explains the examples included in the ``examples/time/`` subdirectory and how they +can be used as patterns for building applications with the SCORE time library. + +Overview +-------- + +The ``examples/time/`` directory contains four working examples that demonstrate how to use +different SCORE time sources: + +- **Basic Clock Examples** (system_time, steady_time, high_res_steady_time): Simple periodic time printers showing the common pattern for reading time from SCORE clocks +- **Vehicle Time Example** (vehicle_time): More complex example showing PTP-synchronized time with initialization, status monitoring, and dual time sources + +All examples follow consistent patterns and can be used as starting points for real applications. + +Building and Running Examples +------------------------------ + +All examples use Bazel: + +.. code-block:: bash + + # Build all examples + bazel build //examples/... + + # Run specific example + bazel run //examples/time/system_time + + # Run tests + bazel test //examples/time/system_time/src:system_time_handler_test + +Common Patterns +--------------- + +All examples share these implementation patterns: + +- **Handler wrapper classes** providing clean APIs over SCORE Clock types +- **TimeReport structs** containing time data with consistent field naming +- **Signal handling** for graceful shutdown on SIGINT/SIGTERM +- **Unit test patterns** using ScopedClockOverride for dependency injection +- **Nanosecond precision** throughout all time calculations + +.. toctree:: + :maxdepth: 2 + :caption: Examples: + + basic_clocks + vehicle_time diff --git a/docs/manuals/examples/vehicle_time.rst b/docs/manuals/examples/vehicle_time.rst new file mode 100644 index 00000000..ec2b1d71 --- /dev/null +++ b/docs/manuals/examples/vehicle_time.rst @@ -0,0 +1,289 @@ +.. ******************************************************************************* + Copyright (c) 2026 Contributors to the Eclipse Foundation + + See the NOTICE file(s) distributed with this work for additional + information regarding copyright ownership. + + This program and the accompanying materials are made available under the + terms of the Apache License Version 2.0 which is available at + https://www.apache.org/licenses/LICENSE-2.0 + + SPDX-License-Identifier: Apache-2.0 + ******************************************************************************* + +Vehicle Time Example +==================== + +Overview +-------- + +The ``vehicle_time`` example demonstrates how to use the SCORE library's VehicleClock +in combination with HighResSteadyClock. This example shows how to work with +PTP-synchronized vehicle time alongside local monotonic time, which is essential +for automotive applications requiring distributed time synchronization. + +What it does +------------ + +This example creates a ``VehicleTimeHandler`` wrapper class that: + +- Provides access to both SCORE ``VehicleClock`` and ``HighResSteadyClock`` +- Returns combined time reports with status information +- Demonstrates initialization patterns for vehicle time backends +- Shows how to monitor time synchronization quality +- Can be unit tested with independent clock mocks + +The main program: + +- Initializes the vehicle time backend +- Runs a loop reading both time sources simultaneously +- Displays time values, reliability, and synchronization status +- Handles SIGINT/SIGTERM for clean shutdown + +Building and Running +-------------------- + +To build and run the example: + +.. code-block:: bash + + # Build the example + bazel build //examples/time/vehicle_time + + # Run the example + bazel run //examples/time/vehicle_time + + # Or run the built binary directly + ./bazel-bin/examples/time/vehicle_time/src/vehicle_time + +**Note**: The vehicle time backend requires proper initialization. The example will +exit with error code 1 if initialization fails (e.g., no PTP service available). + +Output Format +------------- + +The program outputs lines in this format: + +.. code-block:: text + + VehicleTime + HighResSteadyTime printer started. Press Ctrl+C to stop. + [0] vehicle=1720184400.123456789 s hirs=12345.234567890 s is_reliable=yes is_consistent=yes rate_deviation=1.23e-09 + [1] vehicle=1720184401.234567890 s hirs=12346.345678901 s is_reliable=yes is_consistent=yes rate_deviation=1.24e-09 + ... + Shutdown requested. Exiting. + +Where: +- ``vehicle=`` shows the PTP-synchronized time in seconds.nanoseconds +- ``hirs=`` shows the local high-resolution steady time +- ``is_reliable=`` indicates if the vehicle time is synchronized and fault-free +- ``is_consistent=`` indicates if status flags are internally consistent +- ``rate_deviation=`` shows local clock deviation relative to PTP Grand Master + +Code Structure +-------------- + +VehicleTimeHandler Class +~~~~~~~~~~~~~~~~~~~~~~~~ + +Located in ``examples/time/vehicle_time/src/vehicle_time_handler.h``: + +.. code-block:: cpp + + class VehicleTimeHandler { + public: + bool Init() noexcept; + TimeReport GetCurrentTime() const noexcept; + void RegisterStatusCallback(VehicleTime::StatusChangedCallback callback) noexcept; + }; + + struct TimeReport { + std::int64_t vehicle_time_ns{0}; // PTP-synchronized time + std::int64_t high_res_steady_time_ns{0}; // Local monotonic time + bool is_reliable{false}; // Time sync quality + bool is_consistent{false}; // Status flag consistency + double rate_deviation{0.0}; // Clock drift rate + }; + +Key features: +- **Dual time sources**: Both vehicle and local time in single call +- **Status monitoring**: Reliability and consistency flags +- **Rate tracking**: Clock deviation measurement +- **Callback support**: Status change notifications (future feature) + +Main Program +~~~~~~~~~~~~ + +Located in ``examples/time/vehicle_time/src/main.cpp``: + +Key features: +- Initialization error handling with early exit +- Combined time display showing both sources +- Status information formatting for monitoring +- Same signal handling pattern as other examples + +Testing +------- + +Run the unit tests: + +.. code-block:: bash + + bazel test //examples/time/vehicle_time/src:vehicle_time_handler_test + +The test shows how to mock both time sources independently: + +.. code-block:: cpp + + auto vehicle_mock = std::make_shared(); + auto hirs_mock = std::make_shared(); + + score::time::test_utils::ScopedClockOverride vg{vehicle_mock}; + score::time::test_utils::ScopedClockOverride hg{hirs_mock}; + + EXPECT_CALL(*vehicle_mock, Init()).WillOnce(Return(true)); + EXPECT_CALL(*vehicle_mock, Now()).WillOnce(Return(...)); + EXPECT_CALL(*hirs_mock, Now()).WillOnce(Return(...)); + +Bazel Build Setup +----------------- + +The vehicle_time example has more complex dependencies due to dual time sources and initialization. + +Target Structure +~~~~~~~~~~~~~~~~ + +From ``examples/time/vehicle_time/src/BUILD``: + +.. code-block:: python + + cc_library( + name = "time_handler", + hdrs = ["vehicle_time_handler.h"], + deps = [ + "//score/time/vehicle_time:interface", + "//score/time/high_res_steady_time:interface", + ], + ) + + cc_binary( + name = "vehicle_time", + srcs = ["main.cpp"], + deps = [ + ":time_handler", + "//score/time/vehicle_time", # VehicleTime production backend + "//score/time/high_res_steady_time", # HIRS production backend + "@score_baselibs//score/mw/log:console_only_backend", + ], + ) + + cc_test( + name = "vehicle_time_handler_test", + srcs = ["vehicle_time_handler_test.cpp"], + tags = ["exclusive", "unit"], # Required for ScopedClockOverride + deps = [ + ":time_handler", + "//score/time/vehicle_time:vehicle_time_mock", + "//score/time/high_res_steady_time:high_res_steady_time_mock", + "@googletest//:gtest_main", + ], + ) + +Dual Clock Dependencies +~~~~~~~~~~~~~~~~~~~~~~~ + +The handler depends on **two** clock interfaces: + +- ``//score/time/vehicle_time:interface`` - VehicleTime tag and status types +- ``//score/time/high_res_steady_time:interface`` - HighResSteadyTime tag + +The binary links **both** production backends, while tests link **both** mocks. + +Key Targets +~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Target + - Purpose + * - ``//score/time/vehicle_time:interface`` + - VehicleTime types, status flags, callback signatures + * - ``//score/time/vehicle_time`` + - Production backend with TimeDaemon IPC + * - ``//score/time/vehicle_time:vehicle_time_mock`` + - Mock for Init/Now/Subscribe testing + * - ``//score/time/high_res_steady_time:interface`` + - HighResSteadyTime tag + * - ``//score/time/high_res_steady_time`` + - Production HIRS clock backend + * - ``//score/time/high_res_steady_time:high_res_steady_time_mock`` + - Mock for HIRS in tests + +Testing with Dual Mocks +~~~~~~~~~~~~~~~~~~~~~~~ + +The test demonstrates independent mock control: + +.. code-block:: cpp + + auto vehicle_mock = std::make_shared(); + auto hirs_mock = std::make_shared(); + + ScopedClockOverride vg{vehicle_mock}; + ScopedClockOverride hg{hirs_mock}; + + EXPECT_CALL(*vehicle_mock, Init()).WillOnce(Return(true)); + EXPECT_CALL(*vehicle_mock, Now()).WillOnce(Return(vehicle_snapshot)); + EXPECT_CALL(*hirs_mock, Now()).WillOnce(Return(hirs_snapshot)); + +Each clock can be mocked separately with different return values and expectations. + +Adapting for Your Application +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When building components that use VehicleTime: + +1. **Header-only dependencies** use ``:interface``: + + .. code-block:: python + + cc_library( + name = "my_sync_component", + hdrs = ["my_sync_component.h"], + deps = [ + "//score/time/vehicle_time:interface", + "//score/time/high_res_steady_time:interface", + ], + ) + +2. **Binaries** link production backends: + + .. code-block:: python + + cc_binary( + name = "my_app", + deps = [ + ":my_sync_component", + "//score/time/vehicle_time", + "//score/time/high_res_steady_time", + ], + ) + +3. **Tests** link mocks and require exclusive tag: + + .. code-block:: python + + cc_test( + name = "my_sync_component_test", + tags = ["exclusive", "unit"], + deps = [ + ":my_sync_component", + "//score/time/vehicle_time:vehicle_time_mock", + "//score/time/high_res_steady_time:high_res_steady_time_mock", + "@googletest//:gtest_main", + ], + ) + +The layered dependency structure keeps compile times minimal while enabling comprehensive +testing with independent clock control. diff --git a/docs/manuals/index.rst b/docs/manuals/index.rst new file mode 100644 index 00000000..24c29564 --- /dev/null +++ b/docs/manuals/index.rst @@ -0,0 +1,22 @@ +.. + # ******************************************************************************* + # Copyright (c) 2026 Contributors to the Eclipse Foundation + # + # See the NOTICE file(s) distributed with this work for additional + # information regarding copyright ownership. + # + # This program and the accompanying materials are made available under the + # terms of the Apache License Version 2.0 which is available at + # https://www.apache.org/licenses/LICENSE-2.0 + # + # SPDX-License-Identifier: Apache-2.0 + # ******************************************************************************* + +Manuals +======= + +.. toctree:: + :maxdepth: 2 + :caption: Manuals: + + examples/index