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 46 : 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 0 : virtual CHIP_ERROR OnSubscriptionRequested(ReadHandler & aReadHandler, Transport::SecureSession & aSecureSession)
120 : {
121 0 : return CHIP_NO_ERROR;
122 : }
123 :
124 : /*
125 : * Called after a subscription has been fully established.
126 : */
127 0 : 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 0 : 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 110 : 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 66 : 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);
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);
226 : #endif
227 :
228 477 : const SingleLinkedListNode<AttributePathParams> * GetAttributePathList() const { return mpAttributePathList; }
229 2884 : const SingleLinkedListNode<EventPathParams> * GetEventPathList() const { return mpEventPathList; }
230 4722 : 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 449 : void GetReportingIntervals(uint16_t & aMinInterval, uint16_t & aMaxInterval) const
240 : {
241 449 : aMinInterval = mMinIntervalFloorSeconds;
242 449 : aMaxInterval = mMaxInterval;
243 449 : }
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 10 : inline uint16_t GetSubscriberRequestedMaxInterval() const { return mSubscriberRequestedMaxInterval; }
256 :
257 10 : CHIP_ERROR SetMinReportingIntervalForTests(uint16_t aMinInterval)
258 : {
259 10 : VerifyOrReturnError(IsIdle(), CHIP_ERROR_INCORRECT_STATE);
260 10 : VerifyOrReturnError(aMinInterval <= mMaxInterval, CHIP_ERROR_INVALID_ARGUMENT);
261 : // Ensures the new min interval is higher than the subscriber established one.
262 10 : mMinIntervalFloorSeconds = std::max(mMinIntervalFloorSeconds, aMinInterval);
263 10 : 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 : * For ICD publishers, this is set to the IdleModeDuration defined in the ICD Management Cluster.
272 : * If the new max interval is less than the idle mode duration for an ICD device, the function will return
273 : * CHIP_ERROR_INVALID_ARGUMENT.
274 : */
275 31 : CHIP_ERROR SetMaxReportingInterval(uint16_t aMaxInterval)
276 : {
277 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
278 : if (aMaxInterval < mMaxInterval)
279 : {
280 : ChipLogProgress(DataManagement,
281 : "Fail to set MaxReportingInterval to %d as it is less than the current MaxInterval %d for ICD device",
282 : aMaxInterval, mMaxInterval);
283 : return CHIP_ERROR_INVALID_ARGUMENT;
284 : }
285 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
286 31 : VerifyOrReturnError(IsIdle(), CHIP_ERROR_INCORRECT_STATE);
287 29 : VerifyOrReturnError(mMinIntervalFloorSeconds <= aMaxInterval, CHIP_ERROR_INVALID_ARGUMENT);
288 27 : VerifyOrReturnError(aMaxInterval <= std::max(GetPublisherSelectedIntervalLimit(), mSubscriberRequestedMaxInterval),
289 : CHIP_ERROR_INVALID_ARGUMENT);
290 21 : mMaxInterval = aMaxInterval;
291 21 : return CHIP_NO_ERROR;
292 : }
293 :
294 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
295 : /**
296 : *
297 : * @brief Initialize a ReadHandler for a resumed subsciption
298 : *
299 : * Used after the SubscriptionResumptionSessionEstablisher establishs the CASE session
300 : */
301 : void OnSubscriptionResumed(const SessionHandle & sessionHandle, SubscriptionResumptionSessionEstablisher & sessionEstablisher);
302 : #endif
303 :
304 : private:
305 : PriorityLevel GetCurrentPriority() const { return mCurrentPriority; }
306 1980 : EventNumber & GetEventMin() { return mEventMin; }
307 :
308 : /**
309 : * Returns SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT
310 : * For an ICD publisher, this SHALL be set to the idle mode duration.
311 : * Otherwise, this SHALL be set to 60 minutes.
312 : */
313 : uint16_t GetPublisherSelectedIntervalLimit();
314 :
315 : enum class ReadHandlerFlags : uint8_t
316 : {
317 : // The flag indicating we are in the middle of a series of chunked report messages, this flag will be cleared during
318 : // sending last chunked message.
319 : ChunkedReport = (1 << 0),
320 :
321 : // Tracks whether we're in the initial phase of receiving priming
322 : // reports, which is always true for reads and true for subscriptions
323 : // prior to receiving a subscribe response.
324 : PrimingReports = (1 << 1),
325 : ActiveSubscription = (1 << 2),
326 : FabricFiltered = (1 << 3),
327 : // For subscriptions, we record the dirty set generation when we started to generate the last report.
328 : // The mCurrentReportsBeginGeneration records the generation at the start of the current report. This only/
329 : // has a meaningful value while IsReporting() is true.
330 : //
331 : // mPreviousReportsBeginGeneration will be set to mCurrentReportsBeginGeneration after we send the last
332 : // chunk of the current report. Anything that was dirty with a generation earlier than
333 : // mPreviousReportsBeginGeneration has had its value sent to the client.
334 : // when receiving initial request, it needs mark current handler as dirty.
335 : // when there is urgent event, it needs mark current handler as dirty.
336 : ForceDirty = (1 << 4),
337 :
338 : // Don't need the response for report data if true
339 : SuppressResponse = (1 << 5),
340 : };
341 :
342 : /**
343 : * Process a read/subscribe request. Parts of the processing may end up being asynchronous, but the ReadHandler
344 : * guarantees that it will call Shutdown on itself when processing is done (including if OnReadInitialRequest
345 : * returns an error).
346 : *
347 : * @retval #Others If fails to process read request
348 : * @retval #CHIP_NO_ERROR On success.
349 : *
350 : */
351 : void OnInitialRequest(System::PacketBufferHandle && aPayload);
352 :
353 : /**
354 : * Send ReportData to initiator
355 : *
356 : * @param[in] aPayload A payload that has read request data
357 : * @param[in] aMoreChunks A flags indicating there will be more chunks expected to be sent for this read request
358 : *
359 : * @retval #Others If fails to send report data
360 : * @retval #CHIP_NO_ERROR On success.
361 : *
362 : * If an error is returned, the ReadHandler guarantees that it is not in
363 : * a state where it's waiting for a response.
364 : */
365 : CHIP_ERROR SendReportData(System::PacketBufferHandle && aPayload, bool aMoreChunks);
366 :
367 : /*
368 : * Get the appropriate size of a packet buffer to allocate for encoding a Report message.
369 : * This size might depend on the underlying session used by the ReadHandler.
370 : *
371 : * The size returned here is the size not including the various prepended headers
372 : * (what System::PacketBuffer calls the "available size").
373 : */
374 : size_t GetReportBufferMaxSize();
375 :
376 : /**
377 : * Returns whether this ReadHandler represents a subscription that was created by the other side of the provided exchange.
378 : */
379 : bool IsFromSubscriber(Messaging::ExchangeContext & apExchangeContext) const;
380 :
381 41 : bool IsIdle() const { return mState == HandlerState::Idle; }
382 :
383 : /// @brief Returns whether the ReadHandler is in a state where it can send a report and there is data to report.
384 10806 : bool ShouldStartReporting() const
385 : {
386 : // Important: Anything that changes ShouldStartReporting() from false to true
387 : // (which can only happen for subscriptions) must call
388 : // mObserver->OnBecameReportable(this).
389 10806 : return CanStartReporting() && (ShouldReportUnscheduled() || IsDirty());
390 : }
391 : /// @brief CanStartReporting() is true if the ReadHandler is in a state where it could generate
392 : /// a (possibly empty) report if someone asked it to.
393 21307 : bool CanStartReporting() const { return mState == HandlerState::CanStartReporting; }
394 : /// @brief ShouldReportUnscheduled() is true if the ReadHandler should be asked to generate reports
395 : /// without consulting the report scheduler.
396 8828 : bool ShouldReportUnscheduled() const
397 : {
398 8828 : return CanStartReporting() && (IsType(ReadHandler::InteractionType::Read) || IsPriming());
399 : }
400 7791 : bool IsAwaitingReportResponse() const { return mState == HandlerState::AwaitingReportResponse; }
401 :
402 : // Resets the path iterator to the beginning of the whole report for generating a series of new reports.
403 : void ResetPathIterator();
404 :
405 : CHIP_ERROR ProcessDataVersionFilterList(DataVersionFilterIBs::Parser & aDataVersionFilterListParser);
406 :
407 : // if current priority is in the middle, it has valid snapshoted last event number, it check cleaness via comparing
408 : // with snapshotted last event number. if current priority is in the end, no valid
409 : // sanpshotted last event, check with latest last event number, re-setup snapshoted checkpoint, and compare again.
410 : bool CheckEventClean(EventManagement & aEventManager);
411 :
412 27924 : bool IsType(InteractionType type) const { return (mInteractionType == type); }
413 1513 : bool IsChunkedReport() const { return mFlags.Has(ReadHandlerFlags::ChunkedReport); }
414 : // Is reporting indicates whether we are in the middle of a series chunks. As we will set mIsChunkedReport on the first chunk
415 : // and clear that flag on the last chunk, we can use mIsChunkedReport to indicate this state.
416 3927 : bool IsReporting() const { return mFlags.Has(ReadHandlerFlags::ChunkedReport); }
417 10852 : bool IsPriming() const { return mFlags.Has(ReadHandlerFlags::PrimingReports); }
418 42 : bool IsActiveSubscription() const { return mFlags.Has(ReadHandlerFlags::ActiveSubscription); }
419 4925 : bool IsFabricFiltered() const { return mFlags.Has(ReadHandlerFlags::FabricFiltered); }
420 : CHIP_ERROR OnSubscribeRequest(Messaging::ExchangeContext * apExchangeContext, System::PacketBufferHandle && aPayload);
421 441 : void GetSubscriptionId(SubscriptionId & aSubscriptionId) const { aSubscriptionId = mSubscriptionId; }
422 1980 : AttributePathExpandIterator::Position & AttributeIterationPosition() { return mAttributePathExpandPosition; }
423 :
424 : /// @brief Notifies the read handler that a set of attribute paths has been marked dirty. This will schedule a reporting engine
425 : /// run if the change to the attribute path makes the ReadHandler reportable.
426 : /// @param aAttributeChanged Path to the attribute that was changed.
427 : void AttributePathIsDirty(DataModel::Provider * apDataModel, const AttributePathParams & aAttributeChanged);
428 4497 : bool IsDirty() const
429 : {
430 4497 : return (mDirtyGeneration > mPreviousReportsBeginGeneration) || mFlags.Has(ReadHandlerFlags::ForceDirty);
431 : }
432 1088 : void ClearForceDirtyFlag() { ClearStateFlag(ReadHandlerFlags::ForceDirty); }
433 144 : NodeId GetInitiatorNodeId() const
434 : {
435 144 : auto session = GetSession();
436 144 : return session == nullptr ? kUndefinedNodeId : session->GetPeerNodeId();
437 : }
438 :
439 300 : FabricIndex GetAccessingFabricIndex() const
440 : {
441 300 : auto session = GetSession();
442 300 : return session == nullptr ? kUndefinedFabricIndex : session->GetFabricIndex();
443 : }
444 :
445 : Transport::SecureSession * GetSession() const;
446 5916 : SubjectDescriptor GetSubjectDescriptor() const { return GetSession()->GetSubjectDescriptor(); }
447 4925 : bool AllowsLargePayload() const { return GetSession()->AllowsLargePayload(); }
448 :
449 82 : auto GetTransactionStartGeneration() const { return mTransactionStartGeneration; }
450 :
451 : /// @brief Forces the read handler into a dirty state, regardless of what's going on with attributes.
452 : /// This can lead to scheduling of a reporting run immediately, if the min interval has been reached,
453 : /// or after the min interval is reached if it has not yet been reached.
454 : void ForceDirtyState();
455 :
456 4925 : const AttributeEncodeState & GetAttributeEncodeState() const { return mAttributeEncoderState; }
457 4927 : void SetAttributeEncodeState(const AttributeEncodeState & aState) { mAttributeEncoderState = aState; }
458 20 : uint32_t GetLastWrittenEventsBytes() const { return mLastWrittenEventsBytes; }
459 :
460 : // Returns the number of interested paths, including wildcard and concrete paths.
461 6593 : size_t GetAttributePathCount() const { return mpAttributePathList == nullptr ? 0 : mpAttributePathList->Count(); };
462 6593 : size_t GetEventPathCount() const { return mpEventPathList == nullptr ? 0 : mpEventPathList->Count(); };
463 : size_t GetDataVersionFilterCount() const { return mpDataVersionFilterList == nullptr ? 0 : mpDataVersionFilterList->Count(); };
464 :
465 : CHIP_ERROR SendStatusReport(Protocols::InteractionModel::Status aStatus);
466 :
467 : friend class TestReadInteraction;
468 : friend class chip::app::reporting::TestReportingEngine;
469 : friend class chip::app::reporting::TestReportScheduler;
470 :
471 : //
472 : // The engine needs to be able to Abort/Close a ReadHandler instance upon completion of work for a given read/subscribe
473 : // interaction. We do not want to make these methods public just to give an adjacent class in the IM access, since public
474 : // should really be taking application usage considerations as well. Hence, make it a friend.
475 : //
476 : friend class chip::app::reporting::Engine;
477 : friend class chip::app::InteractionModelEngine;
478 : friend class TestInteractionModelEngine;
479 :
480 : // The report scheduler needs to be able to access StateFlag private functions ShouldStartReporting(), CanStartReporting(),
481 : // ForceDirtyState() and IsDirty() to know when to schedule a run so it is declared as a friend class.
482 : friend class chip::app::reporting::ReportScheduler;
483 :
484 : enum class HandlerState : uint8_t
485 : {
486 : Idle, ///< The handler has been initialized and is ready
487 : CanStartReporting, ///< The handler has is now capable of generating reports and may generate one immediately
488 : ///< or later when other criteria are satisfied (e.g hold-off for min reporting interval).
489 : AwaitingReportResponse, ///< The handler has sent the report to the client and is awaiting a status response.
490 : AwaitingDestruction, ///< The object has completed its work and is awaiting destruction by the application.
491 : };
492 :
493 : enum class CloseOptions
494 : {
495 : kDropPersistedSubscription,
496 : kKeepPersistedSubscription
497 : };
498 : /**
499 : * Called internally to signal the completion of all work on this objecta and signal to a registered callback that it's
500 : * safe to release this object.
501 : *
502 : * @param options This specifies whether to drop or keep the subscription
503 : *
504 : */
505 : void Close(CloseOptions options = CloseOptions::kDropPersistedSubscription);
506 :
507 : CHIP_ERROR SendSubscribeResponse();
508 : CHIP_ERROR ProcessSubscribeRequest(System::PacketBufferHandle && aPayload);
509 : CHIP_ERROR ProcessReadRequest(System::PacketBufferHandle && aPayload);
510 : CHIP_ERROR ProcessAttributePaths(AttributePathIBs::Parser & aAttributePathListParser);
511 : CHIP_ERROR ProcessEventPaths(EventPathIBs::Parser & aEventPathsParser);
512 : CHIP_ERROR ProcessEventFilters(EventFilterIBs::Parser & aEventFiltersParser);
513 : CHIP_ERROR OnStatusResponse(Messaging::ExchangeContext * apExchangeContext, System::PacketBufferHandle && aPayload,
514 : bool & aSendStatusResponse);
515 : CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader,
516 : System::PacketBufferHandle && aPayload) override;
517 : void OnResponseTimeout(Messaging::ExchangeContext * apExchangeContext) override;
518 : void MoveToState(const HandlerState aTargetState);
519 :
520 : const char * GetStateStr() const;
521 :
522 : void PersistSubscription();
523 :
524 : /// @brief Modifies a state flag in the read handler. If the read handler went from a
525 : /// non-reportable state to a reportable state, schedules a reporting engine run.
526 : /// @param aFlag Flag to set
527 : /// @param aValue Flag new value
528 : void SetStateFlag(ReadHandlerFlags aFlag, bool aValue = true);
529 :
530 : /// @brief This function call SetStateFlag with the flag value set to false, thus possibly emitting a report
531 : /// generation.
532 : /// @param aFlag Flag to clear
533 : void ClearStateFlag(ReadHandlerFlags aFlag);
534 :
535 : SubscriptionId mSubscriptionId = 0;
536 :
537 : // The current generation of the reporting engine dirty set the last time we were notified that a path we're interested in was
538 : // marked dirty.
539 : //
540 : // This allows us to detemine whether any paths we care about might have
541 : // been marked dirty after we had already sent reports for them, which would
542 : // mean we should report those paths again, by comparing this generation to the
543 : // current generation when we started sending the last set reports that we completed.
544 : //
545 : // This allows us to reset the iterator to the beginning of the current
546 : // cluster instead of the beginning of the whole report in AttributePathIsDirty, without
547 : // permanently missing dirty any paths.
548 : uint64_t mDirtyGeneration = 0;
549 :
550 : // For subscriptions, we record the timestamp when we started to generate the last report.
551 : // The mCurrentReportsBeginGeneration records the timestamp for the current report, which won;t be used for checking if this
552 : // ReadHandler is dirty.
553 : // mPreviousReportsBeginGeneration will be set to mCurrentReportsBeginGeneration after we sent the last chunk of the current
554 : // report.
555 : uint64_t mPreviousReportsBeginGeneration = 0;
556 : uint64_t mCurrentReportsBeginGeneration = 0;
557 : /*
558 : * (mDirtyGeneration = b > a, this is a dirty read handler)
559 : * +- Start Report -> mCurrentReportsBeginGeneration = c
560 : * | +- AttributePathIsDirty (Attribute Y) -> mDirtyGeneration = d
561 : * | | +- Last Chunk -> mPreviousReportsBeginGeneration = mCurrentReportsBeginGeneration = c
562 : * | | | +- (mDirtyGeneration = d) > (mPreviousReportsBeginGeneration = c), this is a dirty read handler
563 : * | | | | Attribute X has a dirty generation less than c, Attribute Y has a dirty generation larger than c
564 : * | | | | So Y will be included in the report but X will not be inclued in this report.
565 : * -a--b--c------d-----e---f---> Generation
566 : * | |
567 : * | +- AttributePathIsDirty (Attribute X) (mDirtyGeneration = b)
568 : * +- mPreviousReportsBeginGeneration
569 : * For read handler, if mDirtyGeneration > mPreviousReportsBeginGeneration, then we regard it as a dirty read handler, and it
570 : * should generate report on timeout reached.
571 : */
572 :
573 : // When we don't have enough resources for a new subscription, the oldest subscription might be evicted by interaction model
574 : // engine, the "oldest" subscription is the subscription with the smallest generation.
575 : uint64_t mTransactionStartGeneration = 0;
576 :
577 : EventNumber mEventMin = 0;
578 :
579 : // The last schedule event number snapshoted in the beginning when preparing to fill new events to reports
580 : EventNumber mLastScheduledEventNumber = 0;
581 :
582 : /// Iterator position state for any ongoing path expansion for handling wildcard reads/subscriptions.
583 : AttributePathExpandIterator::Position mAttributePathExpandPosition;
584 :
585 : Messaging::ExchangeHolder mExchangeCtx;
586 : #if CHIP_CONFIG_UNSAFE_SUBSCRIPTION_EXCHANGE_MANAGER_USE
587 : // TODO: this should be replaced by a pointer to the InteractionModelEngine that created the ReadHandler
588 : // once InteractionModelEngine is no longer a singleton (see issue 23625)
589 : Messaging::ExchangeManager * mExchangeMgr = nullptr;
590 : #endif // CHIP_CONFIG_UNSAFE_SUBSCRIPTION_EXCHANGE_MANAGER_USE
591 :
592 : SingleLinkedListNode<AttributePathParams> * mpAttributePathList = nullptr;
593 : SingleLinkedListNode<EventPathParams> * mpEventPathList = nullptr;
594 : SingleLinkedListNode<DataVersionFilter> * mpDataVersionFilterList = nullptr;
595 :
596 : ManagementCallback & mManagementCallback;
597 :
598 : // TODO (#27675): Merge all observers into one and that one will dispatch the callbacks to the right place.
599 : Observer * mObserver = nullptr;
600 :
601 : uint32_t mLastWrittenEventsBytes = 0;
602 :
603 : // The detailed encoding state for a single attribute, used by list chunking feature.
604 : // The size of AttributeEncoderState is 2 bytes for now.
605 : AttributeEncodeState mAttributeEncoderState;
606 :
607 : uint16_t mMinIntervalFloorSeconds = 0;
608 : uint16_t mMaxInterval = 0;
609 : uint16_t mSubscriberRequestedMaxInterval = 0;
610 :
611 : // Current Handler state
612 : HandlerState mState = HandlerState::Idle;
613 : PriorityLevel mCurrentPriority = PriorityLevel::Invalid;
614 : BitFlags<ReadHandlerFlags> mFlags;
615 : InteractionType mInteractionType = InteractionType::Read;
616 :
617 : SessionHolder mSessionHandle;
618 : };
619 :
620 : } // namespace app
621 : } // namespace chip
|