Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020 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 : /**
20 : * @file
21 : * This file defines read handler for a CHIP Interaction Data model
22 : *
23 : */
24 :
25 : #pragma once
26 :
27 : #include <access/AccessControl.h>
28 : #include <app/AttributePathExpandIterator.h>
29 : #include <app/AttributePathParams.h>
30 : #include <app/AttributeValueEncoder.h>
31 : #include <app/CASESessionManager.h>
32 : #include <app/DataVersionFilter.h>
33 : #include <app/EventManagement.h>
34 : #include <app/EventPathParams.h>
35 : #include <app/MessageDef/AttributePathIBs.h>
36 : #include <app/MessageDef/DataVersionFilterIBs.h>
37 : #include <app/MessageDef/EventFilterIBs.h>
38 : #include <app/MessageDef/EventPathIBs.h>
39 : #include <app/OperationalSessionSetup.h>
40 : #include <app/SubscriptionResumptionSessionEstablisher.h>
41 : #include <app/SubscriptionResumptionStorage.h>
42 : #include <lib/core/CHIPCallback.h>
43 : #include <lib/core/CHIPCore.h>
44 : #include <lib/core/TLVDebug.h>
45 : #include <lib/support/CodeUtils.h>
46 : #include <lib/support/DLLUtil.h>
47 : #include <lib/support/LinkedList.h>
48 : #include <lib/support/logging/CHIPLogging.h>
49 : #include <messaging/ExchangeHolder.h>
50 : #include <messaging/ExchangeMgr.h>
51 : #include <messaging/Flags.h>
52 : #include <protocols/Protocols.h>
53 : #include <system/SystemPacketBuffer.h>
54 :
55 : // https://github.com/CHIP-Specifications/connectedhomeip-spec/blob/61a9d19e6af12fdfb0872bcff26d19de6c680a1a/src/Ch02_Architecture.adoc#1122-subscribe-interaction-limits
56 : inline constexpr uint16_t kSubscriptionMaxIntervalPublisherLimit = 3600; // seconds (60 minutes)
57 :
58 : namespace chip {
59 : namespace app {
60 :
61 : //
62 : // Forward declare the Engine (which is in a different namespace) to be able to use
63 : // it as a friend class below.
64 : //
65 : namespace reporting {
66 : class Engine;
67 : class TestReportingEngine;
68 : class ReportScheduler;
69 : class TestReportScheduler;
70 : } // namespace reporting
71 :
72 : class InteractionModelEngine;
73 : class TestInteractionModelEngine;
74 :
75 : /**
76 : * @class ReadHandler
77 : *
78 : * @brief The read handler is responsible for processing a read request, asking the attribute/event store
79 : * for the relevant data, and sending a reply.
80 : *
81 : */
82 : class ReadHandler : public Messaging::ExchangeDelegate
83 : {
84 : public:
85 : using SubjectDescriptor = Access::SubjectDescriptor;
86 :
87 : enum class InteractionType : uint8_t
88 : {
89 : Read,
90 : Subscribe,
91 : };
92 :
93 : /*
94 : * A callback used to interact with the application.
95 : */
96 : class ApplicationCallback
97 : {
98 : public:
99 : virtual ~ApplicationCallback() = default;
100 :
101 : /*
102 : * Called right after a SubscribeRequest has been parsed and processed. This notifies an interested application
103 : * of a subscription that is about to be established. It also provides an avenue for altering the parameters of the
104 : * subscription (specifically, the min/max negotiated intervals) or even outright rejecting the subscription for
105 : * application-specific reasons.
106 : *
107 : * TODO: Need a new IM status code to convey application-rejected subscribes. Currently, a Failure IM status code is sent
108 : * back to the subscriber, which isn't sufficient.
109 : *
110 : * To reject the subscription, a CHIP_ERROR code that is not equivalent to CHIP_NO_ERROR should be returned.
111 : *
112 : * More information about the set of paths associated with this subscription can be retrieved by calling the appropriate
113 : * Get* methods below.
114 : *
115 : * aReadHandler: Reference to the ReadHandler associated with the subscription.
116 : * aSecureSession: A reference to the underlying secure session associated with the subscription.
117 : *
118 : */
119 : virtual CHIP_ERROR OnSubscriptionRequested(ReadHandler & aReadHandler, Transport::SecureSession & aSecureSession)
120 : {
121 : return CHIP_NO_ERROR;
122 : }
123 :
124 : /*
125 : * Called after a subscription has been fully established.
126 : */
127 : virtual void OnSubscriptionEstablished(ReadHandler & aReadHandler){};
128 :
129 : /*
130 : * Called right before a subscription is about to get terminated. This is only called on subscriptions that were terminated
131 : * after they had been fully established (and therefore had called OnSubscriptionEstablished).
132 : * OnSubscriptionEstablishment().
133 : */
134 : virtual void OnSubscriptionTerminated(ReadHandler & aReadHandler){};
135 : };
136 :
137 : /*
138 : * A callback used to manage the lifetime of the ReadHandler object.
139 : */
140 : class ManagementCallback
141 : {
142 : public:
143 56 : virtual ~ManagementCallback() = default;
144 :
145 : /*
146 : * Method that signals to a registered callback that this object
147 : * has completed doing useful work and is now safe for release/destruction.
148 : */
149 : virtual void OnDone(ReadHandler & apReadHandlerObj) = 0;
150 :
151 : /*
152 : * Retrieve the ApplicationCallback (if a valid one exists) from our management entity. This avoids
153 : * storing multiple references to the application provided callback and having to subsequently manage lifetime
154 : * issues w.r.t the ReadHandler itself.
155 : */
156 : virtual ApplicationCallback * GetAppCallback() = 0;
157 :
158 : /*
159 : * Retrieve the InteractionalModelEngine that holds this ReadHandler.
160 : */
161 : virtual InteractionModelEngine * GetInteractionModelEngine() = 0;
162 : };
163 :
164 : // TODO (#27675) : Merge existing callback and observer into one class and have an observer pool in the Readhandler to notify
165 : // every
166 : /*
167 : * Observer class for ReadHandler, meant to allow multiple objects to observe the ReadHandler. Currently only one observer is
168 : * supported but all above callbacks should be merged into observer type and an observer pool should be added to allow multiple
169 : * objects to observe ReadHandler
170 : */
171 : class Observer
172 : {
173 : public:
174 0 : virtual ~Observer() = default;
175 :
176 : /// @brief Callback invoked to notify a subscription was successfully established for the ReadHandler
177 : /// @param[in] apReadHandler ReadHandler that completed its subscription
178 : virtual void OnSubscriptionEstablished(ReadHandler * apReadHandler) = 0;
179 :
180 : /// @brief Callback invoked when a ReadHandler went from a non reportable state to a reportable state. Indicates to the
181 : /// observer that a report should be emitted when the min interval allows it.
182 : ///
183 : /// This will only be invoked for subscribe-type ReadHandler objects, and only after
184 : /// OnSubscriptionEstablished has been called.
185 : ///
186 : /// @param[in] apReadHandler ReadHandler that became dirty and in HandlerState::CanStartReporting state
187 : virtual void OnBecameReportable(ReadHandler * apReadHandler) = 0;
188 :
189 : /// @brief Callback invoked when the read handler needs to make sure to send a message to the subscriber within the next
190 : /// maxInterval time period.
191 : /// @param[in] apReadHandler ReadHandler that has generated a report
192 : virtual void OnSubscriptionReportSent(ReadHandler * apReadHandler) = 0;
193 :
194 : /// @brief Callback invoked when a ReadHandler is getting removed so it can be unregistered
195 : /// @param[in] apReadHandler ReadHandler getting destroyed
196 : virtual void OnReadHandlerDestroyed(ReadHandler * apReadHandler) = 0;
197 : };
198 :
199 : /*
200 : * Destructor - as part of destruction, it will abort the exchange context
201 : * if a valid one still exists.
202 : *
203 : * See Abort() for details on when that might occur.
204 : */
205 : ~ReadHandler() override;
206 :
207 : /**
208 : *
209 : * Constructor.
210 : *
211 : * The callback passed in has to outlive this handler object.
212 : *
213 : */
214 : ReadHandler(ManagementCallback & apCallback, Messaging::ExchangeContext * apExchangeContext, InteractionType aInteractionType,
215 : Observer * observer, DataModel::Provider * apDataModel);
216 :
217 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
218 : /**
219 : *
220 : * Constructor in preparation for resuming a persisted subscription
221 : *
222 : * The callback passed in has to outlive this handler object.
223 : *
224 : */
225 : ReadHandler(ManagementCallback & apCallback, Observer * observer, DataModel::Provider * apDataModel);
226 : #endif
227 :
228 477 : const SingleLinkedListNode<AttributePathParams> * GetAttributePathList() const { return mpAttributePathList; }
229 2809 : const SingleLinkedListNode<EventPathParams> * GetEventPathList() const { return mpEventPathList; }
230 4147 : const SingleLinkedListNode<DataVersionFilter> * GetDataVersionFilterList() const { return mpDataVersionFilterList; }
231 :
232 : /**
233 : * @brief Returns the reporting intervals that will used by the ReadHandler for the subscription being requested.
234 : * After the subscription is established, these will be the set reporting intervals and cannot be changed.
235 : *
236 : * @param[out] aMinInterval minimum time delta between two reports for the subscription
237 : * @param[in] aMaxInterval maximum time delta between two reports for the subscription
238 : */
239 67 : void GetReportingIntervals(uint16_t & aMinInterval, uint16_t & aMaxInterval) const
240 : {
241 67 : aMinInterval = mMinIntervalFloorSeconds;
242 67 : aMaxInterval = mMaxInterval;
243 67 : }
244 :
245 : /**
246 : * @brief Returns the maximum reporting interval that was initially requested by the subscriber
247 : * This is the same value as the mMaxInterval member if the max interval is not changed by the publisher.
248 : *
249 : * @note If the device is an ICD, the MaxInterval of a subscription is automatically set to a multiple of the IdleModeDuration.
250 : * This function is the only way to get the requested max interval once the OnSubscriptionRequested application callback
251 : * is called.
252 : *
253 : * @return uint16_t subscriber requested maximum reporting interval
254 : */
255 : inline uint16_t GetSubscriberRequestedMaxInterval() const { return mSubscriberRequestedMaxInterval; }
256 :
257 : CHIP_ERROR SetMinReportingIntervalForTests(uint16_t aMinInterval)
258 : {
259 : VerifyOrReturnError(IsIdle(), CHIP_ERROR_INCORRECT_STATE);
260 : VerifyOrReturnError(aMinInterval <= mMaxInterval, CHIP_ERROR_INVALID_ARGUMENT);
261 : // Ensures the new min interval is higher than the subscriber established one.
262 : mMinIntervalFloorSeconds = std::max(mMinIntervalFloorSeconds, aMinInterval);
263 : return CHIP_NO_ERROR;
264 : }
265 :
266 : /*
267 : * Set the maximum reporting interval for the subscription. This SHALL only be called
268 : * from the OnSubscriptionRequested callback above. The restriction is as below
269 : * MinIntervalFloor ≤ MaxInterval ≤ MAX(SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT, MaxIntervalCeiling)
270 : * Where SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT is set to 60m in the spec.
271 : */
272 : CHIP_ERROR SetMaxReportingInterval(uint16_t aMaxInterval)
273 : {
274 : VerifyOrReturnError(IsIdle(), CHIP_ERROR_INCORRECT_STATE);
275 : VerifyOrReturnError(mMinIntervalFloorSeconds <= aMaxInterval, CHIP_ERROR_INVALID_ARGUMENT);
276 : VerifyOrReturnError(aMaxInterval <= std::max(GetPublisherSelectedIntervalLimit(), mSubscriberRequestedMaxInterval),
277 : CHIP_ERROR_INVALID_ARGUMENT);
278 : mMaxInterval = aMaxInterval;
279 : return CHIP_NO_ERROR;
280 : }
281 :
282 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
283 : /**
284 : *
285 : * @brief Initialize a ReadHandler for a resumed subsciption
286 : *
287 : * Used after the SubscriptionResumptionSessionEstablisher establishs the CASE session
288 : */
289 : void OnSubscriptionResumed(const SessionHandle & sessionHandle, SubscriptionResumptionSessionEstablisher & sessionEstablisher);
290 : #endif
291 :
292 : private:
293 : PriorityLevel GetCurrentPriority() const { return mCurrentPriority; }
294 1906 : EventNumber & GetEventMin() { return mEventMin; }
295 :
296 : /**
297 : * Returns SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT
298 : * For an ICD publisher, this SHALL be set to the idle mode duration.
299 : * Otherwise, this SHALL be set to 60 minutes.
300 : */
301 : uint16_t GetPublisherSelectedIntervalLimit();
302 :
303 : enum class ReadHandlerFlags : uint8_t
304 : {
305 : // The flag indicating we are in the middle of a series of chunked report messages, this flag will be cleared during
306 : // sending last chunked message.
307 : ChunkedReport = (1 << 0),
308 :
309 : // Tracks whether we're in the initial phase of receiving priming
310 : // reports, which is always true for reads and true for subscriptions
311 : // prior to receiving a subscribe response.
312 : PrimingReports = (1 << 1),
313 : ActiveSubscription = (1 << 2),
314 : FabricFiltered = (1 << 3),
315 : // For subscriptions, we record the dirty set generation when we started to generate the last report.
316 : // The mCurrentReportsBeginGeneration records the generation at the start of the current report. This only/
317 : // has a meaningful value while IsReporting() is true.
318 : //
319 : // mPreviousReportsBeginGeneration will be set to mCurrentReportsBeginGeneration after we send the last
320 : // chunk of the current report. Anything that was dirty with a generation earlier than
321 : // mPreviousReportsBeginGeneration has had its value sent to the client.
322 : // when receiving initial request, it needs mark current handler as dirty.
323 : // when there is urgent event, it needs mark current handler as dirty.
324 : ForceDirty = (1 << 4),
325 :
326 : // Don't need the response for report data if true
327 : SuppressResponse = (1 << 5),
328 : };
329 :
330 : /**
331 : * Process a read/subscribe request. Parts of the processing may end up being asynchronous, but the ReadHandler
332 : * guarantees that it will call Shutdown on itself when processing is done (including if OnReadInitialRequest
333 : * returns an error).
334 : *
335 : * @retval #Others If fails to process read request
336 : * @retval #CHIP_NO_ERROR On success.
337 : *
338 : */
339 : void OnInitialRequest(System::PacketBufferHandle && aPayload);
340 :
341 : /**
342 : * Send ReportData to initiator
343 : *
344 : * @param[in] aPayload A payload that has read request data
345 : * @param[in] aMoreChunks A flags indicating there will be more chunks expected to be sent for this read request
346 : *
347 : * @retval #Others If fails to send report data
348 : * @retval #CHIP_NO_ERROR On success.
349 : *
350 : * If an error is returned, the ReadHandler guarantees that it is not in
351 : * a state where it's waiting for a response.
352 : */
353 : CHIP_ERROR SendReportData(System::PacketBufferHandle && aPayload, bool aMoreChunks);
354 :
355 : /*
356 : * Get the appropriate size of a packet buffer to allocate for encoding a Report message.
357 : * This size might depend on the underlying session used by the ReadHandler.
358 : *
359 : * The size returned here is the size not including the various prepended headers
360 : * (what System::PacketBuffer calls the "available size").
361 : */
362 : size_t GetReportBufferMaxSize();
363 :
364 : /**
365 : * Returns whether this ReadHandler represents a subscription that was created by the other side of the provided exchange.
366 : */
367 : bool IsFromSubscriber(Messaging::ExchangeContext & apExchangeContext) const;
368 :
369 : bool IsIdle() const { return mState == HandlerState::Idle; }
370 :
371 : /// @brief Returns whether the ReadHandler is in a state where it can send a report and there is data to report.
372 8607 : bool ShouldStartReporting() const
373 : {
374 : // Important: Anything that changes ShouldStartReporting() from false to true
375 : // (which can only happen for subscriptions) must call
376 : // mObserver->OnBecameReportable(this).
377 8607 : return CanStartReporting() && (ShouldReportUnscheduled() || IsDirty());
378 : }
379 : /// @brief CanStartReporting() is true if the ReadHandler is in a state where it could generate
380 : /// a (possibly empty) report if someone asked it to.
381 16645 : bool CanStartReporting() const { return mState == HandlerState::CanStartReporting; }
382 : /// @brief ShouldReportUnscheduled() is true if the ReadHandler should be asked to generate reports
383 : /// without consulting the report scheduler.
384 7478 : bool ShouldReportUnscheduled() const
385 : {
386 7478 : return CanStartReporting() && (IsType(ReadHandler::InteractionType::Read) || IsPriming());
387 : }
388 7347 : bool IsAwaitingReportResponse() const { return mState == HandlerState::AwaitingReportResponse; }
389 :
390 : // Resets the path iterator to the beginning of the whole report for generating a series of new reports.
391 : void ResetPathIterator();
392 :
393 : CHIP_ERROR ProcessDataVersionFilterList(DataVersionFilterIBs::Parser & aDataVersionFilterListParser);
394 :
395 : // if current priority is in the middle, it has valid snapshoted last event number, it check cleaness via comparing
396 : // with snapshotted last event number. if current priority is in the end, no valid
397 : // sanpshotted last event, check with latest last event number, re-setup snapshoted checkpoint, and compare again.
398 : bool CheckEventClean(EventManagement & aEventManager);
399 :
400 22592 : bool IsType(InteractionType type) const { return (mInteractionType == type); }
401 1447 : bool IsChunkedReport() const { return mFlags.Has(ReadHandlerFlags::ChunkedReport); }
402 : // Is reporting indicates whether we are in the middle of a series chunks. As we will set mIsChunkedReport on the first chunk
403 : // and clear that flag on the last chunk, we can use mIsChunkedReport to indicate this state.
404 3779 : bool IsReporting() const { return mFlags.Has(ReadHandlerFlags::ChunkedReport); }
405 7627 : bool IsPriming() const { return mFlags.Has(ReadHandlerFlags::PrimingReports); }
406 42 : bool IsActiveSubscription() const { return mFlags.Has(ReadHandlerFlags::ActiveSubscription); }
407 4350 : bool IsFabricFiltered() const { return mFlags.Has(ReadHandlerFlags::FabricFiltered); }
408 : CHIP_ERROR OnSubscribeRequest(Messaging::ExchangeContext * apExchangeContext, System::PacketBufferHandle && aPayload);
409 370 : void GetSubscriptionId(SubscriptionId & aSubscriptionId) const { aSubscriptionId = mSubscriptionId; }
410 10728 : AttributePathExpandIterator * GetAttributePathExpandIterator() { return &mAttributePathExpandIterator; }
411 :
412 : /// @brief Notifies the read handler that a set of attribute paths has been marked dirty. This will schedule a reporting engine
413 : /// run if the change to the attribute path makes the ReadHandler reportable.
414 : /// @param aAttributeChanged Path to the attribute that was changed.
415 : void AttributePathIsDirty(const AttributePathParams & aAttributeChanged);
416 2824 : bool IsDirty() const
417 : {
418 2824 : return (mDirtyGeneration > mPreviousReportsBeginGeneration) || mFlags.Has(ReadHandlerFlags::ForceDirty);
419 : }
420 1010 : void ClearForceDirtyFlag() { ClearStateFlag(ReadHandlerFlags::ForceDirty); }
421 9 : NodeId GetInitiatorNodeId() const
422 : {
423 9 : auto session = GetSession();
424 9 : return session == nullptr ? kUndefinedNodeId : session->GetPeerNodeId();
425 : }
426 :
427 230 : FabricIndex GetAccessingFabricIndex() const
428 : {
429 230 : auto session = GetSession();
430 230 : return session == nullptr ? kUndefinedFabricIndex : session->GetFabricIndex();
431 : }
432 :
433 : Transport::SecureSession * GetSession() const;
434 5338 : SubjectDescriptor GetSubjectDescriptor() const { return GetSession()->GetSubjectDescriptor(); }
435 :
436 82 : auto GetTransactionStartGeneration() const { return mTransactionStartGeneration; }
437 :
438 : /// @brief Forces the read handler into a dirty state, regardless of what's going on with attributes.
439 : /// This can lead to scheduling of a reporting run immediately, if the min interval has been reached,
440 : /// or after the min interval is reached if it has not yet been reached.
441 : void ForceDirtyState();
442 :
443 4350 : const AttributeEncodeState & GetAttributeEncodeState() const { return mAttributeEncoderState; }
444 4350 : void SetAttributeEncodeState(const AttributeEncodeState & aState) { mAttributeEncoderState = aState; }
445 20 : uint32_t GetLastWrittenEventsBytes() const { return mLastWrittenEventsBytes; }
446 :
447 : // Returns the number of interested paths, including wildcard and concrete paths.
448 4513 : size_t GetAttributePathCount() const { return mpAttributePathList == nullptr ? 0 : mpAttributePathList->Count(); };
449 4513 : size_t GetEventPathCount() const { return mpEventPathList == nullptr ? 0 : mpEventPathList->Count(); };
450 : size_t GetDataVersionFilterCount() const { return mpDataVersionFilterList == nullptr ? 0 : mpDataVersionFilterList->Count(); };
451 :
452 : CHIP_ERROR SendStatusReport(Protocols::InteractionModel::Status aStatus);
453 :
454 : friend class TestReadInteraction;
455 : friend class chip::app::reporting::TestReportingEngine;
456 : friend class chip::app::reporting::TestReportScheduler;
457 :
458 : //
459 : // The engine needs to be able to Abort/Close a ReadHandler instance upon completion of work for a given read/subscribe
460 : // interaction. We do not want to make these methods public just to give an adjacent class in the IM access, since public
461 : // should really be taking application usage considerations as well. Hence, make it a friend.
462 : //
463 : friend class chip::app::reporting::Engine;
464 : friend class chip::app::InteractionModelEngine;
465 : friend class TestInteractionModelEngine;
466 :
467 : // The report scheduler needs to be able to access StateFlag private functions ShouldStartReporting(), CanStartReporting(),
468 : // ForceDirtyState() and IsDirty() to know when to schedule a run so it is declared as a friend class.
469 : friend class chip::app::reporting::ReportScheduler;
470 :
471 : enum class HandlerState : uint8_t
472 : {
473 : Idle, ///< The handler has been initialized and is ready
474 : CanStartReporting, ///< The handler has is now capable of generating reports and may generate one immediately
475 : ///< or later when other criteria are satisfied (e.g hold-off for min reporting interval).
476 : AwaitingReportResponse, ///< The handler has sent the report to the client and is awaiting a status response.
477 : AwaitingDestruction, ///< The object has completed its work and is awaiting destruction by the application.
478 : };
479 :
480 : enum class CloseOptions
481 : {
482 : kDropPersistedSubscription,
483 : kKeepPersistedSubscription
484 : };
485 : /**
486 : * Called internally to signal the completion of all work on this objecta and signal to a registered callback that it's
487 : * safe to release this object.
488 : *
489 : * @param options This specifies whether to drop or keep the subscription
490 : *
491 : */
492 : void Close(CloseOptions options = CloseOptions::kDropPersistedSubscription);
493 :
494 : CHIP_ERROR SendSubscribeResponse();
495 : CHIP_ERROR ProcessSubscribeRequest(System::PacketBufferHandle && aPayload);
496 : CHIP_ERROR ProcessReadRequest(System::PacketBufferHandle && aPayload);
497 : CHIP_ERROR ProcessAttributePaths(AttributePathIBs::Parser & aAttributePathListParser);
498 : CHIP_ERROR ProcessEventPaths(EventPathIBs::Parser & aEventPathsParser);
499 : CHIP_ERROR ProcessEventFilters(EventFilterIBs::Parser & aEventFiltersParser);
500 : CHIP_ERROR OnStatusResponse(Messaging::ExchangeContext * apExchangeContext, System::PacketBufferHandle && aPayload,
501 : bool & aSendStatusResponse);
502 : CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader,
503 : System::PacketBufferHandle && aPayload) override;
504 : void OnResponseTimeout(Messaging::ExchangeContext * apExchangeContext) override;
505 : void MoveToState(const HandlerState aTargetState);
506 :
507 : const char * GetStateStr() const;
508 :
509 : void PersistSubscription();
510 :
511 : /// @brief Modifies a state flag in the read handler. If the read handler went from a
512 : /// non-reportable state to a reportable state, schedules a reporting engine run.
513 : /// @param aFlag Flag to set
514 : /// @param aValue Flag new value
515 : void SetStateFlag(ReadHandlerFlags aFlag, bool aValue = true);
516 :
517 : /// @brief This function call SetStateFlag with the flag value set to false, thus possibly emitting a report
518 : /// generation.
519 : /// @param aFlag Flag to clear
520 : void ClearStateFlag(ReadHandlerFlags aFlag);
521 :
522 : AttributePathExpandIterator mAttributePathExpandIterator;
523 :
524 : // The current generation of the reporting engine dirty set the last time we were notified that a path we're interested in was
525 : // marked dirty.
526 : //
527 : // This allows us to detemine whether any paths we care about might have
528 : // been marked dirty after we had already sent reports for them, which would
529 : // mean we should report those paths again, by comparing this generation to the
530 : // current generation when we started sending the last set reports that we completed.
531 : //
532 : // This allows us to reset the iterator to the beginning of the current
533 : // cluster instead of the beginning of the whole report in AttributePathIsDirty, without
534 : // permanently missing dirty any paths.
535 : uint64_t mDirtyGeneration = 0;
536 :
537 : // For subscriptions, we record the timestamp when we started to generate the last report.
538 : // The mCurrentReportsBeginGeneration records the timestamp for the current report, which won;t be used for checking if this
539 : // ReadHandler is dirty.
540 : // mPreviousReportsBeginGeneration will be set to mCurrentReportsBeginGeneration after we sent the last chunk of the current
541 : // report.
542 : uint64_t mPreviousReportsBeginGeneration = 0;
543 : uint64_t mCurrentReportsBeginGeneration = 0;
544 : /*
545 : * (mDirtyGeneration = b > a, this is a dirty read handler)
546 : * +- Start Report -> mCurrentReportsBeginGeneration = c
547 : * | +- AttributePathIsDirty (Attribute Y) -> mDirtyGeneration = d
548 : * | | +- Last Chunk -> mPreviousReportsBeginGeneration = mCurrentReportsBeginGeneration = c
549 : * | | | +- (mDirtyGeneration = d) > (mPreviousReportsBeginGeneration = c), this is a dirty read handler
550 : * | | | | Attribute X has a dirty generation less than c, Attribute Y has a dirty generation larger than c
551 : * | | | | So Y will be included in the report but X will not be inclued in this report.
552 : * -a--b--c------d-----e---f---> Generation
553 : * | |
554 : * | +- AttributePathIsDirty (Attribute X) (mDirtyGeneration = b)
555 : * +- mPreviousReportsBeginGeneration
556 : * For read handler, if mDirtyGeneration > mPreviousReportsBeginGeneration, then we regard it as a dirty read handler, and it
557 : * should generate report on timeout reached.
558 : */
559 :
560 : // When we don't have enough resources for a new subscription, the oldest subscription might be evicted by interaction model
561 : // engine, the "oldest" subscription is the subscription with the smallest generation.
562 : uint64_t mTransactionStartGeneration = 0;
563 :
564 : SubscriptionId mSubscriptionId = 0;
565 : uint16_t mMinIntervalFloorSeconds = 0;
566 : uint16_t mMaxInterval = 0;
567 : uint16_t mSubscriberRequestedMaxInterval = 0;
568 :
569 : EventNumber mEventMin = 0;
570 :
571 : // The last schedule event number snapshoted in the beginning when preparing to fill new events to reports
572 : EventNumber mLastScheduledEventNumber = 0;
573 :
574 : // TODO: We should shutdown the transaction when the session expires.
575 : SessionHolder mSessionHandle;
576 :
577 : Messaging::ExchangeHolder mExchangeCtx;
578 : #if CHIP_CONFIG_UNSAFE_SUBSCRIPTION_EXCHANGE_MANAGER_USE
579 : // TODO: this should be replaced by a pointer to the InteractionModelEngine that created the ReadHandler
580 : // once InteractionModelEngine is no longer a singleton (see issue 23625)
581 : Messaging::ExchangeManager * mExchangeMgr = nullptr;
582 : #endif // CHIP_CONFIG_UNSAFE_SUBSCRIPTION_EXCHANGE_MANAGER_USE
583 :
584 : SingleLinkedListNode<AttributePathParams> * mpAttributePathList = nullptr;
585 : SingleLinkedListNode<EventPathParams> * mpEventPathList = nullptr;
586 : SingleLinkedListNode<DataVersionFilter> * mpDataVersionFilterList = nullptr;
587 :
588 : ManagementCallback & mManagementCallback;
589 :
590 : uint32_t mLastWrittenEventsBytes = 0;
591 :
592 : // The detailed encoding state for a single attribute, used by list chunking feature.
593 : // The size of AttributeEncoderState is 2 bytes for now.
594 : AttributeEncodeState mAttributeEncoderState;
595 :
596 : // Current Handler state
597 : HandlerState mState = HandlerState::Idle;
598 : PriorityLevel mCurrentPriority = PriorityLevel::Invalid;
599 : BitFlags<ReadHandlerFlags> mFlags;
600 : InteractionType mInteractionType = InteractionType::Read;
601 :
602 : // TODO (#27675): Merge all observers into one and that one will dispatch the callbacks to the right place.
603 : Observer * mObserver = nullptr;
604 : };
605 :
606 : } // namespace app
607 : } // namespace chip
|