Skip to content

Commit

Permalink
Decouple InitDataModelHandler from libCHIP
Browse files Browse the repository at this point in the history
  • Loading branch information
yufengwangca committed Dec 4, 2024
1 parent 38ad07d commit 2ed8dfb
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 54 deletions.
2 changes: 2 additions & 0 deletions src/app/InteractionModelEngine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1836,6 +1836,8 @@ DataModel::Provider * InteractionModelEngine::SetDataModelProvider(DataModel::Pr
mDataModelProvider = model;
if (mDataModelProvider != nullptr)
{
mDataModelProvider->Init();

DataModel::InteractionModelContext context;

context.eventsGenerator = &EventManagement::GetInstance();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,12 @@ using detail::EnumeratorCommandFinder;

namespace {

const chip::CommandId * AcceptedCommands(const EmberAfCluster & cluster)
const CommandId * AcceptedCommands(const EmberAfCluster & cluster)
{
return cluster.acceptedCommandList;
}

const chip::CommandId * GeneratedCommands(const EmberAfCluster & cluster)
const CommandId * GeneratedCommands(const EmberAfCluster & cluster)
{
return cluster.generatedCommandList;
}
Expand Down
23 changes: 15 additions & 8 deletions src/app/codegen-data-model-provider/CodegenDataModelProvider.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include <app/CommandHandlerInterface.h>
#include <app/ConcreteCommandPath.h>
#include <app/data-model-provider/ActionReturnStatus.h>
#include <app/util/DataModelHandler.h>
#include <app/util/af-types.h>

namespace chip {
Expand Down Expand Up @@ -93,7 +94,7 @@ class EnumeratorCommandFinder
/// Given that this relies on global data at link time, there generally can be
/// only one CodegenDataModelProvider per application (you can create more instances,
/// however they would share the exact same underlying data and storage).
class CodegenDataModelProvider : public chip::app::DataModel::Provider
class CodegenDataModelProvider : public DataModel::Provider
{
private:
/// Ember commands are stored as a `CommandId *` pointer that is either null (i.e. no commands)
Expand Down Expand Up @@ -125,6 +126,13 @@ class CodegenDataModelProvider : public chip::app::DataModel::Provider
};

public:
void Init() override
{
// Call the Ember-specific InitDataModelHandler
InitDataModelHandler();
ChipLogProgress(AppServer, "CodegenDataModelHandler initialized.");
}

/// clears out internal caching. Especially useful in unit tests,
/// where path caching does not really apply (the same path may result in different outcomes)
void Reset()
Expand All @@ -145,8 +153,8 @@ class CodegenDataModelProvider : public chip::app::DataModel::Provider
AttributeValueEncoder & encoder) override;
DataModel::ActionReturnStatus WriteAttribute(const DataModel::WriteAttributeRequest & request,
AttributeValueDecoder & decoder) override;
std::optional<DataModel::ActionReturnStatus> Invoke(const DataModel::InvokeRequest & request,
chip::TLV::TLVReader & input_arguments, CommandHandler * handler) override;
std::optional<DataModel::ActionReturnStatus> Invoke(const DataModel::InvokeRequest & request, TLV::TLVReader & input_arguments,
CommandHandler * handler) override;

/// attribute tree iteration
DataModel::EndpointEntry FirstEndpoint() override;
Expand Down Expand Up @@ -216,16 +224,15 @@ class CodegenDataModelProvider : public chip::app::DataModel::Provider
const EmberAfCluster * FindServerCluster(const ConcreteClusterPath & path);

/// Find the index of the given attribute id
std::optional<unsigned> TryFindAttributeIndex(const EmberAfCluster * cluster, chip::AttributeId id) const;
std::optional<unsigned> TryFindAttributeIndex(const EmberAfCluster * cluster, AttributeId id) const;

/// Find the index of the given cluster id
std::optional<unsigned> TryFindClusterIndex(const EmberAfEndpointType * endpoint, chip::ClusterId id,
ClusterSide clusterSide) const;
std::optional<unsigned> TryFindClusterIndex(const EmberAfEndpointType * endpoint, ClusterId id, ClusterSide clusterSide) const;

/// Find the index of the given endpoint id
std::optional<unsigned> TryFindEndpointIndex(chip::EndpointId id) const;
std::optional<unsigned> TryFindEndpointIndex(EndpointId id) const;

using CommandListGetter = const chip::CommandId *(const EmberAfCluster &);
using CommandListGetter = const CommandId *(const EmberAfCluster &);

CommandId FindCommand(const ConcreteCommandPath & path, detail::EnumeratorCommandFinder & handlerFinder,
detail::EnumeratorCommandFinder::Operation operation,
Expand Down
2 changes: 2 additions & 0 deletions src/app/data-model-provider/Provider.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ class Provider : public ProviderMetadataTree
public:
virtual ~Provider() = default;

virtual void Init() = 0;

// `context` pointers will be guaranteed valid until Shutdown is called()
virtual CHIP_ERROR Startup(InteractionModelContext context)
{
Expand Down
81 changes: 37 additions & 44 deletions src/app/server/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
#include <app/data-model-provider/Provider.h>
#include <app/server/Dnssd.h>
#include <app/server/EchoHandler.h>
#include <app/util/DataModelHandler.h>

#if CONFIG_NETWORK_LAYER_BLE
#include <ble/Ble.h>
Expand Down Expand Up @@ -98,8 +97,8 @@ Server Server::sServer;
static uint8_t sInfoEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_INFO_BUFFER_SIZE];
static uint8_t sDebugEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE];
static uint8_t sCritEventBuffer[CHIP_DEVICE_CONFIG_EVENT_LOGGING_CRIT_BUFFER_SIZE];
static ::chip::PersistedCounter<chip::EventNumber> sGlobalEventIdCounter;
static ::chip::app::CircularEventBuffer sLoggingBuffer[CHIP_NUM_EVENT_LOGGING_BUFFERS];
static PersistedCounter<EventNumber> sGlobalEventIdCounter;
static app::CircularEventBuffer sLoggingBuffer[CHIP_NUM_EVENT_LOGGING_BUFFERS];
#endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT

CHIP_ERROR Server::Init(const ServerInitParams & initParams)
Expand Down Expand Up @@ -136,8 +135,8 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)

VerifyOrExit(initParams.dataModelProvider != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);

// TODO(16969): Remove chip::Platform::MemoryInit() call from Server class, it belongs to outer code
chip::Platform::MemoryInit();
// TODO(16969): Remove Platform::MemoryInit() call from Server class, it belongs to outer code
Platform::MemoryInit();

// Initialize PersistentStorageDelegate-based storage
mDeviceStorage = initParams.persistentStorageDelegate;
Expand All @@ -157,11 +156,11 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
}

#if defined(CHIP_SUPPORT_ENABLE_STORAGE_API_AUDIT)
VerifyOrDie(chip::audit::ExecutePersistentStorageApiAudit(*mDeviceStorage));
VerifyOrDie(audit::ExecutePersistentStorageApiAudit(*mDeviceStorage));
#endif

#if defined(CHIP_SUPPORT_ENABLE_STORAGE_LOAD_TEST_AUDIT)
VerifyOrDie(chip::audit::ExecutePersistentStorageLoadTestAudit(*mDeviceStorage));
VerifyOrDie(audit::ExecutePersistentStorageLoadTestAudit(*mDeviceStorage));
#endif

// Set up attribute persistence before we try to bring up the data model
Expand All @@ -176,10 +175,7 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
// 1) Provider initialization (under SetDataModelProvider) happens after
// SetSafeAttributePersistenceProvider, since the provider can then use
// the safe persistence provider to implement and initialize its own attribute persistence logic.
// 2) For now, provider initialization happens before InitDataModelHandler(), which depends
// on atttribute persistence being already set up before it runs. Longer-term, the logic from
// InitDataModelHandler should just move into the codegen provider.
chip::app::InteractionModelEngine::GetInstance()->SetDataModelProvider(initParams.dataModelProvider);
app::InteractionModelEngine::GetInstance()->SetDataModelProvider(initParams.dataModelProvider);

{
FabricTable::InitParams fabricTableInitParams;
Expand Down Expand Up @@ -281,7 +277,7 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
app::DnssdServer::Instance().SetFabricTable(&mFabrics);
app::DnssdServer::Instance().SetCommissioningModeProvider(&mCommissioningWindowManager);

chip::Dnssd::Resolver::Instance().Init(DeviceLayer::UDPEndPointManager());
Dnssd::Resolver::Instance().Init(DeviceLayer::UDPEndPointManager());

#if CHIP_CONFIG_ENABLE_SERVER_IM_EVENT
// Initialize event logging subsystem
Expand All @@ -290,21 +286,18 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
SuccessOrExit(err);

{
::chip::app::LogStorageResources logStorageResources[] = {
{ &sDebugEventBuffer[0], sizeof(sDebugEventBuffer), ::chip::app::PriorityLevel::Debug },
{ &sInfoEventBuffer[0], sizeof(sInfoEventBuffer), ::chip::app::PriorityLevel::Info },
{ &sCritEventBuffer[0], sizeof(sCritEventBuffer), ::chip::app::PriorityLevel::Critical }
app::LogStorageResources logStorageResources[] = {
{ &sDebugEventBuffer[0], sizeof(sDebugEventBuffer), app::PriorityLevel::Debug },
{ &sInfoEventBuffer[0], sizeof(sInfoEventBuffer), app::PriorityLevel::Info },
{ &sCritEventBuffer[0], sizeof(sCritEventBuffer), app::PriorityLevel::Critical }
};

chip::app::EventManagement::GetInstance().Init(&mExchangeMgr, CHIP_NUM_EVENT_LOGGING_BUFFERS, &sLoggingBuffer[0],
&logStorageResources[0], &sGlobalEventIdCounter,
std::chrono::duration_cast<System::Clock::Milliseconds64>(mInitTimestamp));
app::EventManagement::GetInstance().Init(&mExchangeMgr, CHIP_NUM_EVENT_LOGGING_BUFFERS, &sLoggingBuffer[0],
&logStorageResources[0], &sGlobalEventIdCounter,
std::chrono::duration_cast<System::Clock::Milliseconds64>(mInitTimestamp));
}
#endif // CHIP_CONFIG_ENABLE_SERVER_IM_EVENT

// This initializes clusters, so should come after lower level initialization.
InitDataModelHandler();

#if defined(CHIP_APP_USE_ECHO)
err = InitEchoHandler(&mExchangeMgr);
SuccessOrExit(err);
Expand Down Expand Up @@ -333,7 +326,7 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
#if CONFIG_NETWORK_LAYER_BLE
// The device is already commissioned, proactively disable BLE advertisement.
ChipLogProgress(AppServer, "Fabric already commissioned. Disabling BLE advertisement");
chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false);
DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false);
#endif
}
else
Expand Down Expand Up @@ -374,8 +367,8 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
&mCertificateValidityPolicy, mGroupsProvider);
SuccessOrExit(err);

