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

Decouple InitDataModelHandler from libCHIP #36725

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
2ed8dfb
Decouple InitDataModelHandler from libCHIP
yufengwangca Dec 4, 2024
96b12a6
Use StartUp to init
yufengwangca Dec 4, 2024
5139173
Seperate namespace cleanup out
yufengwangca Dec 5, 2024
77b9d57
Merge remote-tracking branch 'upstream/master' into pr/ember/server
yufengwangca Dec 5, 2024
7ee7ef4
Mock function for linking
yufengwangca Dec 5, 2024
94d7aac
Restyled by clang-format
restyled-commits Dec 5, 2024
4565faf
Add API comment
yufengwangca Dec 5, 2024
982676b
Fix mutiple defination conflicts
yufengwangca Dec 5, 2024
ed2bfef
Address review comments
yufengwangca Dec 5, 2024
bc9d9b3
Merge remote-tracking branch 'upstream/master' into pr/ember/server
yufengwangca Dec 5, 2024
5385f19
Restyled by whitespace
restyled-commits Dec 5, 2024
5a8af59
Seperate InitDataModel out
yufengwangca Dec 6, 2024
d27a5e1
Merge remote-tracking branch 'upstream/master' into pr/ember/server
yufengwangca Dec 11, 2024
bb22e12
Revert "Seperate InitDataModel out"
yufengwangca Dec 11, 2024
b735528
Do not directly manipulate the base class's Startup method
yufengwangca Dec 11, 2024
1616274
Address review comment
yufengwangca Dec 12, 2024
ca96081
Restyled by whitespace
restyled-commits Dec 12, 2024
e7a2ae8
Adjust the init order
yufengwangca Dec 12, 2024
0b32b5b
Restyled by whitespace
restyled-commits Dec 12, 2024
99ada31
Update src/app/server/Server.cpp
yufengwangca Dec 13, 2024
266a107
Update src/controller/CHIPDeviceControllerFactory.cpp
yufengwangca Dec 13, 2024
f382d72
Add TODO comment
yufengwangca Dec 13, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
28 changes: 20 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,8 @@
#include <app/CommandHandlerInterface.h>
#include <app/ConcreteCommandPath.h>
#include <app/data-model-provider/ActionReturnStatus.h>
#include <app/data-model-provider/Context.h>
#include <app/util/DataModelHandler.h>
#include <app/util/af-types.h>

namespace chip {
Expand Down Expand Up @@ -93,7 +95,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 @@ -135,6 +137,17 @@ class CodegenDataModelProvider : public chip::app::DataModel::Provider
}

/// Generic model implementations
CHIP_ERROR Startup(DataModel::InteractionModelContext context) override
yufengwangca marked this conversation as resolved.
Show resolved Hide resolved
{
// Call the base class's Startup method to ensure base initialization
ReturnErrorOnFailure(DataModel::Provider::Startup(context));

// Call the Ember-specific InitDataModelHandler
InitDataModelHandler();

return CHIP_NO_ERROR;
}

CHIP_ERROR Shutdown() override
{
Reset();
Expand All @@ -145,8 +158,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 +229,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;
yufengwangca marked this conversation as resolved.
Show resolved Hide resolved
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
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);
yufengwangca marked this conversation as resolved.
Show resolved Hide resolved

{
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();
yufengwangca marked this conversation as resolved.
Show resolved Hide resolved

#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
Loading