Using external clocks

Sensor timestamps can be based on a reference time provided by an external clock library.

You may provide a library that provides a reference time for sensor timestamps. To use an external clock library, you must:

  1. Provide your external clock library with implementation for the following functions:
    open()
    A function that the Sensor service calls when the sensor starts streaming. For example:
    ...
    sensor_error_t reference_clock_open(sensor_unit_t unit)
    {
        ...
        return SENSOR_EOK;
    }
    ...
                  
    close()
    A function that the Sensor service calls when the sensor stops streaming. For example:
    ...
    sensor_error_t reference_clock_close(sensor_unit_t unit)
    {
        ...
        return SENSOR_EOK;
    }
    ...
                  
    get_time()
    A function that the Sensor service calls periodically after the sensor starts streaming to synchronize sensor timestamps. For example:
    ...
    sensor_error_t reference_clock_get_time(sensor_unit_t unit, int64_t *timestamp)
    {
        ...
        static const int64_t NS_PER_SECOND = 1000000000;
        ...
        struct timespec tp;
        if (clock_gettime(CLOCK_REALTIME, &tp) == -1) {
            return SENSOR_EINVAL;
        }
        *timestamp = (tp.tv_sec * NS_PER_SECOND + tp.tv_nsec) / 1000;
        return SENSOR_EOK;
    }
    ...
                  
    See sensor_ext_reference_clock_t.
  2. Assign your external clock functions by using the structure sensor_ext_reference_clock_t.

    For example:

    ...
    sensor_ext_reference_clock_t reference_clock_defs = {
        reference_clock_open,
        reference_clock_get_time,
        reference_clock_close
    };
    ...
          
    Note: In your external clock library, you must use reference_clock_defs to declare your variable name for the structure sensor_ext_reference_clock_t.

    The Sensor service dynamically loads this structure to retrieve the function pointers so that it can interface with your external clock library.

  3. Appropriately configure the reference_clock_library and reference_clock_library parameters in your sensor configuration file.

    See the “Sensor configuration file” section in the System Services guide.

You can configure each sensor to use a different external clock library, or multiple sensors can share one external clock library. You may provide multiple external clock libraries.