err = chip::app::InteractionModelEngine::GetInstance()->Init(&mExchangeMgr, &GetFabricTable(), mReportScheduler,
&mCASESessionManager, mSubscriptionResumptionStorage);
err = app::InteractionModelEngine::GetInstance()->Init(&mExchangeMgr, &GetFabricTable(), mReportScheduler, &mCASESessionManager,
mSubscriptionResumptionStorage);
SuccessOrExit(err);

#if CHIP_CONFIG_ENABLE_ICD_SERVER
Expand All @@ -396,7 +389,7 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
.SetFabricTable(&GetFabricTable())
.SetSymmetricKeyStore(mSessionKeystore)
.SetExchangeManager(&mExchangeMgr)
.SetSubscriptionsInfoProvider(chip::app::InteractionModelEngine::GetInstance())
.SetSubscriptionsInfoProvider(app::InteractionModelEngine::GetInstance())
.SetICDCheckInBackOffStrategy(initParams.icdCheckInBackOffStrategy);

#endif // CHIP_CONFIG_ENABLE_ICD_CIP
Expand Down Expand Up @@ -455,7 +448,7 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
}

#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT // support UDC port for commissioner declaration msgs
mUdcTransportMgr = chip::Platform::New<UdcTransportMgr>();
mUdcTransportMgr = Platform::New<UdcTransportMgr>();
ReturnErrorOnFailure(mUdcTransportMgr->Init(Transport::UdpListenParameters(DeviceLayer::UDPEndPointManager())
.SetAddressType(Inet::IPAddressType::kIPv6)
.SetListenPort(static_cast<uint16_t>(mCdcListenPort))
Expand All @@ -467,7 +460,7 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
#endif // INET_CONFIG_ENABLE_IPV4
));

