Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
--------------
Expand Down
Empty file removed docs/manuals/.gitkeep
Empty file.
122 changes: 122 additions & 0 deletions docs/manuals/api_description/advanced_api.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
..
# *******************************************************************************
# 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
# *******************************************************************************

.. _manual_time_advanced_api:

Advanced API Usage: Subscribing to PTP Protocol Events
======================================================

For advanced use cases, such as diagnostics, network monitoring, or detailed performance analysis, the ``score::time`` framework allows applications to subscribe directly to low-level PTP protocol data events. Instead of polling for the final, processed time, an application can register a callback function that is invoked asynchronously whenever new data arrives from the ``TimeSlave``.

.. warning::

This is an advanced feature. Most applications should use the simpler polling mechanism described in the previous chapter, as it provides the fully quality-assured time. Subscribing to raw PTP data bypasses some of the quality checks performed by the ``TimeDaemon``.

Available Data Subscriptions
----------------------------

Two types of data events can be subscribed to:

1. **`TimeSlaveSyncData`**:
This event is triggered whenever the ``TimeSlave`` successfully processes a PTP Sync/Follow-Up message pair from the Time Master. The data contains raw offset and rate correction information, as well as the underlying hardware and software timestamps.

2. **`PDelayMeasurementData`**:
This event is triggered after the ``TimeSlave`` completes a peer-delay measurement cycle (PDelay_Req/Resp/FUp exchange). The data contains the calculated path delay to the communication partner.

Subscribing to Events
---------------------

The following code example demonstrates how to register, handle, and unregister callbacks for these events.

.. code-block:: cpp

#include "score/time/clock.h"
#include "score/time/vehicle_time.h"
#include <atomic>
#include <iostream>
#include <mutex>

// A thread-safe data handler for our application
class PtpDataLogger
{
public:
void HandleSyncData(const score::time::TimeSlaveSyncData<score::time::VehicleTime>& data)
{
std::lock_guard<std::mutex> lock(mutex_);
std::cout << "PTP Sync Event: Offset = " << data.offset_ns
<< " ns, Rate Ratio = " << data.rate_ratio << std::endl;
// Further processing of the data...
}

void HandlePDelayData(const score::time::PDelayMeasurementData<score::time::VehicleTime>& data)
{
std::lock_guard<std::mutex> lock(mutex_);
std::cout << "PTP PDelay Event: Path Delay = " << data.path_delay_ns << " ns" << std::endl;
// Further processing of the data...
}

private:
std::mutex mutex_;
};

/**
* @brief Demonstrates how to subscribe to and unsubscribe from PTP protocol events.
*/
void subscribe_to_ptp_events()
{
auto& clock = score::time::Clock<score::time::VehicleTime>::GetInstance();
PtpDataLogger logger;

// 1. Subscribe to Sync data events using a lambda that calls our thread-safe handler.
// The returned handle is used later to unsubscribe.
auto sync_subscription = clock.Subscribe<score::time::TimeSlaveSyncData<score::time::VehicleTime>>(
[&logger](const auto& data) { logger.HandleSyncData(data); });

std::cout << "Subscribed to TimeSlaveSyncData events." << std::endl;


// 2. Subscribe to Peer-Delay data events.
auto pdelay_subscription = clock.Subscribe<score::time::PDelayMeasurementData<score::time::VehicleTime>>(
[&logger](const auto& data) { logger.HandlePDelayData(data); });

std::cout << "Subscribed to PDelayMeasurementData events." << std::endl;

// ... application runs and receives callbacks asynchronously ...
std::this_thread::sleep_for(std::chrono::seconds(10));


// 3. Unsubscribe when the data is no longer needed.
// The subscription handle is moved into the Unsubscribe call.
clock.Unsubscribe(std::move(sync_subscription));
std::cout << "Unsubscribed from TimeSlaveSyncData events." << std::endl;

clock.Unsubscribe(std::move(pdelay_subscription));
std::cout << "Unsubscribed from PDelayMeasurementData events." << std::endl;
}


