C

Qt Quick Ultralite Automotive Cluster Demo

// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial
#include "simulation/speedlimits.h"
#include "Automotive/Units.h"
#include "mathutils.h"

#include <etl/array.h>

using namespace Automotive;

namespace {
const etl::array<SpeedLimitValues::Limit, SpeedLimitValues::LimitsCount> LIMITS = {
    SpeedLimitValues::None,
    SpeedLimitValues::VerySlow,
    SpeedLimitValues::Slow,
    SpeedLimitValues::Medium,
    SpeedLimitValues::Fast,
    SpeedLimitValues::VeryFast,
};
}

namespace Simulation {
SpeedLimits::SpeedLimits(uint32_t updatePeriod, uint32_t updatePeriodVariation)
    : _updatePeriod(updatePeriod)
    , _updatePeriodVariation(updatePeriodVariation)
    , _timer(0)
    , _timeToChange(0)
    , _limit(SpeedLimitValues::None)
{
    reset();
}

void SpeedLimits::update(uint32_t tick)
{
    _timer += tick;
    if (_timer > _timeToChange) {
        changeSpeedLimit();
        const int32_t variation = _updatePeriodVariation > _updatePeriod ? _updatePeriod : _updatePeriodVariation;
        calculateNewChangeTime(randomize(-variation, variation));
        _timer = 0;
    }
}

void SpeedLimits::reset(SpeedLimitValues::Limit speedLimit)
{
    _timer = 0;
    _limit = speedLimit;
    calculateNewChangeTime(0); /* No variation after reset */
}

float SpeedLimits::getCurrentSpeedLimitInKmh() const
{
    return Units::instance().longDistanceUnitToKilometers(_limit);
}

SpeedLimitValues::Limit SpeedLimits::getCurrentSpeedLimit() const
{
    return _limit;
}

void SpeedLimits::changeSpeedLimit()
{
    const int idx = randomChoice(LIMITS.size() - 1);
    _limit = LIMITS[idx];
}

void SpeedLimits::calculateNewChangeTime(int32_t variation)
{
    _timeToChange = _updatePeriod + variation;
}

} // namespace Simulation