gUDCClient = chip::Platform::New<Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient>();
gUDCClient = Platform::New<Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient>();
mUdcTransportMgr->SetSessionManager(gUDCClient);
#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY

Expand Down Expand Up @@ -623,23 +616,23 @@ void Server::Shutdown()
app::DnssdServer::Instance().SetICDManager(nullptr);
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
app::DnssdServer::Instance().SetCommissioningModeProvider(nullptr);
chip::Dnssd::ServiceAdvertiser::Instance().Shutdown();
Dnssd::ServiceAdvertiser::Instance().Shutdown();

#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
if (mUdcTransportMgr != nullptr)
{
chip::Platform::Delete(mUdcTransportMgr);
Platform::Delete(mUdcTransportMgr);
mUdcTransportMgr = nullptr;
}
if (gUDCClient != nullptr)
{
chip::Platform::Delete(gUDCClient);
Platform::Delete(gUDCClient);
gUDCClient = nullptr;
}
#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY

chip::Dnssd::Resolver::Instance().Shutdown();
chip::app::InteractionModelEngine::GetInstance()->Shutdown();
Dnssd::Resolver::Instance().Shutdown();
app::InteractionModelEngine::GetInstance()->Shutdown();
#if CHIP_CONFIG_ENABLE_ICD_SERVER
app::InteractionModelEngine::GetInstance()->SetICDManager(nullptr);
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
Expand All @@ -666,15 +659,15 @@ void Server::Shutdown()
mICDManager.Shutdown();
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
mAttributePersister.Shutdown();
// TODO(16969): Remove chip::Platform::MemoryInit() call from Server class, it belongs to outer code
chip::Platform::MemoryShutdown();
// TODO(16969): Remove Platform::MemoryInit() call from Server class, it belongs to outer code
Platform::MemoryShutdown();
}

