Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / include / platform / SoftwareUpdateManager.h
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *    Copyright (c) 2019 Google LLC.
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  *          Defines the public interface for the Device Layer SoftwareUpdateManager object.
22  */
23
24 #pragma once
25
26 #if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER
27
28 #include <core/CHIPTLV.h>
29 #include <platform/internal/CHIPDeviceLayerInternal.h>
30
31 namespace chip {
32 namespace DeviceLayer {
33
34 using namespace chip::TLV;
35
36 class SoftwareUpdateManagerImpl;
37
38 class SoftwareUpdateManager
39 {
40     using ImplClass = SoftwareUpdateManagerImpl;
41
42 public:
43     // ===== Members that define the public interface of the SoftwareUpdateManager
44
45     enum State
46     {
47         kState_Idle                = 1,
48         kState_ScheduledHoldoff    = 2,
49         kState_PrepareQuery        = 3,
50         kState_Query               = 4,
51         kState_PrepareImageStorage = 5,
52         kState_Download            = 6,
53         kState_Install             = 7,
54
55         kState_ApplicationManaged = 8,
56
57         kState_MaxState
58     };
59
60     /**
61      * API events generated by the \c SoftwareUpdateManager object.
62      */
63     enum EventType
64     {
65         /**
66          *  Prepare ImageQuery message
67          *
68          *  Generated when a software update check has been triggered. Provides an opportunity
69          *  for the application to supply product related information to the
70          *  SofwareUpdate:ImageQuery message.
71          */
72         kEvent_PrepareQuery,
73
74         /**
75          *  Prepare meta-data for ImageQuery request
76          *
77          *  Provides an opportunity for the application to append additional meta-data
78          *  to the SofwareUpdate:ImageQuery message if needed. Generated when implementation
79          *  is ready to get meta-data from the application.
80          */
81         kEvent_PrepareQuery_Metadata,
82
83         /**
84          *  Error preparing an ImageQuery request
85          *
86          *  Generated when the implementation encounters an error while preparing to send out
87          *  a software update query.
88          */
89         kEvent_QueryPrepareFailed,
90
91         /**
92          *  ImageQuery request has been sent
93          *
94          *  Informational event to signal that a SofwareUpdate:ImageQuery message has been sent.
95          */
96         kEvent_QuerySent,
97
98         /**
99          *  Software update is available
100          *
101          *  Generated when a SofwareUpdate:ImageQueryResponse is received in response to
102          *  a query containing information of the available update.
103          */
104         kEvent_SoftwareUpdateAvailable,
105
106         /**
107          *  Fetch persisted state information for a partially downloaded image
108          *
109          *  Provides an opportunity for the application to disclose information
110          *  of a partial image previously downloaded so that the download
111          *  may be continued from the point where it last stopped. URI of the available
112          *  software update is provided as an input parameter that the application can use
113          *  to compare if the image being downloaded is the same as the partial image.
114          *
115          *  The application is expected to return the length of the partial image in the
116          *  PartialImageLenInBytes output parameter.  The application can set the value
117          *  of PartialImageLenInBytes to 0 to indicate that no partial image exists or
118          *  that the URI of the partial image does not match.
119          *
120          *  The application may choose to ignore this event by passing it to the default
121          *  event handler. If this is done, the system will always download the entirety
122          *  of the available firmware image.
123          */
124         kEvent_FetchPartialImageInfo,
125
126         /**
127          *  Prepare for storage of a new image
128          *
129          *  Requests the application to perform any steps necessary to prepare local storage
130          *  for the download of a new firmware image.  The application can use this, for example,
131          *  to erase flash pages.
132          *
133          *  The PrepareImageStorage event is generated only in the case where a new firmware
134          *  image is being downloaded.  When a previously interrupted download is resumed,
135          *  PrepareImageStorage is not generated.
136          *
137          *  The application must signal completion of the prepare operation by calling the
138          *  \c PrepareImageStorageComplete() method.  It may do this within the event callback
139          *  itself, or at a later time.  If called from a task other than the chip task,
140          *  the caller must hold the chip stack lock.
141          *
142          *  The application can choose to ignore the PrepareImageStorage event by passing it
143          *  to the default event handler.  If this is done, the system automatically proceeds
144          *  to the image download state.
145          *
146          *  To support resuming an interrupted download, the application should persist the
147          *  image URI (supplied as an event parameter), and use this when handling subsequent
148          *  FetchPartialImageInfo events.
149          */
150         kEvent_PrepareImageStorage,
151
152         /**
153          *  Image download has begun
154          *
155          *  Informational event to signal the start of an image download transaction.
156          */
157         kEvent_StartImageDownload,
158
159         /**
160          *  Store a block of image data
161          *
162          *  Generated whenever a data block is received from the file download server.
163          *  Parameters included with this event provide the data and the length of the data.
164          *
165          *  To support resuming an interrupted download, the application should maintain a
166          *  persistent count of the total number of image bytes stored, and use this value
167          *  when handling subsequent FetchPartialImageInfo events.
168          */
169         kEvent_StoreImageBlock,
170
171         /**
172          *  Compute an image integrity check value
173          *
174          *  Requests the application to compute an integrity check value over the downloaded
175          *  image. Generated once downloading is complete.
176          */
177         kEvent_ComputeImageIntegrity,
178
179         /**
180          *  Reset state of partially downloaded image
181          *
182          *  Requests the application to forget the persisted state associated with a downloaded
183          *  image.  A ResetPartialImageInfo event is generated whenever a downloaded image fails
184          *  its integrity check.  After a ResetPartialImageInfo event has been processed,
185          *  subsequent FetchPartialImageInfo events should indicate that no partial image is
186          *  available.
187          *
188          *  Note that, when handling the ResetPartialImageInfo event, the application is NOT
189          *  required to clear image data itself, only the state information associated with the
190          *  image (i.e. the URI and partial image length).
191          *
192          *  If the application does not support image download resumption, it may ignore this
193          *  event by passing it to the default event handler.
194          */
195         kEvent_ResetPartialImageInfo,
196
197         /**
198          *  Image is ready to be installed
199          *
200          *  Informational event to signal that image is ready to be installed.
201          *  Generated once an image passes the integrity check.
202          */
203         kEvent_ReadyToInstall,
204
205         /**
206          *  Begin image installation
207          *
208          *  Requests the application to being the process of installing a downloaded firmware
209          *  image.
210          */
211         kEvent_StartInstallImage,
212
213         /**
214          *  Software update process finished
215          *
216          *  Generated when a software update check has finished with or without
217          *  errors. Parameters included with this event provide the reason for failure
218          *  if the attempt finished due to a failure.
219          */
220         kEvent_Finished,
221
222         /**
223          *  Check default event handling behavior.
224          *
225          *  Used to verify correct default event handling in the application.
226          *
227          *  Applications must NOT handle this event.
228          */
229         kEvent_DefaultCheck = 100,
230
231     };
232
233     /**
234      *  When a software update is available, the application can chose one of
235      *  the following actions as part of the SoftwareUpdateAvailable API event
236      *  callback. The default action will be set to kAction_Now.
237      */
238     enum ActionType
239     {
240         /**
241          *  Ignore the download completely. A kEvent_Finished API event callback will
242          *  be generated with error CHIP_DEVICE_ERROR_SOFTWARE_UPDATE_CANCELLED if
243          *  this option is selected and the retry logic will not be invoked.
244          */
245         kAction_Ignore,
246
247         /**
248          *  Start the download right away. A kEvent_FetchPartialImageInfo API event
249          *  callback will be generated right after.
250          */
251         kAction_DownloadNow,
252
253         /**
254          *  Pause download on start. Scheduled software update checks (if enabled) will be suspended.
255          *  State machine will remain in Download state. When ready, application can
256          *  call the resume download API to proceed with download or call Abort to cancel.
257          */
258         kAction_DownloadLater,
259
260         /**
261          *  Allows application to manage the rest of the phases of software update such as
262          *  download, image integrity validation and install. Software update manager
263          *  state machine will move to the ApplicationManaged state. Scheduled software update checks (if enabled)
264          *  will be suspended till application calls Abort or ImageInstallComplete API.
265          */
266         kAction_ApplicationManaged,
267     };
268
269     /**
270      *  Incoming parameters sent with events generated directly from this component
271      *
272      */
273     union InEventParam;
274
275     /**
276      *  Outgoing parameters sent with events generated directly from this component
277      *
278      */
279     union OutEventParam;
280
281     struct RetryParam
282     {
283         /**
284          *  Specifies the retry attempt number.
285          *  It is reset on a successful software update attempt.
286          */
287         uint32_t NumRetries;
288     };
289
290     typedef void (*EventCallback)(void * apAppState, EventType aEvent, const InEventParam & aInParam, OutEventParam & aOutParam);
291     typedef void (*RetryPolicyCallback)(void * aAppState, RetryParam & aRetryParam, uint32_t & aOutIntervalMsec);
292
293     CHIP_ERROR Abort();
294     CHIP_ERROR CheckNow();
295     CHIP_ERROR ImageInstallComplete(CHIP_ERROR aError);
296     CHIP_ERROR PrepareImageStorageComplete(CHIP_ERROR aError);
297     CHIP_ERROR SetEventCallback(void * aAppState, EventCallback aEventCallback);
298     CHIP_ERROR SetQueryIntervalWindow(uint32_t aMinWaitTimeMs, uint32_t aMaxWaitTimeMs);
299
300     bool IsInProgress();
301
302     void SetRetryPolicyCallback(RetryPolicyCallback aRetryPolicyCallback);
303
304     State GetState();
305
306     static void DefaultEventHandler(void * apAppState, EventType aEvent, const InEventParam & aInParam, OutEventParam & aOutParam);
307
308 private:
309     // ===== Members for internal use by the following friends.
310
311     // friend class SoftwareUpdateManagerImpl;
312     template <class>
313     friend class Internal::GenericPlatformManagerImpl;
314
315     CHIP_ERROR Init();
316
317 protected:
318     // Construction/destruction limited to subclasses.
319     SoftwareUpdateManager()  = default;
320     ~SoftwareUpdateManager() = default;
321
322     // No copy, move or assignment.
323     SoftwareUpdateManager(const SoftwareUpdateManager &)  = delete;
324     SoftwareUpdateManager(const SoftwareUpdateManager &&) = delete;
325     SoftwareUpdateManager & operator=(const SoftwareUpdateManager &) = delete;
326 };
327
328 /**
329  * Returns a reference to the public interface of the SoftwareUpdateManager singleton object.
330  *
331  * chip application should use this to access features of the SoftwareUpdateManager object
332  * that are common to all platforms.
333  */
334 extern SoftwareUpdateManager & SoftwareUpdateMgr();
335
336 /**
337  * Returns the platform-specific implementation of the SoftwareUpdateManager singleton object.
338  *
339  * chip applications can use this to gain access to features of the SoftwareUpdateManager
340  * that are specific to the selected platform.
341  */
342 extern SoftwareUpdateManagerImpl & SoftwareUpdateMgrImpl();
343
344 } // namespace DeviceLayer
345 } // namespace chip
346
347 /* Include a header file containing the implementation of the SoftwareUpdateManager
348  * object for the selected platform.
349  */
350 #ifdef EXTERNAL_SOFTWAREUPDATEMANAGERIMPL_HEADER
351 #include EXTERNAL_SOFTWAREUPDATEMANAGERIMPL_HEADER
352 #else
353 #define SOFTWAREUPDATEMANAGERIMPL_HEADER <platform/SoftwareUpdateManagerImpl.h>
354 #include SOFTWAREUPDATEMANAGERIMPL_HEADER
355 #endif
356
357 namespace chip {
358 namespace DeviceLayer {
359
360 using namespace chip::TLV;
361
362 union SoftwareUpdateManager::InEventParam
363 {
364     void Clear() { memset(this, 0, sizeof(*this)); }
365
366     SoftwareUpdateManager * Source;
367     struct
368     {
369         TLVWriter * MetaDataWriter;
370     } PrepareQuery_Metadata;
371
372     struct
373     {
374         CHIP_ERROR Error;
375     } QueryPrepareFailed;
376
377     struct
378     {
379         uint8_t IntegrityType;
380         const char * URI;
381         const char * Version;
382     } SoftwareUpdateAvailable;
383
384     struct
385     {
386         const char * URI;
387     } FetchPartialImageInfo;
388
389     struct
390     {
391         const char * URI;
392         uint8_t IntegrityType;
393     } PrepareImageStorage;
394
395     struct
396     {
397         uint8_t * DataBlock;
398         uint32_t DataBlockLen;
399     } StoreImageBlock;
400
401     struct
402     {
403         uint8_t IntegrityType;
404         uint8_t * IntegrityValueBuf;  // Pointer to the buffer for the app to copy Integrity Value into.
405         uint8_t IntegrityValueBufLen; // Length of the provided buffer.
406     } ComputeImageIntegrity;
407
408     struct
409     {
410         CHIP_ERROR Error;
411     } Finished;
412 };
413
414 union SoftwareUpdateManager::OutEventParam
415 {
416     void Clear() { memset(this, 0, sizeof(*this)); }
417
418     bool DefaultHandlerCalled;
419     struct
420     {
421         const char * PackageSpecification;
422         const char * DesiredLocale;
423         CHIP_ERROR Error;
424     } PrepareQuery;
425
426     struct
427     {
428         CHIP_ERROR Error;
429     } PrepareQuery_Metadata;
430
431     struct
432     {
433         ActionType Action;
434     } SoftwareUpdateAvailable;
435
436     struct
437     {
438         uint64_t PartialImageLen;
439     } FetchPartialImageInfo;
440
441     struct
442     {
443         CHIP_ERROR Error;
444     } StoreImageBlock;
445
446     struct
447     {
448         CHIP_ERROR Error;
449     } ComputeImageIntegrity;
450 };
451
452 inline CHIP_ERROR SoftwareUpdateManager::Init()
453 {
454     return static_cast<ImplClass *>(this)->_Init();
455 }
456
457 inline CHIP_ERROR SoftwareUpdateManager::CheckNow()
458 {
459     return static_cast<ImplClass *>(this)->_CheckNow();
460 }
461
462 inline CHIP_ERROR SoftwareUpdateManager::ImageInstallComplete(CHIP_ERROR aError)
463 {
464     return static_cast<ImplClass *>(this)->_ImageInstallComplete(aError);
465 }
466
467 inline CHIP_ERROR SoftwareUpdateManager::PrepareImageStorageComplete(CHIP_ERROR aError)
468 {
469     return static_cast<ImplClass *>(this)->_PrepareImageStorageComplete(aError);
470 }
471
472 inline SoftwareUpdateManager::State SoftwareUpdateManager::GetState()
473 {
474     return static_cast<ImplClass *>(this)->_GetState();
475 }
476
477 inline CHIP_ERROR SoftwareUpdateManager::Abort()
478 {
479     return static_cast<ImplClass *>(this)->_Abort();
480 }
481
482 inline bool SoftwareUpdateManager::IsInProgress()
483 {
484     return static_cast<ImplClass *>(this)->_IsInProgress();
485 }
486
487 inline CHIP_ERROR SoftwareUpdateManager::SetQueryIntervalWindow(uint32_t aMinRangeSecs, uint32_t aMaxRangeSecs)
488 {
489     return static_cast<ImplClass *>(this)->_SetQueryIntervalWindow(aMinRangeSecs, aMaxRangeSecs);
490 }
491
492 inline void SoftwareUpdateManager::SetRetryPolicyCallback(const RetryPolicyCallback aRetryPolicyCallback)
493 {
494     static_cast<ImplClass *>(this)->_SetRetryPolicyCallback(aRetryPolicyCallback);
495 }
496
497 inline CHIP_ERROR SoftwareUpdateManager::SetEventCallback(void * const aAppState, const EventCallback aEventCallback)
498 {
499     return static_cast<ImplClass *>(this)->_SetEventCallback(aAppState, aEventCallback);
500 }
501
502 inline void SoftwareUpdateManager::DefaultEventHandler(void * apAppState, EventType aEvent, const InEventParam & aInParam,
503                                                        OutEventParam & aOutParam)
504 {
505     ImplClass::_DefaultEventHandler(apAppState, aEvent, aInParam, aOutParam);
506 }
507
508 } // namespace DeviceLayer
509 } // namespace chip
510
511 #endif // CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER