forked from nrfconnect/sdk-connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOTAImageProcessorImpl.cpp
284 lines (237 loc) · 9.46 KB
/
OTAImageProcessorImpl.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OTAImageProcessorImpl.h"
#include "Reboot.h"
#include <app/clusters/ota-requestor/OTADownloader.h>
#include <app/clusters/ota-requestor/OTARequestorInterface.h>
#include <lib/support/CodeUtils.h>
#include <platform/CHIPDeviceLayer.h>
#include <system/SystemError.h>
#ifdef CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE
#include <credentials/CertificationDeclaration.h>
#include <platform/Zephyr/ZephyrConfig.h>
#include <zephyr/settings/settings.h>
#endif
#include "DFUSync.h"
#include <dfu/dfu_target.h>
#ifdef CONFIG_DFU_TARGET_SUIT
#include <dfu/dfu_target_suit.h>
#else
#include <dfu/dfu_target_mcuboot.h>
#include <zephyr/dfu/mcuboot.h>
#endif
#include <dfu/dfu_multi_image.h>
#include <zephyr/logging/log.h>
#include <zephyr/pm/device.h>
namespace chip {
namespace {
#ifdef CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE
// Cd globals are needed to be accessed from dfu image writer lambdas
uint8_t sCdBuf[chip::Credentials::kMaxCMSSignedCDMessage] = { 0 };
size_t sCdSavedBytes = 0;
#endif
void PostOTAStateChangeEvent(DeviceLayer::OtaState newState)
{
DeviceLayer::ChipDeviceEvent otaChange;
otaChange.Type = DeviceLayer::DeviceEventType::kOtaStateChanged;
otaChange.OtaStateChanged.newState = newState;
CHIP_ERROR error = DeviceLayer::PlatformMgr().PostEvent(&otaChange);
if (error != CHIP_NO_ERROR)
{
ChipLogError(SoftwareUpdate, "Error while posting OtaChange event %" CHIP_ERROR_FORMAT, error.Format());
}
}
} // namespace
namespace DeviceLayer {
CHIP_ERROR OTAImageProcessorImpl::PrepareDownload()
{
VerifyOrReturnError(mDownloader != nullptr, CHIP_ERROR_INCORRECT_STATE);
if (DFUSync::GetInstance().Take(mDfuSyncMutexId) != CHIP_NO_ERROR)
{
ChipLogError(SoftwareUpdate, "Cannot start Matter OTA, another DFU in progress.");
return CHIP_ERROR_BUSY;
}
TriggerFlashAction(ExternalFlashManager::Action::WAKE_UP);
return DeviceLayer::SystemLayer().ScheduleLambda([this] {
CHIP_ERROR err = PrepareDownloadImpl();
if (err != CHIP_NO_ERROR)
{
DFUSync::GetInstance().Free(mDfuSyncMutexId);
}
mDownloader->OnPreparedForDownload(err);
});
}
CHIP_ERROR OTAImageProcessorImpl::PrepareDownloadImpl()
{
mHeaderParser.Init();
mParams = {};
#ifdef CONFIG_DFU_TARGET_SUIT
ReturnErrorOnFailure(System::MapErrorZephyr(dfu_target_suit_set_buf(mBuffer, sizeof(mBuffer))));
#else
ReturnErrorOnFailure(System::MapErrorZephyr(dfu_target_mcuboot_set_buf(mBuffer, sizeof(mBuffer))));
#endif // CONFIG_DFU_TARGET_SUIT
ReturnErrorOnFailure(System::MapErrorZephyr(dfu_multi_image_init(mBuffer, sizeof(mBuffer))));
for (int image_id = 0; image_id < CONFIG_UPDATEABLE_IMAGE_NUMBER; ++image_id)
{
dfu_image_writer writer;
#ifdef CONFIG_DFU_TARGET_SUIT
// The first image is the SUIT manifest and must be placed in id=0, while all other images must be placed in id + 1,
// because id=1 is dedicated for internal DFU purposes when the SUIT manifest contains the firmware.
// In our case, we use cache processing, so we need to put firmware images starting from id=2.
writer.image_id = image_id == 0 ? image_id : image_id + 1;
writer.open = [](int id, size_t size) { return dfu_target_init(DFU_TARGET_IMAGE_TYPE_SUIT, id, size, nullptr); };
#else
writer.image_id = image_id;
writer.open = [](int id, size_t size) { return dfu_target_init(DFU_TARGET_IMAGE_TYPE_MCUBOOT, id, size, nullptr); };
#endif
writer.write = [](const uint8_t * chunk, size_t chunk_size) { return dfu_target_write(chunk, chunk_size); };
writer.close = [](bool success) { return success ? dfu_target_done(success) : dfu_target_reset(); };
ReturnErrorOnFailure(System::MapErrorZephyr(dfu_multi_image_register_writer(&writer)));
};
#ifdef CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE
dfu_image_writer cdWriter;
cdWriter.image_id = CONFIG_CHIP_CERTIFiCATION_DECLARATION_OTA_IMAGE_ID;
cdWriter.open = [](int id, size_t size) { return size <= sizeof(sCdBuf) ? 0 : -EFBIG; };
cdWriter.write = [](const uint8_t * chunk, size_t chunk_size) {
memcpy(&sCdBuf[sCdSavedBytes], chunk, chunk_size);
sCdSavedBytes += chunk_size;
return 0;
};
cdWriter.close = [](bool success) {
return settings_save_one(Internal::ZephyrConfig::kConfigKey_CertificationDeclaration, sCdBuf, sCdSavedBytes);
};
ReturnErrorOnFailure(System::MapErrorZephyr(dfu_multi_image_register_writer(&cdWriter)));
#endif
PostOTAStateChangeEvent(DeviceLayer::kOtaDownloadInProgress);
return CHIP_NO_ERROR;
}
CHIP_ERROR OTAImageProcessorImpl::Finalize()
{
PostOTAStateChangeEvent(DeviceLayer::kOtaDownloadComplete);
DFUSync::GetInstance().Free(mDfuSyncMutexId);
return System::MapErrorZephyr(dfu_multi_image_done(true));
}
CHIP_ERROR OTAImageProcessorImpl::Abort()
{
CHIP_ERROR error;
error = System::MapErrorZephyr(dfu_multi_image_done(false));
DFUSync::GetInstance().Free(mDfuSyncMutexId);
TriggerFlashAction(ExternalFlashManager::Action::SLEEP);
PostOTAStateChangeEvent(DeviceLayer::kOtaDownloadAborted);
return error;
}
CHIP_ERROR OTAImageProcessorImpl::Apply()
{
PostOTAStateChangeEvent(DeviceLayer::kOtaApplyInProgress);
// Schedule update of all images
int err = dfu_target_schedule_update(-1);
TriggerFlashAction(ExternalFlashManager::Action::SLEEP);
#ifdef CONFIG_CHIP_OTA_REQUESTOR_REBOOT_ON_APPLY
if (!err)
{
return SystemLayer().StartTimer(
System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_OTA_REQUESTOR_REBOOT_DELAY_MS),
[](System::Layer *, void * /* context */) {
PlatformMgr().HandleServerShuttingDown();
k_msleep(CHIP_DEVICE_CONFIG_SERVER_SHUTDOWN_ACTIONS_SLEEP_MS);
#ifdef CONFIG_DFU_TARGET_SUIT
dfu_target_suit_reboot();
#else
Reboot(SoftwareRebootReason::kSoftwareUpdate);
#endif
},
nullptr /* context */);
}
else
{
PostOTAStateChangeEvent(DeviceLayer::kOtaApplyFailed);
return System::MapErrorZephyr(err);
}
#else
return System::MapErrorZephyr(err);
#endif
}
CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & aBlock)
{
VerifyOrReturnError(mDownloader != nullptr, CHIP_ERROR_INCORRECT_STATE);
CHIP_ERROR error = ProcessHeader(aBlock);
if (error == CHIP_NO_ERROR)
{
// DFU target library buffers data internally, so do not clone the block data.
if (mParams.downloadedBytes > std::numeric_limits<size_t>::max())
{
error = CHIP_ERROR_BUFFER_TOO_SMALL;
}
else
{
int err = dfu_multi_image_write(static_cast<size_t>(mParams.downloadedBytes), aBlock.data(), aBlock.size());
mParams.downloadedBytes += aBlock.size();
error = System::MapErrorZephyr(err);
}
}
// Report the result back to the downloader asynchronously.
return DeviceLayer::SystemLayer().ScheduleLambda([this, error, aBlock] {
if (error == CHIP_NO_ERROR)
{
ChipLogDetail(SoftwareUpdate, "Downloaded %u/%u bytes", static_cast<unsigned>(mParams.downloadedBytes),
static_cast<unsigned>(mParams.totalFileBytes));
mDownloader->FetchNextData();
}
else
{
mDownloader->EndDownload(error);
PostOTAStateChangeEvent(DeviceLayer::kOtaDownloadFailed);
}
});
}
bool OTAImageProcessorImpl::IsFirstImageRun()
{
OTARequestorInterface * requestor = GetRequestorInstance();
ReturnErrorCodeIf(requestor == nullptr, false);
uint32_t currentVersion;
ReturnErrorCodeIf(ConfigurationMgr().GetSoftwareVersion(currentVersion) != CHIP_NO_ERROR, false);
return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying &&
requestor->GetTargetVersion() == currentVersion;
}
CHIP_ERROR OTAImageProcessorImpl::ConfirmCurrentImage()
{
PostOTAStateChangeEvent(DeviceLayer::kOtaApplyComplete);
return mImageConfirmed ? CHIP_NO_ERROR : CHIP_ERROR_INCORRECT_STATE;
}
CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & aBlock)
{
if (mHeaderParser.IsInitialized())
{
OTAImageHeader header;
CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(aBlock, header);
// Needs more data to decode the header
ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR);
ReturnErrorOnFailure(error);
mParams.totalFileBytes = header.mPayloadSize;
mHeaderParser.Clear();
}
return CHIP_NO_ERROR;
}
void OTAImageProcessorImpl::TriggerFlashAction(ExternalFlashManager::Action action)
{
if (mFlashHandler)
{
mFlashHandler->DoAction(action);
}
}
} // namespace DeviceLayer
} // namespace chip