Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Telink] Fix TC-OPCREDS-3.6 and prevent writing to NVS during factory reset #26784

Merged
52 changes: 51 additions & 1 deletion examples/platform/telink/common/src/AppTaskCommon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@
#include "OTAUtil.h"
#endif

#ifdef CONFIG_CHIP_FACTORY_RESET_ERASE_NVS
#include <zephyr/fs/nvs.h>
#include <zephyr/settings/settings.h>
#endif

LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL);

namespace {
Expand Down Expand Up @@ -111,7 +116,48 @@ class AppFabricTableDelegate : public FabricTable::Delegate
{
if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0)
{
chip::Server::GetInstance().ScheduleFactoryReset();
ChipLogProgress(DeviceLayer, "Performing erasing of settings partition");

#ifdef CONFIG_CHIP_FACTORY_RESET_ERASE_NVS
void * storage = nullptr;
int status = settings_storage_get(&storage);

if (status == 0)
{
status = nvs_clear(static_cast<nvs_fs *>(storage));
}

if (!status)
{
status = nvs_mount(static_cast<nvs_fs *>(storage));
}

if (status)
{
ChipLogError(DeviceLayer, "Storage clearance failed: %d", status);
}
#else
const CHIP_ERROR err = PersistedStorage::KeyValueStoreMgrImpl().DoFactoryReset();

if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "Factory reset failed: %" CHIP_ERROR_FORMAT, err.Format());
}

ConnectivityMgr().ErasePersistentInfo();
#endif
}
}
};

class PlatformMgrDelegate : public DeviceLayer::PlatformManagerDelegate
{
void OnShutDown() override
{
if (ThreadStackManagerImpl().IsThreadEnabled())
{
ThreadStackManagerImpl().SetThreadEnabled(false);
ThreadStackManagerImpl().SetRadioBlocked(true);
}
}
};
Expand Down Expand Up @@ -229,6 +275,10 @@ CHIP_ERROR AppTaskCommon::InitCommonParts(void)
emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false);
#endif

// We need to disable OpenThread to prevent writing to the NVS storage when factory reset occurs
// For this the OnShutdown function is used
PlatformMgr().SetDelegate(new PlatformMgrDelegate);

// Add CHIP event handler and start CHIP thread.
// Note that all the initialization code should happen prior to this point to avoid data races
// between the main and the CHIP threads.
Expand Down