3 * Copyright (c) 2021 Project CHIP Authors
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "LifetimePersistedCounter.h"
20 #include <platform/PersistedStorage.h>
21 #include <support/CodeUtils.h>
22 #include <support/logging/CHIPLogging.h>
29 LifetimePersistedCounter::LifetimePersistedCounter() : mId(chip::Platform::PersistedStorage::kEmptyKey) {}
31 LifetimePersistedCounter::~LifetimePersistedCounter() {}
34 LifetimePersistedCounter::Init(const chip::Platform::PersistedStorage::Key aId)
36 CHIP_ERROR err = CHIP_NO_ERROR;
41 // Read our previously-stored starting value.
42 SuccessOrExit(err = ReadStartValue(startValue));
44 // This will set the starting value, after which we're ready.
45 SuccessOrExit(err = MonotonicallyIncreasingCounter::Init(startValue));
52 LifetimePersistedCounter::Advance()
54 CHIP_ERROR err = CHIP_NO_ERROR;
56 VerifyOrExit(mId != chip::Platform::PersistedStorage::kEmptyKey, err = CHIP_ERROR_INCORRECT_STATE);
58 SuccessOrExit(err = MonotonicallyIncreasingCounter::Advance());
60 SuccessOrExit(err = chip::Platform::PersistedStorage::Write(mId, GetValue()));
66 LifetimePersistedCounter::ReadStartValue(uint32_t & aStartValue)
68 CHIP_ERROR err = CHIP_NO_ERROR;
72 err = chip::Platform::PersistedStorage::Read(mId, aStartValue);
73 if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND)
75 // No previously-stored value, no worries, the counter is initialized to zero.
76 // Suppress the error.