Threading and Safety Considerations
-----------------------------------

.. attention::

Callback functions are executed on a **backend thread** owned by the ``score::time`` framework, not on the application's main thread. Therefore, all callback handlers **must be thread-safe**.

* **Data Protection**: Use mutexes, atomics, or other synchronization primitives to protect any shared data that is accessed or modified within the callback.
* **Keep it Short**: Callbacks should be lightweight and non-blocking. Offload any time-consuming processing to a separate application-owned thread to avoid delaying the ``score::time`` backend.

Unsubscribing
-------------

It is crucial to unsubscribe from events when they are no longer needed to prevent resource leaks and dangling callbacks. The ``Subscribe`` method returns a handle object which must be passed to the ``Unsubscribe`` method. The handle is invalidated upon unsubscription.
88 changes: 88 additions & 0 deletions docs/manuals/api_description/api_usage.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
..
# *******************************************************************************
# 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
# *******************************************************************************

.. _manual_time_api_usage:

API Usage: Accessing Vehicle Time
=================================

The primary interface for applications to access synchronized time is the ``score::time`` client library. It provides a simple, robust, and testable way to get the current time without dealing with the underlying complexities of PTP and IPC.

This section describes the most common use case: polling the current Vehicle Time.

Polling the Current Time
------------------------

This method involves actively requesting the current time from the ``score::time`` framework. It is the simplest way to get a timepoint when needed.

.. code-block:: cpp

#include "score/time/clock.h"
#include "score/time/vehicle_time.h"
#include <iostream>
#include <thread>

/**
* @brief Demonstrates how to poll the current Vehicle Time and check its status.
*/
void poll_vehicle_time()
{
// 1. Get a handle to the VehicleClock singleton instance.
auto& clock = score::time::Clock<score::time::VehicleTime>::GetInstance();

// 2. Request the current time snapshot.
// This call retrieves the latest time information from the TimeDaemon via IPC.
const auto snapshot = clock.Now();

// 3. Check the status of the snapshot.
// The IsReliable() flag indicates if the time is currently synchronized
// to a master and has passed all quality checks in the TimeDaemon.
if (snapshot.Status().IsReliable())
{
// 4. Use the timepoint.
// The timepoint is a std::chrono::time_point.
const auto current_time = snapshot.TimePoint();
const auto ns_since_epoch = std::chrono::duration_cast<std::chrono::nanoseconds>(
current_time.time_since_epoch()).count();

std::cout << "Successfully retrieved reliable Vehicle Time: "
<< ns_since_epoch << " ns since epoch." << std::endl;
}
else
{
// 5. Handle the "not synchronized" case.
// If the time is not reliable, applications must not use the timepoint value.
// This can happen during startup or if the connection to the Time Master is lost.
// The application should implement a retry-logic or fallback.
std::cerr << "Warning: Vehicle Time is not synchronized or not reliable. "
<< "Retrying later..." << std::endl;
}
}

Workflow Explanation
--------------------

The sequence diagram "VT1 — VehicleTime: Time Polling with Status Check" illustrates the following steps:

1. **Get Instance**: The application first obtains a singleton instance of the ``VehicleClock``. This is a lightweight operation and the clock handle can be stored and reused.
2. **Now()**: The application calls the ``Now()`` method on the clock instance. This triggers an IPC call to the ``TimeDaemon`` to fetch the latest synchronized time data.
3. **Return Snapshot**: The framework returns a ``ClockSnapshot`` object. This object contains not just the timepoint, but also a crucial ``VehicleTimeStatus`` payload.
4. **Status Check**: The application **must** call the ``Status().IsReliable()`` method on the snapshot. This boolean flag consolidates all underlying quality metrics (e.g., is PTP master available? is shared memory data fresh? has the time passed plausibility checks?).
5. **Conditional Logic**:
* If ``IsReliable()`` returns ``true``, the timepoint is valid and can be safely used by the application logic.
* If ``IsReliable()`` returns ``false``, the application must discard the timepoint value and handle the failure case (e.g., by logging a warning and retrying the operation after a short delay).