#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
// NOTE: UDC client is located in Server.cpp because it really only makes sense
// to send UDC from a Matter device. The UDC message payload needs to include the device's
// randomly generated service name.
CHIP_ERROR Server::SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner,
CHIP_ERROR Server::SendUserDirectedCommissioningRequest(Transport::PeerAddress commissioner,
Protocols::UserDirectedCommissioning::IdentificationDeclaration & id)
{
ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest()");
Expand All @@ -685,7 +678,7 @@ CHIP_ERROR Server::SendUserDirectedCommissioningRequest(chip::Transport::PeerAdd
if (strlen(id.GetInstanceName()) == 0)
{
ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Instance Name not known");
char nameBuffer[chip::Dnssd::Commission::kInstanceNameMaxLength + 1];
char nameBuffer[Dnssd::Commission::kInstanceNameMaxLength + 1];
err = app::DnssdServer::Instance().GetCommissionableInstanceName(nameBuffer, sizeof(nameBuffer));
if (err != CHIP_NO_ERROR)
{
Expand Down Expand Up @@ -727,9 +720,9 @@ CHIP_ERROR Server::SendUserDirectedCommissioningRequest(chip::Transport::PeerAdd

if (strlen(id.GetDeviceName()) == 0)
{
char deviceName[chip::Dnssd::kKeyDeviceNameMaxLength + 1] = {};
if (!chip::DeviceLayer::ConfigurationMgr().IsCommissionableDeviceNameEnabled() ||
chip::DeviceLayer::ConfigurationMgr().GetCommissionableDeviceName(deviceName, sizeof(deviceName)) != CHIP_NO_ERROR)
char deviceName[Dnssd::kKeyDeviceNameMaxLength + 1] = {};
if (!DeviceLayer::ConfigurationMgr().IsCommissionableDeviceNameEnabled() ||
DeviceLayer::ConfigurationMgr().GetCommissionableDeviceName(deviceName, sizeof(deviceName)) != CHIP_NO_ERROR)
{
ChipLogDetail(AppServer, "Server::SendUserDirectedCommissioningRequest() Device Name not known");
}
Expand All @@ -743,13 +736,13 @@ CHIP_ERROR Server::SendUserDirectedCommissioningRequest(chip::Transport::PeerAdd
if (id.GetRotatingIdLength() == 0)
{
AdditionalDataPayloadGeneratorParams additionalDataPayloadParams;
uint8_t rotatingDeviceIdUniqueId[chip::DeviceLayer::ConfigurationManager::kRotatingDeviceIDUniqueIDLength];
uint8_t rotatingDeviceIdUniqueId[DeviceLayer::ConfigurationManager::kRotatingDeviceIDUniqueIDLength];
MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId);

ReturnErrorOnFailure(
chip::DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan));
DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan));
ReturnErrorOnFailure(
chip::DeviceLayer::ConfigurationMgr().GetLifetimeCounter(additionalDataPayloadParams.rotatingDeviceIdLifetimeCounter));
DeviceLayer::ConfigurationMgr().GetLifetimeCounter(additionalDataPayloadParams.rotatingDeviceIdLifetimeCounter));
additionalDataPayloadParams.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan;

uint8_t rotatingDeviceIdInternalBuffer[RotatingDeviceId::kMaxLength];
Expand Down Expand Up @@ -784,7 +777,7 @@ CHIP_ERROR Server::SendUserDirectedCommissioningRequest(chip::Transport::PeerAdd
#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
void Server::ResumeSubscriptions()
{
CHIP_ERROR err = chip::app::InteractionModelEngine::GetInstance()->ResumeSubscriptions();
CHIP_ERROR err = app::InteractionModelEngine::GetInstance()->ResumeSubscriptions();
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "Error when trying to resume subscriptions : %" CHIP_ERROR_FORMAT, err.Format());
Expand Down

0 comments on commit 2ed8dfb

Please sign in to comment.