Matter SDK Coverage Report
Current view: top level - app/reporting - ReportScheduler.h (source / functions) Coverage Total Hit
Test: SHA:f84fe08d06f240e801b5d923f8a938a9938ca110 Lines: 93.8 % 48 45
Test Date: 2025-02-22 08:08:07 Functions: 75.0 % 24 18

            Line data    Source code
       1              : /*
       2              :  *
       3              :  *    Copyright (c) 2023 Project CHIP Authors
       4              :  *    All rights reserved.
       5              :  *
       6              :  *    Licensed under the Apache License, Version 2.0 (the "License");
       7              :  *    you may not use this file except in compliance with the License.
       8              :  *    You may obtain a copy of the License at
       9              :  *
      10              :  *        http://www.apache.org/licenses/LICENSE-2.0
      11              :  *
      12              :  *    Unless required by applicable law or agreed to in writing, software
      13              :  *    distributed under the License is distributed on an "AS IS" BASIS,
      14              :  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      15              :  *    See the License for the specific language governing permissions and
      16              :  *    limitations under the License.
      17              :  */
      18              : 
      19              : #pragma once
      20              : 
      21              : #include <app/ReadHandler.h>
      22              : #include <app/icd/server/ICDStateObserver.h>
      23              : #include <lib/core/CHIPError.h>
      24              : #include <system/SystemClock.h>
      25              : 
      26              : namespace chip {
      27              : namespace app {
      28              : namespace reporting {
      29              : 
      30              : // Forward declaration of TestReportScheduler to allow it to be friend with ReportScheduler
      31              : class TestReportScheduler;
      32              : 
      33              : class TimerContext
      34              : {
      35              : public:
      36            0 :     virtual ~TimerContext() {}
      37              :     virtual void TimerFired() = 0;
      38              : };
      39              : 
      40              : /**
      41              :  * @class ReportScheduler
      42              :  *
      43              :  * @brief This class is responsible for scheduling Engine runs based on the reporting intervals of the ReadHandlers.
      44              :  *
      45              :  *
      46              :  * This class holds a pool of ReadHandlerNodes that are used to keep track of the minimum and maximum timestamps for a report to be
      47              :  * emitted based on the reporting intervals of the ReadHandlers associated with the node.
      48              :  *
      49              :  * The ReportScheduler also holds a TimerDelegate pointer that is used to start and cancel timers for the ReadHandlers depending
      50              :  * on the reporting logic of the Scheduler.
      51              :  *
      52              :  * It inherits the ReadHandler::Observer class to be notified of reportability changes in the ReadHandlers.
      53              :  * It inherits the ICDStateObserver class to allow the implementation to generate reports based on the changes in ICD devices state,
      54              :  * such as going from idle to active mode and vice-versa.
      55              :  *
      56              :  * @note The logic for how and when to schedule reports is implemented in the subclasses of ReportScheduler, such as
      57              :  * ReportSchedulerImpl and SyncronizedReportSchedulerImpl.
      58              :  */
      59              : class ReportScheduler : public ReadHandler::Observer, public ICDStateObserver
      60              : {
      61              : public:
      62              :     using Timestamp = System::Clock::Timestamp;
      63              : 
      64              :     /// @brief This class acts as an interface between the report scheduler and the system timer to reduce dependencies on the
      65              :     /// system layer.
      66              :     class TimerDelegate
      67              :     {
      68              :     public:
      69            0 :         virtual ~TimerDelegate() {}
      70              :         /// @brief Start a timer for a given context. The report scheduler must always cancel an existing timer for a context (using
      71              :         /// CancelTimer) before starting a new one for that context.
      72              :         /// @param context context to pass to the timer callback.
      73              :         /// @param aTimeout time in milliseconds before the timer expires
      74              :         virtual CHIP_ERROR StartTimer(TimerContext * context, System::Clock::Timeout aTimeout) = 0;
      75              :         /// @brief Cancel a timer for a given context
      76              :         /// @param context used to identify the timer to cancel
      77              :         virtual void CancelTimer(TimerContext * context)   = 0;
      78              :         virtual bool IsTimerActive(TimerContext * context) = 0;
      79              :         virtual Timestamp GetCurrentMonotonicTimestamp()   = 0;
      80              :     };
      81              : 
      82              :     /**
      83              :      * @class ReadHandlerNode
      84              :      *
      85              :      * @brief This class is responsible for determining when a ReadHandler is reportable depending on the monotonic timestamp of
      86              :      *  the system and the intervals of the ReadHandler. It inherits the TimerContext class to allow it to be used as a context for
      87              :      *  a TimerDelegate so that the TimerDelegate can call the TimerFired method when the timer expires.
      88              :      *
      89              :      *  Three conditions that can prevent the ReadHandler from being reportable:
      90              :      *  1: The ReadHandler is not in the CanStartReporting state:
      91              :      *      This condition can be resolved by setting the CanStartReporting flag on the ReadHandler
      92              :      *
      93              :      *  2: The minimal interval since the last report has not elapsed
      94              :      *      This condition can be resolved after enough time has passed since the last report or by setting the EngineRunScheduled
      95              :      *      flag
      96              :      *
      97              :      *  3: The maximal interval since the last report has not elapsed and the ReadHandler is not dirty:
      98              :      *      This condition can be resolved after enough time has passed since the last report to reach the max interval, by the
      99              :      *      ReadHandler becoming dirty or by setting the CanBeSynced flag and having another ReadHandler needing to report.
     100              :      *
     101              :      *  Once the 3 conditions are met, the ReadHandler is considered reportable.
     102              :      *
     103              :      *  Flags:
     104              :      *
     105              :      *  CanBeSynced: Mechanism to allow the ReadHandler to emit a report if another readHandler is ReportableNow.
     106              :      *  This flag is currently only used by the SynchronizedReportScheduler to allow firing reports of ReadHandlers at the same
     107              :      *  time.
     108              :      *
     109              :      *  EngineRunScheduled: Mechanism to ensure that the reporting engine will see the ReadHandler as reportable if a timer fires.
     110              :      *  This flag is used to confirm that the next report timer has fired for a ReadHandler, thus allowing reporting when timers
     111              :      *  fire earlier than the minimal timestamp due to mechanisms such as NTP clock adjustments.
     112              :      *
     113              :      */
     114              :     class ReadHandlerNode : public TimerContext
     115              :     {
     116              :     public:
     117              :         enum class ReadHandlerNodeFlags : uint8_t
     118              :         {
     119              :             // Flag to indicate if the engine run is already scheduled so the scheduler can ignore
     120              :             // it when calculating the next run time
     121              :             EngineRunScheduled = (1 << 0),
     122              :             // Flag to allow the read handler to be synced with other handlers that have an earlier max timestamp
     123              :             CanBeSynced = (1 << 1),
     124              :         };
     125              : 
     126          302 :         ReadHandlerNode(ReadHandler * aReadHandler, ReportScheduler * aScheduler, const Timestamp & now) : mScheduler(aScheduler)
     127              :         {
     128          302 :             VerifyOrDie(aReadHandler != nullptr);
     129          302 :             VerifyOrDie(aScheduler != nullptr);
     130              : 
     131          302 :             mReadHandler = aReadHandler;
     132          302 :             SetIntervalTimeStamps(aReadHandler, now);
     133          302 :         }
     134        27636 :         ReadHandler * GetReadHandler() const { return mReadHandler; }
     135              : 
     136              :         /// @brief Check if the Node is reportable now, meaning its readhandler was made reportable by attribute dirtying and
     137              :         /// handler state, and minimal time interval since the last report has elapsed, or the maximal time interval since the last
     138              :         /// report has elapsed.
     139              :         /// @note If a handler has been flagged as scheduled for an engine run, it will be reported regardless of the timestamps.
     140              :         /// This is done to guarantee that the reporting engine will see the handler as reportable if a timer fires, even if it
     141              :         /// fires early.
     142              :         /// @param now current time to use for the check, the user must ensure to provide a valid time for this to be reliable
     143          636 :         bool IsReportableNow(const Timestamp & now) const
     144              :         {
     145         1818 :             return (mReadHandler->CanStartReporting() &&
     146         1672 :                     ((now >= mMinTimestamp && (mReadHandler->IsDirty() || now >= mMaxTimestamp || CanBeSynced())) ||
     147         1127 :                      IsEngineRunScheduled()));
     148              :         }
     149              : 
     150           65 :         bool CanStartReporting() const { return mReadHandler->CanStartReporting(); }
     151           80 :         bool IsChunkedReport() const { return mReadHandler->IsChunkedReport(); }
     152          491 :         bool IsEngineRunScheduled() const { return mFlags.Has(ReadHandlerNodeFlags::EngineRunScheduled); }
     153          307 :         void SetEngineRunScheduled(bool aEngineRunScheduled)
     154              :         {
     155          307 :             mFlags.Set(ReadHandlerNodeFlags::EngineRunScheduled, aEngineRunScheduled);
     156          307 :         }
     157          490 :         bool CanBeSynced() const { return mFlags.Has(ReadHandlerNodeFlags::CanBeSynced); }
     158          178 :         void SetCanBeSynced(bool aCanBeSynced) { mFlags.Set(ReadHandlerNodeFlags::CanBeSynced, aCanBeSynced); }
     159              : 
     160              :         /// @brief Set the interval timestamps for the node based on the read handler reporting intervals
     161              :         /// @param aReadHandler read handler to get the intervals from
     162              :         /// @param now current time to calculate the mMin and mMax timestamps, the user must ensure to provide a valid time for this
     163              :         /// to be reliable
     164          323 :         void SetIntervalTimeStamps(ReadHandler * aReadHandler, const Timestamp & now)
     165              :         {
     166              :             uint16_t minInterval, maxInterval;
     167          323 :             aReadHandler->GetReportingIntervals(minInterval, maxInterval);
     168          323 :             mMinTimestamp = now + System::Clock::Seconds16(minInterval);
     169          323 :             mMaxTimestamp = now + System::Clock::Seconds16(maxInterval);
     170          323 :         }
     171              : 
     172          129 :         void TimerFired() override
     173              :         {
     174          129 :             SetEngineRunScheduled(true);
     175          129 :             mScheduler->ReportTimerCallback();
     176          129 :         }
     177              : 
     178          472 :         System::Clock::Timestamp GetMinTimestamp() const { return mMinTimestamp; }
     179          768 :         System::Clock::Timestamp GetMaxTimestamp() const { return mMaxTimestamp; }
     180              : 
     181              :     private:
     182              :         ReadHandler * mReadHandler;
     183              :         ReportScheduler * mScheduler;
     184              :         Timestamp mMinTimestamp;
     185              :         Timestamp mMaxTimestamp;
     186              : 
     187              :         BitFlags<ReadHandlerNodeFlags> mFlags;
     188              :     };
     189              : 
     190           54 :     ReportScheduler(TimerDelegate * aTimerDelegate) : mTimerDelegate(aTimerDelegate) {}
     191              : 
     192            0 :     virtual ~ReportScheduler() = default;
     193              : 
     194              :     virtual void ReportTimerCallback() = 0;
     195              : 
     196              :     /// @brief Check whether a ReadHandler is reportable right now, taking into account its minimum and maximum intervals.
     197              :     /// @param aReadHandler read handler to check
     198          286 :     bool IsReportableNow(ReadHandler * aReadHandler)
     199              :     {
     200              :         // Update the now timestamp to ensure external calls to IsReportableNow are always comparing to the current time
     201          286 :         Timestamp now          = mTimerDelegate->GetCurrentMonotonicTimestamp();
     202          286 :         ReadHandlerNode * node = FindReadHandlerNode(aReadHandler);
     203          286 :         return (nullptr != node) ? node->IsReportableNow(now) : false;
     204              :     }
     205              : 
     206              :     /// @brief Check if a ReadHandler is reportable without considering the timing
     207          413 :     bool IsReadHandlerReportable(ReadHandler * aReadHandler) const
     208              :     {
     209          413 :         return (nullptr != aReadHandler) ? aReadHandler->ShouldStartReporting() : false;
     210              :     }
     211              :     /// @brief Sets the ForceDirty flag of a ReadHandler
     212              :     void HandlerForceDirtyState(ReadHandler * aReadHandler) { aReadHandler->ForceDirtyState(); }
     213              : 
     214              :     /// @brief Get the number of ReadHandlers registered in the scheduler's node pool
     215              :     size_t GetNumReadHandlers() const { return mNodesPool.Allocated(); }
     216              : 
     217              : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
     218              :     Timestamp GetMinTimestampForHandler(const ReadHandler * aReadHandler)
     219              :     {
     220              :         ReadHandlerNode * node = FindReadHandlerNode(aReadHandler);
     221              :         return node->GetMinTimestamp();
     222              :     }
     223              :     Timestamp GetMaxTimestampForHandler(const ReadHandler * aReadHandler)
     224              :     {
     225              :         ReadHandlerNode * node = FindReadHandlerNode(aReadHandler);
     226              :         return node->GetMaxTimestamp();
     227              :     }
     228              :     ReadHandlerNode * GetReadHandlerNode(const ReadHandler * aReadHandler) { return FindReadHandlerNode(aReadHandler); }
     229              : #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST
     230              : 
     231              : protected:
     232              :     friend class chip::app::reporting::TestReportScheduler;
     233              : 
     234              :     /// @brief Find the ReadHandlerNode for a given ReadHandler pointer
     235              :     /// @param [in] aReadHandler ReadHandler pointer to look for in the ReadHandler nodes list
     236              :     /// @return Node Address if the node was found, nullptr otherwise
     237         3494 :     ReadHandlerNode * FindReadHandlerNode(const ReadHandler * aReadHandler)
     238              :     {
     239         3494 :         ReadHandlerNode * foundNode = nullptr;
     240         3494 :         mNodesPool.ForEachActiveObject([&foundNode, aReadHandler](ReadHandlerNode * node) {
     241        26990 :             if (node->GetReadHandler() == aReadHandler)
     242              :             {
     243         1458 :                 foundNode = node;
     244         1458 :                 return Loop::Break;
     245              :             }
     246              : 
     247        25532 :             return Loop::Continue;
     248              :         });
     249         3494 :         return foundNode;
     250              :     }
     251              : 
     252              :     ObjectPool<ReadHandlerNode, CHIP_IM_MAX_NUM_READS + CHIP_IM_MAX_NUM_SUBSCRIPTIONS> mNodesPool;
     253              :     TimerDelegate * mTimerDelegate;
     254              : };
     255              : }; // namespace reporting
     256              : }; // namespace app
     257              : }; // namespace chip
        

Generated by: LCOV version 2.0-1