.. attention::

Never use the ``TimePoint`` from a ``ClockSnapshot`` without first verifying that ``Status().IsReliable()`` is true. Using an unreliable timepoint can lead to incorrect or inconsistent behavior in safety-critical applications.
116 changes: 116 additions & 0 deletions docs/manuals/api_description/lifecycle.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
..
# *******************************************************************************
# 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
# *******************************************************************************

.. _manual_time_lifecycle:

Clock Lifecycle Management
==========================

Before an application can read reliable time from clocks like ``VehicleClock``, the underlying backend service must be initialized and ready. The ``Clock`` API provides several functions to manage this lifecycle gracefully.

.. attention::
These lifecycle functions are primarily relevant for clocks that depend on external services, like ``VehicleClock``. Simpler clocks such as ``SystemClock`` or ``SteadyClock`` are always available and do not require these steps.

Initializing the Clock
----------------------

The ``Init()`` method must be called once to establish the connection to the backend service (e.g., the ``TimeDaemon``). Until ``Init()`` succeeds, any call to ``Now()`` will return a snapshot with a "not ready" or "unknown" status.

.. code-block:: cpp

#include "score/time/clock.h"
#include "score/time/vehicle_time.h"
#include <iostream>

void initialize_clock()
{
auto& clock = score::time::Clock<score::time::VehicleTime>::GetInstance();

// Attempt to initialize the connection to the backend.
// This can be retried if it fails (e.g., if the TimeDaemon is not yet running).
if (clock.Init())
{
std::cout << "Clock backend initialized successfully." << std::endl;
}
else
{
std::cerr << "Clock backend initialization failed. Please retry." << std::endl;
}
}

Waiting for Availability
------------------------

After initialization, the clock might still not be "reliable" because the ``TimeDaemon`` itself is waiting for synchronization with the PTP master. Instead of polling in a loop, applications can use ``WaitUntilAvailable()`` to block efficiently until the clock is ready.

This is the recommended approach for applications that cannot proceed without a valid time source at startup.

.. code-block:: cpp

#include "score/time/clock.h"
#include "score/time/vehicle_time.h"
#include <score/stop_token.hpp>
#include <iostream>
#include <chrono>

void wait_for_reliable_time(const score::cpp::stop_token& stop_token)
{
auto& clock = score::time::Clock<score::time::VehicleTime>::GetInstance();

if (!clock.Init()) {
std::cerr << "Initialization failed. Cannot wait for time." << std::endl;
return;
}

// Wait for a maximum of 30 seconds for the clock to become available.
// The wait will be interrupted if the application's stop_token is triggered.
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30);

std::cout << "Waiting for VehicleTime to become available..." << std::endl;

if (clock.WaitUntilAvailable(stop_token, deadline))
{
std::cout << "VehicleTime is now available and synchronized!" << std::endl;

// Now it is safe to start polling or using the time.
const auto snapshot = clock.Now();
if (snapshot.Status().IsReliable()) {
// ... proceed with application logic ...
}
}
else
{
std::cerr << "Timed out waiting for VehicleTime. Is the TimeSlave running and synchronized?" << std::endl;
}
}


Checking Availability (Non-Blocking)
------------------------------------

For applications that need to perform other tasks while waiting for time, the non-blocking ``IsAvailable()`` method can be used to periodically check the status.

.. code-block:: cpp

// Inside an application's main loop
auto& clock = score::time::Clock<score::time::VehicleTime>::GetInstance();

if (clock.IsAvailable())
{
// Time is ready, perform time-sensitive tasks.
}
else
{
// Time is not yet ready, perform other tasks.
}
Loading
Loading