From 19a70ba6dbf0ad235867fbb67a05483c42f9e18e Mon Sep 17 00:00:00 2001 From: Jiacheng Guo Date: Tue, 24 Aug 2021 19:09:18 +0800 Subject: [PATCH 1/8] Refactor the server to organize as a class --- examples/all-clusters-app/esp32/main/main.cpp | 7 +- examples/bridge-app/esp32/main/main.cpp | 2 +- examples/bridge-app/linux/main.cpp | 2 +- examples/lighting-app/efr32/src/AppTask.cpp | 2 +- examples/lighting-app/k32w/main/AppTask.cpp | 4 +- examples/lighting-app/mbed/main/AppTask.cpp | 2 +- .../lighting-app/nrfconnect/main/AppTask.cpp | 6 +- examples/lighting-app/qpg/src/AppTask.cpp | 4 +- examples/lighting-app/telink/src/AppTask.cpp | 4 +- .../lock-app/cc13x2x7_26x2x7/main/AppTask.cpp | 4 +- examples/lock-app/efr32/src/AppTask.cpp | 2 +- examples/lock-app/esp32/main/main.cpp | 2 +- examples/lock-app/k32w/main/AppTask.cpp | 4 +- examples/lock-app/mbed/main/AppTask.cpp | 2 +- examples/lock-app/nrfconnect/main/AppTask.cpp | 6 +- examples/lock-app/p6/src/AppTask.cpp | 2 +- examples/lock-app/qpg/src/AppTask.cpp | 4 +- examples/ota-provider-app/linux/main.cpp | 2 +- examples/platform/linux/AppMain.cpp | 10 +- .../linux/CommissioneeShellCommands.cpp | 2 +- .../pump-app/cc13x2x7_26x2x7/main/AppTask.cpp | 4 +- examples/pump-app/nrfconnect/main/AppTask.cpp | 6 +- .../cc13x2x7_26x2x7/main/AppTask.cpp | 4 +- .../nrfconnect/main/AppTask.cpp | 6 +- .../esp32/main/main.cpp | 2 +- examples/tv-casting-app/linux/main.cpp | 4 +- examples/window-app/common/src/WindowApp.cpp | 2 +- .../administrator-commissioning-server.cpp | 12 +- .../operational-credentials-server.cpp | 14 +- src/app/server/Mdns.cpp | 4 +- src/app/server/RendezvousServer.h | 4 +- src/app/server/Server.cpp | 551 ++++++++---------- src/app/server/Server.h | 144 +++-- src/app/server/SessionManager.h | 24 - src/controller/CHIPDeviceController.h | 4 +- .../secure_channel/RendezvousParameters.h | 8 +- 36 files changed, 407 insertions(+), 459 deletions(-) delete mode 100644 src/app/server/SessionManager.h diff --git a/examples/all-clusters-app/esp32/main/main.cpp b/examples/all-clusters-app/esp32/main/main.cpp index 72f5f8545bfb9d..81dab2c318fb70 100644 --- a/examples/all-clusters-app/esp32/main/main.cpp +++ b/examples/all-clusters-app/esp32/main/main.cpp @@ -346,7 +346,7 @@ class SetupListModel : public ListScreen::Model if (i == 0) { ConnectivityMgr().ClearWiFiStationProvision(); - OpenBasicCommissioningWindow(ResetFabrics::kYes); + chip::Server::GetServer().OpenBasicCommissioningWindow(ResetFabrics::kYes); } else if (i == 1) { @@ -355,7 +355,8 @@ class SetupListModel : public ListScreen::Model else if (i == 2) { app::Mdns::AdvertiseCommissionableNode(app::Mdns::CommissioningMode::kEnabledBasic); - OpenBasicCommissioningWindow(ResetFabrics::kYes, kNoCommissioningTimeout, PairingWindowAdvertisement::kMdns); + chip::Server::GetServer().OpenBasicCommissioningWindow(ResetFabrics::kYes, kNoCommissioningTimeout, + PairingWindowAdvertisement::kMdns); } } @@ -627,7 +628,7 @@ extern "C" void app_main() // Init ZCL Data Model and CHIP App Server AppCallbacks callbacks; - InitServer(&callbacks); + chip::Server::GetServer().Init(&callbacks); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/bridge-app/esp32/main/main.cpp b/examples/bridge-app/esp32/main/main.cpp index de1fb5ef3a860a..cbb0297c7140c5 100644 --- a/examples/bridge-app/esp32/main/main.cpp +++ b/examples/bridge-app/esp32/main/main.cpp @@ -390,7 +390,7 @@ extern "C" void app_main() return; } - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/bridge-app/linux/main.cpp b/examples/bridge-app/linux/main.cpp index 17638f8ff51e14..00e9713f45508b 100644 --- a/examples/bridge-app/linux/main.cpp +++ b/examples/bridge-app/linux/main.cpp @@ -513,7 +513,7 @@ int main(int argc, char * argv[]) chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true); // Init ZCL Data Model and CHIP App Server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lighting-app/efr32/src/AppTask.cpp b/examples/lighting-app/efr32/src/AppTask.cpp index 4aadec1a576e09..1caeff477c5f07 100644 --- a/examples/lighting-app/efr32/src/AppTask.cpp +++ b/examples/lighting-app/efr32/src/AppTask.cpp @@ -108,7 +108,7 @@ CHIP_ERROR AppTask::Init() CHIP_ERROR err = CHIP_NO_ERROR; // Init ZCL Data Model - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lighting-app/k32w/main/AppTask.cpp b/examples/lighting-app/k32w/main/AppTask.cpp index f5d6657e37d244..338057f8c2d742 100644 --- a/examples/lighting-app/k32w/main/AppTask.cpp +++ b/examples/lighting-app/k32w/main/AppTask.cpp @@ -88,7 +88,7 @@ CHIP_ERROR AppTask::Init() CHIP_ERROR err = CHIP_NO_ERROR; // Init ZCL Data Model and start server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -489,7 +489,7 @@ void AppTask::BleHandler(AppEvent * aEvent) { ConnectivityMgr().SetBLEAdvertisingEnabled(true); - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) { K32W_LOG("Started BLE Advertising!"); } diff --git a/examples/lighting-app/mbed/main/AppTask.cpp b/examples/lighting-app/mbed/main/AppTask.cpp index 9c755869af8fa8..99aedd0f64afcf 100644 --- a/examples/lighting-app/mbed/main/AppTask.cpp +++ b/examples/lighting-app/mbed/main/AppTask.cpp @@ -116,7 +116,7 @@ int AppTask::Init() chip::DeviceLayer::ConnectivityMgrImpl().StartWiFiManagement(); // Init ZCL Data Model and start server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lighting-app/nrfconnect/main/AppTask.cpp b/examples/lighting-app/nrfconnect/main/AppTask.cpp index ca4823182f89be..b7b46f5343bf7c 100644 --- a/examples/lighting-app/nrfconnect/main/AppTask.cpp +++ b/examples/lighting-app/nrfconnect/main/AppTask.cpp @@ -106,7 +106,7 @@ int AppTask::Init() LightingMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -352,7 +352,7 @@ void AppTask::StartThreadHandler(AppEvent * aEvent) if (aEvent->ButtonEvent.PinNo != THREAD_START_BUTTON) return; - if (AddTestCommissioning() != CHIP_NO_ERROR) + if (chip::Server::GetServer().AddTestCommissioning() != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); } @@ -386,7 +386,7 @@ void AppTask::StartBLEAdvertisementHandler(AppEvent * aEvent) return; } - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) { LOG_ERR("OpenBasicCommissioningWindow() failed"); } diff --git a/examples/lighting-app/qpg/src/AppTask.cpp b/examples/lighting-app/qpg/src/AppTask.cpp index dac51dd420d18e..2cde8d8033db83 100644 --- a/examples/lighting-app/qpg/src/AppTask.cpp +++ b/examples/lighting-app/qpg/src/AppTask.cpp @@ -100,7 +100,7 @@ CHIP_ERROR AppTask::Init() qvCHIP_SetBtnCallback(ButtonEventHandler); // Init ZCL Data Model - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -111,7 +111,7 @@ CHIP_ERROR AppTask::Init() PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); // Enable BLE advertisements - OpenBasicCommissioningWindow(chip::ResetFabrics::kNo); + chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo); ChipLogProgress(NotSpecified, "BLE advertising started. Waiting for Pairing."); return err; diff --git a/examples/lighting-app/telink/src/AppTask.cpp b/examples/lighting-app/telink/src/AppTask.cpp index dc344e69d94c3a..5a22deb9b0763f 100644 --- a/examples/lighting-app/telink/src/AppTask.cpp +++ b/examples/lighting-app/telink/src/AppTask.cpp @@ -98,7 +98,7 @@ CHIP_ERROR AppTask::Init() LightingMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -106,7 +106,7 @@ CHIP_ERROR AppTask::Init() ConfigurationMgr().LogDeviceConfig(); PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); - ret = AddTestCommissioning(); + ret = chip::Server::GetServer().AddTestCommissioning(); if (ret != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); diff --git a/examples/lock-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/lock-app/cc13x2x7_26x2x7/main/AppTask.cpp index 16510c56dad81d..3e6813b090bdb3 100644 --- a/examples/lock-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/lock-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -144,7 +144,7 @@ int AppTask::Init() // Init ZCL Data Model and start server PLAT_LOG("Initialize Server"); - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -333,7 +333,7 @@ void AppTask::DispatchEvent(AppEvent * aEvent) // Enable BLE advertisements if (!ConnectivityMgr().IsBLEAdvertisingEnabled()) { - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) { PLAT_LOG("Enabled BLE Advertisement"); } diff --git a/examples/lock-app/efr32/src/AppTask.cpp b/examples/lock-app/efr32/src/AppTask.cpp index ce1712bdbbcb11..0a0ae4325c56f1 100644 --- a/examples/lock-app/efr32/src/AppTask.cpp +++ b/examples/lock-app/efr32/src/AppTask.cpp @@ -100,7 +100,7 @@ CHIP_ERROR AppTask::StartAppTask() CHIP_ERROR AppTask::Init() { // Init ZCL Data Model - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lock-app/esp32/main/main.cpp b/examples/lock-app/esp32/main/main.cpp index 3a31d195180b89..b63f6542a3f076 100644 --- a/examples/lock-app/esp32/main/main.cpp +++ b/examples/lock-app/esp32/main/main.cpp @@ -85,7 +85,7 @@ extern "C" void app_main() return; } - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lock-app/k32w/main/AppTask.cpp b/examples/lock-app/k32w/main/AppTask.cpp index f50c5550ae63da..e4fd52db3b2a01 100644 --- a/examples/lock-app/k32w/main/AppTask.cpp +++ b/examples/lock-app/k32w/main/AppTask.cpp @@ -87,7 +87,7 @@ CHIP_ERROR AppTask::Init() CHIP_ERROR err = CHIP_NO_ERROR; // Init ZCL Data Model and start server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -528,7 +528,7 @@ void AppTask::BleHandler(void * aGenericEvent) { ConnectivityMgr().SetBLEAdvertisingEnabled(true); - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) { K32W_LOG("Started BLE Advertising!"); } diff --git a/examples/lock-app/mbed/main/AppTask.cpp b/examples/lock-app/mbed/main/AppTask.cpp index fe15f5b43f9771..e47874bd41d71b 100644 --- a/examples/lock-app/mbed/main/AppTask.cpp +++ b/examples/lock-app/mbed/main/AppTask.cpp @@ -120,7 +120,7 @@ int AppTask::Init() chip::DeviceLayer::ConnectivityMgrImpl().StartWiFiManagement(); // Init ZCL Data Model and start server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lock-app/nrfconnect/main/AppTask.cpp b/examples/lock-app/nrfconnect/main/AppTask.cpp index 43364949d48fb7..7fd32d3a8c8934 100644 --- a/examples/lock-app/nrfconnect/main/AppTask.cpp +++ b/examples/lock-app/nrfconnect/main/AppTask.cpp @@ -97,7 +97,7 @@ int AppTask::Init() BoltLockMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -352,7 +352,7 @@ void AppTask::StartThreadHandler(AppEvent * aEvent) if (aEvent->ButtonEvent.PinNo != THREAD_START_BUTTON) return; - if (AddTestCommissioning() != CHIP_NO_ERROR) + if (chip::Server::GetServer().AddTestCommissioning() != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); } @@ -386,7 +386,7 @@ void AppTask::StartBLEAdvertisementHandler(AppEvent * aEvent) return; } - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) { LOG_ERR("OpenBasicCommissioningWindow() failed"); } diff --git a/examples/lock-app/p6/src/AppTask.cpp b/examples/lock-app/p6/src/AppTask.cpp index a67598472228a3..0f8ceb9b131cba 100644 --- a/examples/lock-app/p6/src/AppTask.cpp +++ b/examples/lock-app/p6/src/AppTask.cpp @@ -102,7 +102,7 @@ CHIP_ERROR AppTask::Init() }, 0); // Init ZCL Data Model - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lock-app/qpg/src/AppTask.cpp b/examples/lock-app/qpg/src/AppTask.cpp index ec5129c3c07958..38796fbaf7bb9b 100644 --- a/examples/lock-app/qpg/src/AppTask.cpp +++ b/examples/lock-app/qpg/src/AppTask.cpp @@ -103,7 +103,7 @@ CHIP_ERROR AppTask::Init() qvCHIP_LedSet(LOCK_STATE_LED, !BoltLockMgr().IsUnlocked()); // Init ZCL Data Model - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -350,7 +350,7 @@ void AppTask::FunctionHandler(AppEvent * aEvent) if (!ConnectivityMgr().IsThreadProvisioned()) { // Enable BLE advertisements and pairing window - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) { ChipLogProgress(NotSpecified, "BLE advertising started. Waiting for Pairing."); } diff --git a/examples/ota-provider-app/linux/main.cpp b/examples/ota-provider-app/linux/main.cpp index 7eafc4fbd33ce4..7bd4907ea42b35 100644 --- a/examples/ota-provider-app/linux/main.cpp +++ b/examples/ota-provider-app/linux/main.cpp @@ -121,7 +121,7 @@ int main(int argc, char * argv[]) } chip::DeviceLayer::ConfigurationMgr().LogDeviceConfig(); - InitServer(); + chip::Server::GetServer().Init(); exchangeMgr = chip::ExchangeManager(); err = exchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(chip::Protocols::BDX::Id, &bdxServer); diff --git a/examples/platform/linux/AppMain.cpp b/examples/platform/linux/AppMain.cpp index 96252b465fcf7a..5fc27d44267833 100644 --- a/examples/platform/linux/AppMain.cpp +++ b/examples/platform/linux/AppMain.cpp @@ -265,17 +265,17 @@ void ChipLinuxAppMainLoop() std::thread shellThread([]() { Engine::Root().RunMainLoop(); }); chip::Shell::RegisterCommissioneeCommands(); #endif + uint16_t securePort = CHIP_PORT; + uint16_t unsecurePort = CHIP_UDC_PORT; #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE // use a different service port to make testing possible with other sample devices running on same host - ServerConfigParams params; - params.securedServicePort = LinuxDeviceOptions::GetInstance().securedDevicePort; - params.unsecuredServicePort = LinuxDeviceOptions::GetInstance().unsecuredCommissionerPort; - SetServerConfig(params); + securePort = LinuxDeviceOptions::GetInstance().securedDevicePort; + unsecurePort = LinuxDeviceOptions::GetInstance().unsecuredCommissionerPort; #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE // Init ZCL Data Model and CHIP App Server - InitServer(); + chip::Server::GetServer().Init(nullptr, securePort, unsecurePort); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/platform/linux/CommissioneeShellCommands.cpp b/examples/platform/linux/CommissioneeShellCommands.cpp index bb356e7bbd806a..7c057ce94b18ae 100644 --- a/examples/platform/linux/CommissioneeShellCommands.cpp +++ b/examples/platform/linux/CommissioneeShellCommands.cpp @@ -46,7 +46,7 @@ static CHIP_ERROR SendUDC(bool printHeader, chip::Transport::PeerAddress commiss streamer_printf(sout, "SendUDC: "); } - SendUserDirectedCommissioningRequest(commissioner); + Server::GetServer().SendUserDirectedCommissioningRequest(commissioner); streamer_printf(sout, "done\r\n"); diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp index ef76464d5f0132..82fee5ff063eb6 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -146,7 +146,7 @@ int AppTask::Init() // Init ZCL Data Model and start server PLAT_LOG("Initialize Server"); - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -335,7 +335,7 @@ void AppTask::DispatchEvent(AppEvent * aEvent) // Enable BLE advertisements if (!ConnectivityMgr().IsBLEAdvertisingEnabled()) { - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) { PLAT_LOG("Enabled BLE Advertisement"); } diff --git a/examples/pump-app/nrfconnect/main/AppTask.cpp b/examples/pump-app/nrfconnect/main/AppTask.cpp index f8ea7e8ed10f0f..2062acededb451 100644 --- a/examples/pump-app/nrfconnect/main/AppTask.cpp +++ b/examples/pump-app/nrfconnect/main/AppTask.cpp @@ -97,7 +97,7 @@ int AppTask::Init() PumpMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -352,7 +352,7 @@ void AppTask::StartThreadHandler(AppEvent * aEvent) if (aEvent->ButtonEvent.PinNo != THREAD_START_BUTTON) return; - if (AddTestCommissioning() != CHIP_NO_ERROR) + if (chip::Server::GetServer().AddTestCommissioning() != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); } @@ -386,7 +386,7 @@ void AppTask::StartBLEAdvertisementHandler(AppEvent * aEvent) return; } - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) { LOG_ERR("OpenBasicCommissioningWindow() failed"); } diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp index c5141dd07c60fd..78d34e4230fd91 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -146,7 +146,7 @@ int AppTask::Init() // Init ZCL Data Model and start server PLAT_LOG("Initialize Server"); - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -335,7 +335,7 @@ void AppTask::DispatchEvent(AppEvent * aEvent) // Enable BLE advertisements if (!ConnectivityMgr().IsBLEAdvertisingEnabled()) { - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) { PLAT_LOG("Enabled BLE Advertisement"); } diff --git a/examples/pump-controller-app/nrfconnect/main/AppTask.cpp b/examples/pump-controller-app/nrfconnect/main/AppTask.cpp index f8ea7e8ed10f0f..2062acededb451 100644 --- a/examples/pump-controller-app/nrfconnect/main/AppTask.cpp +++ b/examples/pump-controller-app/nrfconnect/main/AppTask.cpp @@ -97,7 +97,7 @@ int AppTask::Init() PumpMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -352,7 +352,7 @@ void AppTask::StartThreadHandler(AppEvent * aEvent) if (aEvent->ButtonEvent.PinNo != THREAD_START_BUTTON) return; - if (AddTestCommissioning() != CHIP_NO_ERROR) + if (chip::Server::GetServer().AddTestCommissioning() != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); } @@ -386,7 +386,7 @@ void AppTask::StartBLEAdvertisementHandler(AppEvent * aEvent) return; } - if (OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) + if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) { LOG_ERR("OpenBasicCommissioningWindow() failed"); } diff --git a/examples/temperature-measurement-app/esp32/main/main.cpp b/examples/temperature-measurement-app/esp32/main/main.cpp index 4529eaba8b13d0..8726c712701f57 100644 --- a/examples/temperature-measurement-app/esp32/main/main.cpp +++ b/examples/temperature-measurement-app/esp32/main/main.cpp @@ -80,7 +80,7 @@ extern "C" void app_main() return; } - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/tv-casting-app/linux/main.cpp b/examples/tv-casting-app/linux/main.cpp index 47e86f26d148d2..be006537728c9f 100644 --- a/examples/tv-casting-app/linux/main.cpp +++ b/examples/tv-casting-app/linux/main.cpp @@ -42,8 +42,8 @@ chip::System::SocketWatchToken token; void PrepareForCommissioning(const Mdns::DiscoveredNodeData * selectedCommissioner = nullptr) { // Enter commissioning mode, open commissioning window - InitServer(); - ReturnOnFailure(OpenBasicCommissioningWindow(ResetFabrics::kYes, commissioningWindowTimeoutInSec)); + Server::GetServer().Init(); + ReturnOnFailure(Server::GetServer().OpenBasicCommissioningWindow(ResetFabrics::kYes, commissioningWindowTimeoutInSec)); // Display onboarding payload chip::DeviceLayer::ConfigurationMgr().LogDeviceConfig(); diff --git a/examples/window-app/common/src/WindowApp.cpp b/examples/window-app/common/src/WindowApp.cpp index ea4d0e26fb8468..abca6e309c7708 100644 --- a/examples/window-app/common/src/WindowApp.cpp +++ b/examples/window-app/common/src/WindowApp.cpp @@ -69,7 +69,7 @@ WindowApp::Cover * WindowApp::GetCover(chip::EndpointId endpoint) CHIP_ERROR WindowApp::Init() { // Init ZCL Data Model - InitServer(); + chip::Server::GetServer().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp b/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp index fe35b8955cc160..ff9aade50d4620 100644 --- a/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp +++ b/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp @@ -43,7 +43,7 @@ bool emberAfAdministratorCommissioningClusterOpenCommissioningWindowCallback(End ChipLogProgress(Zcl, "Received command to open commissioning window"); - VerifyOrExit(!IsPairingWindowOpen(), status = EMBER_ZCL_STATUS_FAILURE); + VerifyOrExit(!Server::GetServer().IsPairingWindowOpen(), status = EMBER_ZCL_STATUS_FAILURE); VerifyOrExit(sizeof(verifier) == pakeVerifier.size(), status = EMBER_ZCL_STATUS_FAILURE); VerifyOrExit(iterations >= kPBKDFMinimumIterations, status = EMBER_ZCL_STATUS_FAILURE); VerifyOrExit(iterations <= kPBKDFMaximumIterations, status = EMBER_ZCL_STATUS_FAILURE); @@ -55,8 +55,8 @@ bool emberAfAdministratorCommissioningClusterOpenCommissioningWindowCallback(End memcpy(verifier.mW0, &verifierData[0], kSpake2p_WS_Length); memcpy(verifier.mL, &verifierData[kSpake2p_WS_Length], kSpake2p_WS_Length); - VerifyOrExit(OpenEnhancedCommissioningWindow(commissioningTimeout, discriminator, verifier, iterations, salt, passcodeID) == - CHIP_NO_ERROR, + VerifyOrExit(Server::GetServer().OpenEnhancedCommissioningWindow(commissioningTimeout, discriminator, verifier, iterations, + salt, passcodeID) == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); ChipLogProgress(Zcl, "Commissioning window is now open"); @@ -75,9 +75,9 @@ bool emberAfAdministratorCommissioningClusterOpenBasicCommissioningWindowCallbac { EmberAfStatus status = EMBER_ZCL_STATUS_SUCCESS; ChipLogProgress(Zcl, "Received command to open basic commissioning window"); - VerifyOrExit(!IsPairingWindowOpen(), status = EMBER_ZCL_STATUS_FAILURE); + VerifyOrExit(!Server::GetServer().IsPairingWindowOpen(), status = EMBER_ZCL_STATUS_FAILURE); VerifyOrExit(commissioningTimeout <= kMaxCommissionioningTimeoutSeconds, status = EMBER_ZCL_STATUS_FAILURE); - VerifyOrExit(OpenBasicCommissioningWindow(ResetFabrics::kNo, commissioningTimeout) == CHIP_NO_ERROR, + VerifyOrExit(Server::GetServer().OpenBasicCommissioningWindow(ResetFabrics::kNo, commissioningTimeout) == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); ChipLogProgress(Zcl, "Commissioning window is now open"); @@ -93,7 +93,7 @@ bool emberAfAdministratorCommissioningClusterOpenBasicCommissioningWindowCallbac bool emberAfAdministratorCommissioningClusterRevokeCommissioningCallback(EndpointId endpoint, app::CommandHandler * commandObj) { ChipLogProgress(Zcl, "Received command to close commissioning window"); - ClosePairingWindow(); + Server::GetServer().ClosePairingWindow(); ChipLogProgress(Zcl, "Commissioning window is now closed"); emberAfSendImmediateDefaultResponse(EMBER_ZCL_STATUS_SUCCESS); return true; diff --git a/src/app/clusters/operational-credentials-server/operational-credentials-server.cpp b/src/app/clusters/operational-credentials-server/operational-credentials-server.cpp index 434b2b28efeeac..be6e8a7e43daa6 100644 --- a/src/app/clusters/operational-credentials-server/operational-credentials-server.cpp +++ b/src/app/clusters/operational-credentials-server/operational-credentials-server.cpp @@ -121,7 +121,7 @@ CHIP_ERROR writeFabricsIntoFabricsListAttribute() // Loop through fabrics uint8_t fabricIndex = 0; - for (auto & fabricInfo : GetGlobalFabricTable()) + for (auto & fabricInfo : Server::GetServer().GetFabricTable()) { NodeId nodeId = fabricInfo.GetPeerId().GetNodeId(); uint64_t fabricId = fabricInfo.GetFabricId(); @@ -187,7 +187,7 @@ static FabricInfo * retrieveCurrentFabric() FabricIndex index = emberAfCurrentCommand()->source->GetSecureSession().GetFabricIndex(); emberAfPrintln(EMBER_AF_PRINT_DEBUG, "OpCreds: Finding fabric with fabricIndex %d", index); - return GetGlobalFabricTable().FindFabricWithIndex(index); + return Server::GetServer().GetFabricTable().FindFabricWithIndex(index); } // TODO: The code currently has two sources of truths for fabrics, the fabricInfo table + the attributes. There should only be one, @@ -234,7 +234,7 @@ OpCredsFabricTableDelegate gFabricDelegate; void emberAfPluginOperationalCredentialsServerInitCallback(void) { emberAfPrintln(EMBER_AF_PRINT_DEBUG, "OpCreds: Initiating OpCreds cluster by writing fabrics list from fabric table."); - GetGlobalFabricTable().SetFabricDelegate(&gFabricDelegate); + Server::GetServer().GetFabricTable().SetFabricDelegate(&gFabricDelegate); writeFabricsIntoFabricsListAttribute(); } @@ -244,7 +244,7 @@ bool emberAfOperationalCredentialsClusterRemoveFabricCallback(EndpointId endpoin emberAfPrintln(EMBER_AF_PRINT_DEBUG, "OpCreds: RemoveFabric"); // TODO: Generate emberAfFabricClusterPrintln EmberAfStatus status = EMBER_ZCL_STATUS_SUCCESS; - CHIP_ERROR err = GetGlobalFabricTable().Delete(fabricIndex); + CHIP_ERROR err = Server::GetServer().GetFabricTable().Delete(fabricIndex); VerifyOrExit(err == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); exit: @@ -270,7 +270,7 @@ bool emberAfOperationalCredentialsClusterUpdateFabricLabelCallback(EndpointId en VerifyOrExit(err == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); // Persist updated fabric - err = GetGlobalFabricTable().Store(fabric->GetFabricIndex()); + err = Server::GetServer().GetFabricTable().Store(fabric->GetFabricIndex()); VerifyOrExit(err == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); exit: @@ -359,10 +359,10 @@ bool emberAfOperationalCredentialsClusterAddNOCCallback(EndpointId endpoint, app gFabricBeingCommissioned.SetVendorId(adminVendorId); - err = GetGlobalFabricTable().AddNewFabric(gFabricBeingCommissioned, &fabricIndex); + err = Server::GetServer().GetFabricTable().AddNewFabric(gFabricBeingCommissioned, &fabricIndex); VerifyOrExit(err == CHIP_NO_ERROR, nocResponse = ConvertToNOCResponseStatus(err)); - err = GetGlobalFabricTable().Store(fabricIndex); + err = Server::GetServer().GetFabricTable().Store(fabricIndex); VerifyOrExit(err == CHIP_NO_ERROR, nocResponse = ConvertToNOCResponseStatus(err)); // We might have a new operational identity, so we should start advertising it right away. diff --git a/src/app/server/Mdns.cpp b/src/app/server/Mdns.cpp index f47230e37190b2..854568eb2f45ad 100644 --- a/src/app/server/Mdns.cpp +++ b/src/app/server/Mdns.cpp @@ -42,7 +42,7 @@ namespace { bool HaveOperationalCredentials() { // Look for any fabric info that has a useful operational identity. - for (const Transport::FabricInfo & fabricInfo : GetGlobalFabricTable()) + for (const Transport::FabricInfo & fabricInfo : Server::GetServer().GetFabricTable()) { if (fabricInfo.IsInitialized()) { @@ -110,7 +110,7 @@ CHIP_ERROR GetCommissionableInstanceName(char * buffer, size_t bufferLen) /// Set MDNS operational advertisement CHIP_ERROR AdvertiseOperational() { - for (const Transport::FabricInfo & fabricInfo : GetGlobalFabricTable()) + for (const Transport::FabricInfo & fabricInfo : Server::GetServer().GetFabricTable()) { if (fabricInfo.IsInitialized()) { diff --git a/src/app/server/RendezvousServer.h b/src/app/server/RendezvousServer.h index b0a27120fe09a8..4a73a0ae00acc4 100644 --- a/src/app/server/RendezvousServer.h +++ b/src/app/server/RendezvousServer.h @@ -61,10 +61,10 @@ class RendezvousServer : public SessionEstablishmentDelegate SessionIDAllocator * mIDAllocator = nullptr; - const RendezvousAdvertisementDelegate * mAdvDelegate; + RendezvousAdvertisementDelegate * mAdvDelegate; bool HasAdvertisementDelegate() const { return mAdvDelegate != nullptr; } - const RendezvousAdvertisementDelegate * GetAdvertisementDelegate() const { return mAdvDelegate; } + RendezvousAdvertisementDelegate * GetAdvertisementDelegate() { return mAdvDelegate; } }; } // namespace chip diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index ccdf2ccb356aef..06bf359eb7249b 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * 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. @@ -15,12 +15,11 @@ * limitations under the License. */ -#include - #include #include #include +#include #include #include @@ -45,19 +44,13 @@ #include #include -#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT || CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE -#include -#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT || CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE - -#if CHIP_DEVICE_CONFIG_ENABLE_MDNS -#include -#endif - -using namespace ::chip; -using namespace ::chip::Inet; -using namespace ::chip::Transport; -using namespace ::chip::DeviceLayer; -using namespace ::chip::Messaging; +using chip::RendezvousInformationFlag; +using chip::DeviceLayer::PersistedStorage::KeyValueStoreMgr; +using chip::Inet::IPAddressType; +using chip::Transport::BleListenParameters; +using chip::Transport::kMinValidFabricIndex; +using chip::Transport::PeerAddress; +using chip::Transport::UdpListenParameters; namespace { @@ -72,327 +65,71 @@ constexpr bool isRendezvousBypassed() #endif } -constexpr bool useTestPairing() -{ - // Use the test pairing whenever rendezvous is bypassed. Otherwise, there wouldn't be - // any way to communicate with the device using CHIP protocol. - // This is used to bypass BLE in the cirque test. - // Only in the cirque test this is enabled with --args='bypass_rendezvous=true'. - return isRendezvousBypassed(); -} - -class ServerStorageDelegate : public PersistentStorageDelegate -{ - CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override - { - ChipLogProgress(AppServer, "Retrieved value from server storage."); - return PersistedStorage::KeyValueStoreMgr().Get(key, buffer, size); - } - - CHIP_ERROR SyncSetKeyValue(const char * key, const void * value, uint16_t size) override - { - ChipLogProgress(AppServer, "Stored value in server storage"); - return PersistedStorage::KeyValueStoreMgr().Put(key, value, size); - } - - CHIP_ERROR SyncDeleteKeyValue(const char * key) override - { - ChipLogProgress(AppServer, "Delete value in server storage"); - return PersistedStorage::KeyValueStoreMgr().Delete(key); - } -}; - -ServerStorageDelegate gServerStorage; -SessionIDAllocator gSessionIDAllocator; - -// TODO: The following class is setting the discriminator in Persistent Storage. This is -// is needed since BLE reads the discriminator using ConfigurationMgr APIs. The -// better solution will be to pass the discriminator to BLE without changing it -// in the persistent storage. -// https://github.com/project-chip/connectedhomeip/issues/4767 -class DeviceDiscriminatorCache -{ -public: - CHIP_ERROR UpdateDiscriminator(uint16_t discriminator) - { - if (!mOriginalDiscriminatorCached) - { - // Cache the original discriminator - ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSetupDiscriminator(mOriginalDiscriminator)); - mOriginalDiscriminatorCached = true; - } - - return DeviceLayer::ConfigurationMgr().StoreSetupDiscriminator(discriminator); - } - - CHIP_ERROR RestoreDiscriminator() - { - if (mOriginalDiscriminatorCached) - { - // Restore the original discriminator - ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().StoreSetupDiscriminator(mOriginalDiscriminator)); - mOriginalDiscriminatorCached = false; - } - - return CHIP_NO_ERROR; - } - -private: - bool mOriginalDiscriminatorCached = false; - uint16_t mOriginalDiscriminator = 0; -}; - -DeviceDiscriminatorCache gDeviceDiscriminatorCache; -FabricTable gFabrics; -bool gPairingWindowOpen = false; - -class ServerRendezvousAdvertisementDelegate : public RendezvousAdvertisementDelegate -{ -public: - CHIP_ERROR StartAdvertisement() const override - { - if (isBLE) - { - ReturnErrorOnFailure(chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true)); - } - if (mDelegate != nullptr) - { - mDelegate->OnPairingWindowOpened(); - } - gPairingWindowOpen = true; - return CHIP_NO_ERROR; - } - CHIP_ERROR StopAdvertisement() const override - { - gDeviceDiscriminatorCache.RestoreDiscriminator(); - - gPairingWindowOpen = false; - - if (isBLE) - { - ReturnErrorOnFailure(chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false)); - } - - if (mDelegate != nullptr) - { - mDelegate->OnPairingWindowClosed(); - } - - return CHIP_NO_ERROR; - } - - void SetDelegate(AppDelegate * delegate) { mDelegate = delegate; } - void SetBLE(bool ble) { isBLE = ble; } - void SetFabricIndex(FabricIndex id) { mFabric = id; } - -private: - AppDelegate * mDelegate = nullptr; - FabricIndex mFabric; - bool isBLE = true; -}; - -DemoTransportMgr gTransports; -SecureSessionMgr gSessions; -RendezvousServer gRendezvousServer; -CASEServer gCASEServer; -Messaging::ExchangeManager gExchangeMgr; -ServerRendezvousAdvertisementDelegate gAdvDelegate; - -class ServerCallback : public ExchangeDelegate -{ -public: - CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * exchangeContext, const PacketHeader & packetHeader, - const PayloadHeader & payloadHeader, System::PacketBufferHandle && buffer) override - { - CHIP_ERROR err = CHIP_NO_ERROR; - // as soon as a client connects, assume it is connected - VerifyOrExit(!buffer.IsNull(), ChipLogError(AppServer, "Received data but couldn't process it...")); - VerifyOrExit(mSessionMgr != nullptr, ChipLogError(AppServer, "SecureSessionMgr is not initilized yet")); - HandleDataModelMessage(exchangeContext, std::move(buffer)); - - exit: - return err; - } - - void OnResponseTimeout(ExchangeContext * ec) override - { - ChipLogProgress(AppServer, "Failed to receive response"); - if (mDelegate != nullptr) - { - mDelegate->OnReceiveError(); - } - } - - void SetDelegate(AppDelegate * delegate) { mDelegate = delegate; } - void SetSessionMgr(SecureSessionMgr * mgr) { mSessionMgr = mgr; } - -private: - AppDelegate * mDelegate = nullptr; - SecureSessionMgr * mSessionMgr = nullptr; -}; - -secure_channel::MessageCounterManager gMessageCounterManager; -ServerCallback gCallbacks; -SecurePairingUsingTestSecret gTestPairing; - -#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT - -chip::Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient gUDCClient; - -#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT - -void HandlePairingWindowTimeout(System::Layer * aSystemLayer, void * aAppState) +void HandlePairingWindowTimeout(chip::System::Layer * aSystemLayer, void * aAppState) { - ClosePairingWindow(); + chip::Server * server = static_cast(aAppState); + server->ClosePairingWindow(); } } // namespace -CHIP_ERROR OpenBasicCommissioningWindow(ResetFabrics resetFabrics, uint16_t commissioningTimeoutSeconds, - chip::PairingWindowAdvertisement advertisementMode) -{ - // TODO(cecille): If this is re-called when the window is already open, what should happen? - gDeviceDiscriminatorCache.RestoreDiscriminator(); - - uint32_t pinCode; - ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSetupPinCode(pinCode)); - - RendezvousParameters params; - - params.SetSetupPINCode(pinCode); -#if CONFIG_NETWORK_LAYER_BLE - gAdvDelegate.SetBLE(advertisementMode == chip::PairingWindowAdvertisement::kBle); - params.SetAdvertisementDelegate(&gAdvDelegate); - if (advertisementMode == chip::PairingWindowAdvertisement::kBle) - { - params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); - } -#endif // CONFIG_NETWORK_LAYER_BLE - - if (resetFabrics == ResetFabrics::kYes) - { - gFabrics.DeleteAllFabrics(); - // Only resetting gNextAvailableFabricIndex at reboot otherwise previously paired device with fabricID 0 - // can continue sending messages to accessory as next available fabric will also be 0. - // This logic is not up to spec, will be implemented up to spec once AddOptCert is implemented. - gFabrics.Reset(); - } - - ReturnErrorOnFailure(gRendezvousServer.WaitForPairing( - std::move(params), kSpake2p_Iteration_Count, - ByteSpan(reinterpret_cast(kSpake2pKeyExchangeSalt), strlen(kSpake2pKeyExchangeSalt)), 0, &gExchangeMgr, - &gTransports, &gSessions)); - - if (commissioningTimeoutSeconds != kNoCommissioningTimeout) - { - ReturnErrorOnFailure( - DeviceLayer::SystemLayer.StartTimer(commissioningTimeoutSeconds * 1000, HandlePairingWindowTimeout, nullptr)); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR OpenEnhancedCommissioningWindow(uint16_t commissioningTimeoutSeconds, uint16_t discriminator, PASEVerifier & verifier, - uint32_t iterations, ByteSpan salt, uint16_t passcodeID) -{ - RendezvousParameters params; - - ReturnErrorOnFailure(gDeviceDiscriminatorCache.UpdateDiscriminator(discriminator)); - -// TODO: Do not turn on BLE when opening the Enhanced Commissioning Window. -#if CONFIG_NETWORK_LAYER_BLE - gAdvDelegate.SetBLE(true); - params.SetAdvertisementDelegate(&gAdvDelegate); - params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); -#endif // CONFIG_NETWORK_LAYER_BLE - params.SetPASEVerifier(verifier).SetAdvertisementDelegate(&gAdvDelegate); - - ReturnErrorOnFailure( - gRendezvousServer.WaitForPairing(std::move(params), iterations, salt, passcodeID, &gExchangeMgr, &gTransports, &gSessions)); - - if (commissioningTimeoutSeconds != kNoCommissioningTimeout) - { - ReturnErrorOnFailure( - DeviceLayer::SystemLayer.StartTimer(commissioningTimeoutSeconds * 1000, HandlePairingWindowTimeout, nullptr)); - } +namespace chip { - return CHIP_NO_ERROR; -} +Server Server::sServer; -void ClosePairingWindow() +CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint16_t unsecureServicePort) { - if (gPairingWindowOpen) - { - ChipLogProgress(AppServer, "Closing pairing window"); - gRendezvousServer.Cleanup(); - } -} - -bool IsPairingWindowOpen() -{ - return gPairingWindowOpen; -} - -uint16_t gSecuredServicePort = CHIP_PORT; -uint16_t gUnsecuredServicePort = CHIP_UDC_PORT; - -void SetServerConfig(ServerConfigParams params) -{ - gSecuredServicePort = params.securedServicePort; - gUnsecuredServicePort = params.unsecuredServicePort; -} + mAppDelgate = delegate; + mSecuredServicePort = secureServicePort; + mUnsecuredServicePort = unsecureServicePort; -// The function will initialize datamodel handler and then start the server -// The server assumes the platform's networking has been setup already -void InitServer(AppDelegate * delegate) -{ CHIP_ERROR err = CHIP_NO_ERROR; chip::Platform::MemoryInit(); - InitDataModelHandler(&gExchangeMgr); - gCallbacks.SetDelegate(delegate); + InitDataModelHandler(&mExchangeMgr); #if CHIP_DEVICE_LAYER_TARGET_DARWIN - err = PersistedStorage::KeyValueStoreMgrImpl().Init("chip.store"); + err = DeviceLayer::PersistedStorage::KeyValueStoreMgrImpl().Init("chip.store"); SuccessOrExit(err); #elif CHIP_DEVICE_LAYER_TARGET_LINUX - PersistedStorage::KeyValueStoreMgrImpl().Init(CHIP_CONFIG_KVS_PATH); + DeviceLayer::PersistedStorage::KeyValueStoreMgrImpl().Init(CHIP_CONFIG_KVS_PATH); #endif - err = gRendezvousServer.Init(delegate, &gSessionIDAllocator); + err = mRendezvousServer.Init(mAppDelgate, &mSessionIDAllocator); SuccessOrExit(err); - gAdvDelegate.SetDelegate(delegate); - - err = gFabrics.Init(&gServerStorage); + err = mFabrics.Init(this); SuccessOrExit(err); // Init transport before operations with secure session mgr. - err = gTransports.Init( - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6).SetListenPort(gSecuredServicePort) + err = mTransports.Init(UdpListenParameters(&DeviceLayer::InetLayer) + .SetAddressType(IPAddressType::kIPAddressType_IPv6) + .SetListenPort(mSecuredServicePort) #if INET_CONFIG_ENABLE_IPV4 - , - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv4).SetListenPort(gSecuredServicePort) + , + UdpListenParameters(&DeviceLayer::InetLayer) + .SetAddressType(IPAddressType::kIPAddressType_IPv4) + .SetListenPort(mSecuredServicePort) #endif #if CONFIG_NETWORK_LAYER_BLE - , - BleListenParameters(DeviceLayer::ConnectivityMgr().GetBleLayer()) + , + BleListenParameters(DeviceLayer::ConnectivityMgr().GetBleLayer()) #endif ); SuccessOrExit(err); - err = gSessions.Init(&DeviceLayer::SystemLayer, &gTransports, &gFabrics, &gMessageCounterManager); + err = mSessions.Init(&DeviceLayer::SystemLayer, &mTransports, &mFabrics, &mMessageCounterManager); SuccessOrExit(err); - err = gExchangeMgr.Init(&gSessions); + err = mExchangeMgr.Init(&mSessions); SuccessOrExit(err); - err = gMessageCounterManager.Init(&gExchangeMgr); + err = mMessageCounterManager.Init(&mExchangeMgr); SuccessOrExit(err); - err = chip::app::InteractionModelEngine::GetInstance()->Init(&gExchangeMgr, nullptr); + err = chip::app::InteractionModelEngine::GetInstance()->Init(&mExchangeMgr, nullptr); SuccessOrExit(err); #if defined(CHIP_APP_USE_ECHO) @@ -400,7 +137,7 @@ void InitServer(AppDelegate * delegate) SuccessOrExit(err); #endif - if (useTestPairing()) + if (isRendezvousBypassed()) { ChipLogProgress(AppServer, "Rendezvous and secure pairing skipped"); SuccessOrExit(err = AddTestCommissioning()); @@ -419,8 +156,8 @@ void InitServer(AppDelegate * delegate) } #if CHIP_DEVICE_CONFIG_ENABLE_MDNS - app::Mdns::SetSecuredPort(gSecuredServicePort); - app::Mdns::SetUnsecuredPort(gUnsecuredServicePort); + app::Mdns::SetSecuredPort(mSecuredServicePort); + app::Mdns::SetUnsecuredPort(mUnsecuredServicePort); #endif // CHIP_DEVICE_CONFIG_ENABLE_MDNS // ESP32 and Mbed OS examples have a custom logic for enabling DNS-SD #if CHIP_DEVICE_CONFIG_ENABLE_MDNS && !CHIP_DEVICE_LAYER_TARGET_ESP32 && !CHIP_DEVICE_LAYER_TARGET_MBED @@ -428,18 +165,16 @@ void InitServer(AppDelegate * delegate) app::Mdns::StartServer(); #endif - gCallbacks.SetSessionMgr(&gSessions); - // Register to receive unsolicited legacy ZCL messages from the exchange manager. - err = gExchangeMgr.RegisterUnsolicitedMessageHandlerForProtocol(Protocols::TempZCL::Id, &gCallbacks); + err = mExchangeMgr.RegisterUnsolicitedMessageHandlerForProtocol(Protocols::TempZCL::Id, this); SuccessOrExit(err); // Register to receive unsolicited Service Provisioning messages from the exchange manager. - err = gExchangeMgr.RegisterUnsolicitedMessageHandlerForProtocol(Protocols::ServiceProvisioning::Id, &gCallbacks); + err = mExchangeMgr.RegisterUnsolicitedMessageHandlerForProtocol(Protocols::ServiceProvisioning::Id, this); SuccessOrExit(err); - err = gCASEServer.ListenForSessionEstablishment(&gExchangeMgr, &gTransports, chip::DeviceLayer::ConnectivityMgr().GetBleLayer(), - &gSessions, &GetGlobalFabricTable(), &gSessionIDAllocator); + err = mCASEServer.ListenForSessionEstablishment(&mExchangeMgr, &mTransports, chip::DeviceLayer::ConnectivityMgr().GetBleLayer(), + &mSessions, &mFabrics, &mSessionIDAllocator); SuccessOrExit(err); exit: @@ -451,14 +186,14 @@ void InitServer(AppDelegate * delegate) { ChipLogProgress(AppServer, "Server Listening..."); } + return err; } #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 SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner) +CHIP_ERROR Server::SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner) { ChipLogDetail(AppServer, "SendUserDirectedCommissioningRequest2"); @@ -479,7 +214,7 @@ CHIP_ERROR SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress com return CHIP_ERROR_NO_MEMORY; } - err = gUDCClient.SendUDCMessage(&gTransports, std::move(payloadBuf), commissioner); + err = gUDCClient.SendUDCMessage(&mTransports, std::move(payloadBuf), commissioner); if (err == CHIP_NO_ERROR) { ChipLogDetail(AppServer, "Send UDC request success"); @@ -490,20 +225,105 @@ CHIP_ERROR SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress com } return err; } - #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT -CHIP_ERROR AddTestCommissioning() +CHIP_ERROR Server::OpenBasicCommissioningWindow(ResetFabrics resetFabrics, uint16_t commissioningTimeoutSeconds, + PairingWindowAdvertisement advertisementMode) +{ + // TODO(cecille): If this is re-called when the window is already open, what should happen? + mDeviceDiscriminatorCache.RestoreDiscriminator(); + + uint32_t pinCode; + ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSetupPinCode(pinCode)); + + RendezvousParameters params; + + params.SetSetupPINCode(pinCode); + SetBLE(false); +#if CONFIG_NETWORK_LAYER_BLE + SetBLE(advertisementMode == chip::PairingWindowAdvertisement::kBle); + params.SetAdvertisementDelegate(this); + if (advertisementMode == chip::PairingWindowAdvertisement::kBle) + { + params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); + } +#endif // CONFIG_NETWORK_LAYER_BLE + + if (resetFabrics == ResetFabrics::kYes) + { + mFabrics.DeleteAllFabrics(); + // Only resetting gNextAvailableFabricIndex at reboot otherwise previously paired device with fabricID 0 + // can continue sending messages to accessory as next available fabric will also be 0. + // This logic is not up to spec, will be implemented up to spec once AddOptCert is implemented. + mFabrics.Reset(); + } + + ReturnErrorOnFailure(mRendezvousServer.WaitForPairing( + std::move(params), kSpake2p_Iteration_Count, + ByteSpan(reinterpret_cast(kSpake2pKeyExchangeSalt), strlen(kSpake2pKeyExchangeSalt)), 0, &mExchangeMgr, + &mTransports, &mSessions)); + + if (commissioningTimeoutSeconds != kNoCommissioningTimeout) + { + ReturnErrorOnFailure( + DeviceLayer::SystemLayer.StartTimer(commissioningTimeoutSeconds * 1000, HandlePairingWindowTimeout, this)); + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR Server::OpenEnhancedCommissioningWindow(uint16_t commissioningTimeoutSeconds, uint16_t discriminator, + PASEVerifier & verifier, uint32_t iterations, ByteSpan salt, uint16_t passcodeID) +{ + RendezvousParameters params; + + ReturnErrorOnFailure(mDeviceDiscriminatorCache.UpdateDiscriminator(discriminator)); + + SetBLE(false); +#if CONFIG_NETWORK_LAYER_BLE + SetBLE(true); + params.SetAdvertisementDelegate(this); + params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); +#endif + params.SetPASEVerifier(verifier).SetAdvertisementDelegate(this); + + ReturnErrorOnFailure( + mRendezvousServer.WaitForPairing(std::move(params), iterations, salt, passcodeID, &mExchangeMgr, &mTransports, &mSessions)); + + if (commissioningTimeoutSeconds != kNoCommissioningTimeout) + { + ReturnErrorOnFailure( + DeviceLayer::SystemLayer.StartTimer(commissioningTimeoutSeconds * 1000, HandlePairingWindowTimeout, this)); + } + + return CHIP_NO_ERROR; +} + +void Server::ClosePairingWindow() +{ + if (mPairingWindowOpen) + { + ChipLogProgress(AppServer, "Closing pairing window"); + mRendezvousServer.Cleanup(); + } +} + +bool Server::IsPairingWindowOpen() +{ + return mPairingWindowOpen; +} + +CHIP_ERROR Server::AddTestCommissioning() { CHIP_ERROR err = CHIP_NO_ERROR; PASESession * testSession = nullptr; PASESessionSerializable serializedTestSession; - gTestPairing.ToSerializable(serializedTestSession); + mTestPairing.ToSerializable(serializedTestSession); testSession = chip::Platform::New(); testSession->FromSerializable(serializedTestSession); - SuccessOrExit(err = gSessions.NewPairing(Optional{ PeerAddress::Uninitialized() }, chip::kTestControllerNodeId, + SuccessOrExit(err = mSessions.NewPairing(Optional{ PeerAddress::Uninitialized() }, chip::kTestControllerNodeId, testSession, SecureSession::SessionRole::kResponder, kMinValidFabricIndex)); exit: @@ -514,11 +334,106 @@ CHIP_ERROR AddTestCommissioning() } if (err != CHIP_NO_ERROR) - gFabrics.ReleaseFabricIndex(kMinValidFabricIndex); + { + mFabrics.ReleaseFabricIndex(kMinValidFabricIndex); + } + return err; +} + +CHIP_ERROR Server::SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) +{ + ChipLogDetail(AppServer, "Retrieved value from server storage."); + return KeyValueStoreMgr().Get(key, buffer, size); +} + +CHIP_ERROR Server::SyncSetKeyValue(const char * key, const void * value, uint16_t size) +{ + ChipLogDetail(AppServer, "Stored value in server storage"); + return KeyValueStoreMgr().Put(key, value, size); +} + +CHIP_ERROR Server::SyncDeleteKeyValue(const char * key) +{ + ChipLogDetail(AppServer, "Delete value in server storage"); + return KeyValueStoreMgr().Delete(key); +} + +CHIP_ERROR Server::StartAdvertisement() +{ + if (mIsBLE) + { + ReturnErrorOnFailure(chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true)); + } + if (mAppDelgate != nullptr) + { + mAppDelgate->OnPairingWindowOpened(); + } + mPairingWindowOpen = true; + return CHIP_NO_ERROR; +} + +CHIP_ERROR Server::StopAdvertisement() +{ + mDeviceDiscriminatorCache.RestoreDiscriminator(); + + mPairingWindowOpen = false; + + if (mIsBLE) + { + ReturnErrorOnFailure(chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false)); + } + + if (mAppDelgate != nullptr) + { + mAppDelgate->OnPairingWindowClosed(); + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR Server::OnMessageReceived(Messaging::ExchangeContext * exchangeContext, const PacketHeader & packetHeader, + const PayloadHeader & payloadHeader, System::PacketBufferHandle && buffer) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + // as soon as a client connects, assume it is connected + VerifyOrExit(!buffer.IsNull(), ChipLogError(AppServer, "Received data but couldn't process it...")); + HandleDataModelMessage(exchangeContext, std::move(buffer)); + +exit: return err; } -FabricTable & GetGlobalFabricTable() +void Server::OnResponseTimeout(Messaging::ExchangeContext * ec) +{ + ChipLogProgress(AppServer, "Failed to receive response"); + if (mAppDelgate != nullptr) + { + mAppDelgate->OnReceiveError(); + } +} + +CHIP_ERROR Server::DeviceDiscriminatorCache::UpdateDiscriminator(uint16_t discriminator) { - return gFabrics; + if (!mOriginalDiscriminatorCached) + { + // Cache the original discriminator + ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSetupDiscriminator(mOriginalDiscriminator)); + mOriginalDiscriminatorCached = true; + } + + return DeviceLayer::ConfigurationMgr().StoreSetupDiscriminator(discriminator); } + +CHIP_ERROR Server::DeviceDiscriminatorCache::RestoreDiscriminator() +{ + if (mOriginalDiscriminatorCached) + { + // Restore the original discriminator + ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().StoreSetupDiscriminator(mOriginalDiscriminator)); + mOriginalDiscriminatorCached = false; + } + + return CHIP_NO_ERROR; +} + +} // namespace chip diff --git a/src/app/server/Server.h b/src/app/server/Server.h index 6ff2d315592aeb..db0d358844d3b8 100644 --- a/src/app/server/Server.h +++ b/src/app/server/Server.h @@ -18,20 +18,21 @@ #pragma once #include +#include #include #include +#include +#include #include +#include +#include #include #include #include #include #include -struct ServerConfigParams -{ - uint16_t securedServicePort = CHIP_PORT; - uint16_t unsecuredServicePort = CHIP_UDC_PORT; -}; +namespace chip { constexpr size_t kMaxBlePendingPackets = 1; @@ -45,32 +46,6 @@ using DemoTransportMgr = chip::TransportMgr #endif >; -/** - * Currently, this method must be called BEFORE InitServer. - * In the future, it would be nice to be able to call it - * at any time but that requires handling for changes to every - * field on ServerConfigParams (restarting port listener, etc). - * - */ -void SetServerConfig(ServerConfigParams params); - -/** - * Initialize DataModelHandler and start CHIP datamodel server, the server - * assumes the platform's networking has been setup already. - * - * @param [in] delegate An optional AppDelegate - */ -void InitServer(AppDelegate * delegate = nullptr); - -#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT -CHIP_ERROR SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner); -#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT - -CHIP_ERROR AddTestCommissioning(); - -chip::Transport::FabricTable & GetGlobalFabricTable(); - -namespace chip { enum class ResetFabrics { @@ -84,21 +59,102 @@ enum class PairingWindowAdvertisement kMdns, }; -} // namespace chip - constexpr uint16_t kNoCommissioningTimeout = UINT16_MAX; -/** - * Open the pairing window using default configured parameters. - */ -CHIP_ERROR -OpenBasicCommissioningWindow(chip::ResetFabrics resetFabrics, uint16_t commissioningTimeoutSeconds = kNoCommissioningTimeout, - chip::PairingWindowAdvertisement advertisementMode = chip::PairingWindowAdvertisement::kBle); +class Server : public RendezvousAdvertisementDelegate, public PersistentStorageDelegate, public Messaging::ExchangeDelegate +{ +public: + CHIP_ERROR Init(AppDelegate * delegate = nullptr, uint16_t secureServicePort = CHIP_PORT, + uint16_t unsecureServicePort = CHIP_UDC_PORT); + +#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT + CHIP_ERROR SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner); +#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT + + /** + * Open the pairing window using default configured parameters. + */ + CHIP_ERROR OpenBasicCommissioningWindow(ResetFabrics resetFabrics, + uint16_t commissioningTimeoutSeconds = kNoCommissioningTimeout, + PairingWindowAdvertisement advertisementMode = chip::PairingWindowAdvertisement::kBle); + + CHIP_ERROR OpenEnhancedCommissioningWindow(uint16_t commissioningTimeoutSeconds, uint16_t discriminator, + PASEVerifier & verifier, uint32_t iterations, chip::ByteSpan salt, + uint16_t passcodeID); -CHIP_ERROR OpenEnhancedCommissioningWindow(uint16_t commissioningTimeoutSeconds, uint16_t discriminator, - chip::PASEVerifier & verifier, uint32_t iterations, chip::ByteSpan salt, - uint16_t passcodeID); + CHIP_ERROR AddTestCommissioning(); -void ClosePairingWindow(); + void ClosePairingWindow(); -bool IsPairingWindowOpen(); + bool IsPairingWindowOpen(); + + void SetBLE(bool ble) { mIsBLE = ble; } + + void SetFabricIndex(FabricIndex id) { mFabricIndex = id; } + + Transport::FabricTable & GetFabricTable() { return mFabrics; } + + Messaging::ExchangeManager & GetExchangManager() { return mExchangeMgr; } + + SessionIDAllocator & GetSessionIDAllocator() { return mSessionIDAllocator; } + + SecureSessionMgr & GetSecureSessionManager() { return mSessions; } + + static Server & GetServer() { return sServer; } + +private: + Server() {} + + static Server sServer; + + class DeviceDiscriminatorCache + { + public: + CHIP_ERROR UpdateDiscriminator(uint16_t discriminator); + + CHIP_ERROR RestoreDiscriminator(); + + private: + bool mOriginalDiscriminatorCached = false; + uint16_t mOriginalDiscriminator = 0; + }; + + /// PersistentStorageDelegate implementation + CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override; + CHIP_ERROR SyncSetKeyValue(const char * key, const void * value, uint16_t size) override; + CHIP_ERROR SyncDeleteKeyValue(const char * key) override; + + /// RendezvousAdvertisementDelegate implementation + CHIP_ERROR StartAdvertisement() override; + CHIP_ERROR StopAdvertisement() override; + + // Messaging::ExchangeDelegate + CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * exchangeContext, const PacketHeader & packetHeader, + const PayloadHeader & payloadHeader, System::PacketBufferHandle && buffer) override; + void OnResponseTimeout(Messaging::ExchangeContext * ec) override; + + AppDelegate * mAppDelgate; + + DemoTransportMgr mTransports; + SecureSessionMgr mSessions; + RendezvousServer mRendezvousServer; + CASEServer mCASEServer; + Messaging::ExchangeManager mExchangeMgr; + Transport::FabricTable mFabrics; + SessionIDAllocator mSessionIDAllocator; + secure_channel::MessageCounterManager mMessageCounterManager; +#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT + chip::Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient gUDCClient; +#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT + SecurePairingUsingTestSecret mTestPairing; + + DeviceDiscriminatorCache mDeviceDiscriminatorCache; + + uint16_t mSecuredServicePort; + uint16_t mUnsecuredServicePort; + bool mPairingWindowOpen = false; + FabricIndex mFabricIndex; + bool mIsBLE = true; +}; + +} // namespace chip diff --git a/src/app/server/SessionManager.h b/src/app/server/SessionManager.h deleted file mode 100644 index 17d78a987de5ab..00000000000000 --- a/src/app/server/SessionManager.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * - * Copyright (c) 2020 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. - */ - -#pragma once - -#include - -namespace chip { -SecureSessionMgr & SessionManager(); -} // namespace chip diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index a10abf133bd980..ea3957df609a88 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -397,13 +397,13 @@ class DeviceCommissionerRendezvousAdvertisementDelegate : public RendezvousAdver * @brief * Starts advertisement of the device for rendezvous availability. */ - CHIP_ERROR StartAdvertisement() const override { return CHIP_NO_ERROR; } + CHIP_ERROR StartAdvertisement() override { return CHIP_NO_ERROR; } /** * @brief * Stops advertisement of the device for rendezvous availability. */ - CHIP_ERROR StopAdvertisement() const override { return CHIP_NO_ERROR; } + CHIP_ERROR StopAdvertisement() override { return CHIP_NO_ERROR; } }; /** diff --git a/src/protocols/secure_channel/RendezvousParameters.h b/src/protocols/secure_channel/RendezvousParameters.h index 17bb455d49e7f0..6dfab892b5fa24 100644 --- a/src/protocols/secure_channel/RendezvousParameters.h +++ b/src/protocols/secure_channel/RendezvousParameters.h @@ -35,13 +35,13 @@ class DLL_EXPORT RendezvousAdvertisementDelegate { public: /// called to start advertising that rendezvous is possible (commisioning available) - virtual CHIP_ERROR StartAdvertisement() const { return CHIP_ERROR_NOT_IMPLEMENTED; } + virtual CHIP_ERROR StartAdvertisement() { return CHIP_ERROR_NOT_IMPLEMENTED; } /// called when advertisement is not needed for Rendezvous (e.g. got a BLE connection) - virtual CHIP_ERROR StopAdvertisement() const { return CHIP_ERROR_NOT_IMPLEMENTED; } + virtual CHIP_ERROR StopAdvertisement() { return CHIP_ERROR_NOT_IMPLEMENTED; } /// Called when a rendezvous operation is complete - virtual void RendezvousComplete() const {} + virtual void RendezvousComplete() {} virtual ~RendezvousAdvertisementDelegate() {} }; @@ -113,7 +113,7 @@ class RendezvousParameters bool HasAdvertisementDelegate() const { return mAdvDelegate != nullptr; } - const RendezvousAdvertisementDelegate * GetAdvertisementDelegate() const { return mAdvDelegate; } + RendezvousAdvertisementDelegate * GetAdvertisementDelegate() const { return mAdvDelegate; } RendezvousParameters & SetAdvertisementDelegate(RendezvousAdvertisementDelegate * delegate) { From ee618caf06be0725a2fc218a6ae0e0c87d2037fe Mon Sep 17 00:00:00 2001 From: Jiacheng Guo Date: Mon, 30 Aug 2021 20:17:07 +0800 Subject: [PATCH 2/8] Make Server combination of small objects --- examples/all-clusters-app/esp32/main/main.cpp | 8 +- examples/bridge-app/esp32/main/main.cpp | 2 +- examples/bridge-app/linux/main.cpp | 2 +- examples/lighting-app/efr32/src/AppTask.cpp | 2 +- examples/lighting-app/k32w/main/AppTask.cpp | 5 +- examples/lighting-app/mbed/main/AppTask.cpp | 2 +- .../lighting-app/nrfconnect/main/AppTask.cpp | 6 +- examples/lighting-app/qpg/src/AppTask.cpp | 4 +- examples/lighting-app/telink/src/AppTask.cpp | 4 +- .../lock-app/cc13x2x7_26x2x7/main/AppTask.cpp | 5 +- examples/lock-app/efr32/src/AppTask.cpp | 2 +- examples/lock-app/esp32/main/main.cpp | 2 +- examples/lock-app/k32w/main/AppTask.cpp | 5 +- examples/lock-app/mbed/main/AppTask.cpp | 2 +- examples/lock-app/nrfconnect/main/AppTask.cpp | 6 +- examples/lock-app/p6/src/AppTask.cpp | 2 +- examples/lock-app/qpg/src/AppTask.cpp | 5 +- examples/ota-provider-app/linux/main.cpp | 2 +- examples/platform/linux/AppMain.cpp | 2 +- .../linux/CommissioneeShellCommands.cpp | 2 +- .../pump-app/cc13x2x7_26x2x7/main/AppTask.cpp | 5 +- examples/pump-app/nrfconnect/main/AppTask.cpp | 6 +- .../cc13x2x7_26x2x7/main/AppTask.cpp | 5 +- .../nrfconnect/main/AppTask.cpp | 6 +- .../esp32/main/main.cpp | 2 +- examples/tv-casting-app/linux/main.cpp | 5 +- examples/window-app/common/src/WindowApp.cpp | 2 +- .../administrator-commissioning-server.cpp | 13 +- .../operational-credentials-server.cpp | 14 +- src/app/server/BUILD.gn | 2 + src/app/server/CommissionManager.cpp | 174 ++++++++++++++++++ src/app/server/CommissionManager.h | 84 +++++++++ src/app/server/Mdns.cpp | 4 +- src/app/server/Server.cpp | 168 ++--------------- src/app/server/Server.h | 96 +++++----- 35 files changed, 389 insertions(+), 267 deletions(-) create mode 100644 src/app/server/CommissionManager.cpp create mode 100644 src/app/server/CommissionManager.h diff --git a/examples/all-clusters-app/esp32/main/main.cpp b/examples/all-clusters-app/esp32/main/main.cpp index 81dab2c318fb70..b03f796547d431 100644 --- a/examples/all-clusters-app/esp32/main/main.cpp +++ b/examples/all-clusters-app/esp32/main/main.cpp @@ -346,7 +346,7 @@ class SetupListModel : public ListScreen::Model if (i == 0) { ConnectivityMgr().ClearWiFiStationProvision(); - chip::Server::GetServer().OpenBasicCommissioningWindow(ResetFabrics::kYes); + chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(ResetFabrics::kYes); } else if (i == 1) { @@ -355,8 +355,8 @@ class SetupListModel : public ListScreen::Model else if (i == 2) { app::Mdns::AdvertiseCommissionableNode(app::Mdns::CommissioningMode::kEnabledBasic); - chip::Server::GetServer().OpenBasicCommissioningWindow(ResetFabrics::kYes, kNoCommissioningTimeout, - PairingWindowAdvertisement::kMdns); + chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow( + ResetFabrics::kYes, kNoCommissioningTimeout, CommissioningWindowAdvertisement::kMdns); } } @@ -628,7 +628,7 @@ extern "C" void app_main() // Init ZCL Data Model and CHIP App Server AppCallbacks callbacks; - chip::Server::GetServer().Init(&callbacks); + chip::Server::GetInstance().Init(&callbacks); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/bridge-app/esp32/main/main.cpp b/examples/bridge-app/esp32/main/main.cpp index cbb0297c7140c5..ad2420ded777ca 100644 --- a/examples/bridge-app/esp32/main/main.cpp +++ b/examples/bridge-app/esp32/main/main.cpp @@ -390,7 +390,7 @@ extern "C" void app_main() return; } - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/bridge-app/linux/main.cpp b/examples/bridge-app/linux/main.cpp index 00e9713f45508b..9d4f08c1b07eb0 100644 --- a/examples/bridge-app/linux/main.cpp +++ b/examples/bridge-app/linux/main.cpp @@ -513,7 +513,7 @@ int main(int argc, char * argv[]) chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true); // Init ZCL Data Model and CHIP App Server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lighting-app/efr32/src/AppTask.cpp b/examples/lighting-app/efr32/src/AppTask.cpp index 1caeff477c5f07..728fe97e5d3c3f 100644 --- a/examples/lighting-app/efr32/src/AppTask.cpp +++ b/examples/lighting-app/efr32/src/AppTask.cpp @@ -108,7 +108,7 @@ CHIP_ERROR AppTask::Init() CHIP_ERROR err = CHIP_NO_ERROR; // Init ZCL Data Model - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lighting-app/k32w/main/AppTask.cpp b/examples/lighting-app/k32w/main/AppTask.cpp index 338057f8c2d742..9e7428f26875a1 100644 --- a/examples/lighting-app/k32w/main/AppTask.cpp +++ b/examples/lighting-app/k32w/main/AppTask.cpp @@ -88,7 +88,7 @@ CHIP_ERROR AppTask::Init() CHIP_ERROR err = CHIP_NO_ERROR; // Init ZCL Data Model and start server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -489,7 +489,8 @@ void AppTask::BleHandler(AppEvent * aEvent) { ConnectivityMgr().SetBLEAdvertisingEnabled(true); - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == + CHIP_NO_ERROR) { K32W_LOG("Started BLE Advertising!"); } diff --git a/examples/lighting-app/mbed/main/AppTask.cpp b/examples/lighting-app/mbed/main/AppTask.cpp index 99aedd0f64afcf..08f48fb5c11405 100644 --- a/examples/lighting-app/mbed/main/AppTask.cpp +++ b/examples/lighting-app/mbed/main/AppTask.cpp @@ -116,7 +116,7 @@ int AppTask::Init() chip::DeviceLayer::ConnectivityMgrImpl().StartWiFiManagement(); // Init ZCL Data Model and start server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lighting-app/nrfconnect/main/AppTask.cpp b/examples/lighting-app/nrfconnect/main/AppTask.cpp index b7b46f5343bf7c..ad42a405433237 100644 --- a/examples/lighting-app/nrfconnect/main/AppTask.cpp +++ b/examples/lighting-app/nrfconnect/main/AppTask.cpp @@ -106,7 +106,7 @@ int AppTask::Init() LightingMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -352,7 +352,7 @@ void AppTask::StartThreadHandler(AppEvent * aEvent) if (aEvent->ButtonEvent.PinNo != THREAD_START_BUTTON) return; - if (chip::Server::GetServer().AddTestCommissioning() != CHIP_NO_ERROR) + if (chip::Server::GetInstance().AddTestCommissioning() != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); } @@ -386,7 +386,7 @@ void AppTask::StartBLEAdvertisementHandler(AppEvent * aEvent) return; } - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) { LOG_ERR("OpenBasicCommissioningWindow() failed"); } diff --git a/examples/lighting-app/qpg/src/AppTask.cpp b/examples/lighting-app/qpg/src/AppTask.cpp index 2cde8d8033db83..2c9807ac18b258 100644 --- a/examples/lighting-app/qpg/src/AppTask.cpp +++ b/examples/lighting-app/qpg/src/AppTask.cpp @@ -100,7 +100,7 @@ CHIP_ERROR AppTask::Init() qvCHIP_SetBtnCallback(ButtonEventHandler); // Init ZCL Data Model - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -111,7 +111,7 @@ CHIP_ERROR AppTask::Init() PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); // Enable BLE advertisements - chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo); + chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo); ChipLogProgress(NotSpecified, "BLE advertising started. Waiting for Pairing."); return err; diff --git a/examples/lighting-app/telink/src/AppTask.cpp b/examples/lighting-app/telink/src/AppTask.cpp index 5a22deb9b0763f..652f07822ccdb6 100644 --- a/examples/lighting-app/telink/src/AppTask.cpp +++ b/examples/lighting-app/telink/src/AppTask.cpp @@ -98,7 +98,7 @@ CHIP_ERROR AppTask::Init() LightingMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -106,7 +106,7 @@ CHIP_ERROR AppTask::Init() ConfigurationMgr().LogDeviceConfig(); PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); - ret = chip::Server::GetServer().AddTestCommissioning(); + ret = chip::Server::GetInstance().AddTestCommissioning(); if (ret != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); diff --git a/examples/lock-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/lock-app/cc13x2x7_26x2x7/main/AppTask.cpp index 3e6813b090bdb3..fe663af7ddadec 100644 --- a/examples/lock-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/lock-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -144,7 +144,7 @@ int AppTask::Init() // Init ZCL Data Model and start server PLAT_LOG("Initialize Server"); - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -333,7 +333,8 @@ void AppTask::DispatchEvent(AppEvent * aEvent) // Enable BLE advertisements if (!ConnectivityMgr().IsBLEAdvertisingEnabled()) { - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == + CHIP_NO_ERROR) { PLAT_LOG("Enabled BLE Advertisement"); } diff --git a/examples/lock-app/efr32/src/AppTask.cpp b/examples/lock-app/efr32/src/AppTask.cpp index 0a0ae4325c56f1..bfbfc3eee581a3 100644 --- a/examples/lock-app/efr32/src/AppTask.cpp +++ b/examples/lock-app/efr32/src/AppTask.cpp @@ -100,7 +100,7 @@ CHIP_ERROR AppTask::StartAppTask() CHIP_ERROR AppTask::Init() { // Init ZCL Data Model - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lock-app/esp32/main/main.cpp b/examples/lock-app/esp32/main/main.cpp index b63f6542a3f076..15e00f649b623a 100644 --- a/examples/lock-app/esp32/main/main.cpp +++ b/examples/lock-app/esp32/main/main.cpp @@ -85,7 +85,7 @@ extern "C" void app_main() return; } - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lock-app/k32w/main/AppTask.cpp b/examples/lock-app/k32w/main/AppTask.cpp index e4fd52db3b2a01..38c570972ad70e 100644 --- a/examples/lock-app/k32w/main/AppTask.cpp +++ b/examples/lock-app/k32w/main/AppTask.cpp @@ -87,7 +87,7 @@ CHIP_ERROR AppTask::Init() CHIP_ERROR err = CHIP_NO_ERROR; // Init ZCL Data Model and start server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -528,7 +528,8 @@ void AppTask::BleHandler(void * aGenericEvent) { ConnectivityMgr().SetBLEAdvertisingEnabled(true); - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == + CHIP_NO_ERROR) { K32W_LOG("Started BLE Advertising!"); } diff --git a/examples/lock-app/mbed/main/AppTask.cpp b/examples/lock-app/mbed/main/AppTask.cpp index e47874bd41d71b..33a96bb4946768 100644 --- a/examples/lock-app/mbed/main/AppTask.cpp +++ b/examples/lock-app/mbed/main/AppTask.cpp @@ -120,7 +120,7 @@ int AppTask::Init() chip::DeviceLayer::ConnectivityMgrImpl().StartWiFiManagement(); // Init ZCL Data Model and start server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lock-app/nrfconnect/main/AppTask.cpp b/examples/lock-app/nrfconnect/main/AppTask.cpp index 7fd32d3a8c8934..b178d107b1d6a3 100644 --- a/examples/lock-app/nrfconnect/main/AppTask.cpp +++ b/examples/lock-app/nrfconnect/main/AppTask.cpp @@ -97,7 +97,7 @@ int AppTask::Init() BoltLockMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -352,7 +352,7 @@ void AppTask::StartThreadHandler(AppEvent * aEvent) if (aEvent->ButtonEvent.PinNo != THREAD_START_BUTTON) return; - if (chip::Server::GetServer().AddTestCommissioning() != CHIP_NO_ERROR) + if (chip::Server::GetInstance().AddTestCommissioning() != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); } @@ -386,7 +386,7 @@ void AppTask::StartBLEAdvertisementHandler(AppEvent * aEvent) return; } - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) { LOG_ERR("OpenBasicCommissioningWindow() failed"); } diff --git a/examples/lock-app/p6/src/AppTask.cpp b/examples/lock-app/p6/src/AppTask.cpp index 0f8ceb9b131cba..746e3d4ae71210 100644 --- a/examples/lock-app/p6/src/AppTask.cpp +++ b/examples/lock-app/p6/src/AppTask.cpp @@ -102,7 +102,7 @@ CHIP_ERROR AppTask::Init() }, 0); // Init ZCL Data Model - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/lock-app/qpg/src/AppTask.cpp b/examples/lock-app/qpg/src/AppTask.cpp index 38796fbaf7bb9b..96451ea8023128 100644 --- a/examples/lock-app/qpg/src/AppTask.cpp +++ b/examples/lock-app/qpg/src/AppTask.cpp @@ -103,7 +103,7 @@ CHIP_ERROR AppTask::Init() qvCHIP_LedSet(LOCK_STATE_LED, !BoltLockMgr().IsUnlocked()); // Init ZCL Data Model - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -350,7 +350,8 @@ void AppTask::FunctionHandler(AppEvent * aEvent) if (!ConnectivityMgr().IsThreadProvisioned()) { // Enable BLE advertisements and pairing window - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == + CHIP_NO_ERROR) { ChipLogProgress(NotSpecified, "BLE advertising started. Waiting for Pairing."); } diff --git a/examples/ota-provider-app/linux/main.cpp b/examples/ota-provider-app/linux/main.cpp index 7bd4907ea42b35..79f002cd11fbc6 100644 --- a/examples/ota-provider-app/linux/main.cpp +++ b/examples/ota-provider-app/linux/main.cpp @@ -121,7 +121,7 @@ int main(int argc, char * argv[]) } chip::DeviceLayer::ConfigurationMgr().LogDeviceConfig(); - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); exchangeMgr = chip::ExchangeManager(); err = exchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(chip::Protocols::BDX::Id, &bdxServer); diff --git a/examples/platform/linux/AppMain.cpp b/examples/platform/linux/AppMain.cpp index 5fc27d44267833..8b8ce6ff9e6cba 100644 --- a/examples/platform/linux/AppMain.cpp +++ b/examples/platform/linux/AppMain.cpp @@ -275,7 +275,7 @@ void ChipLinuxAppMainLoop() #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE // Init ZCL Data Model and CHIP App Server - chip::Server::GetServer().Init(nullptr, securePort, unsecurePort); + chip::Server::GetInstance().Init(nullptr, securePort, unsecurePort); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/platform/linux/CommissioneeShellCommands.cpp b/examples/platform/linux/CommissioneeShellCommands.cpp index 7c057ce94b18ae..24bb09856ffe66 100644 --- a/examples/platform/linux/CommissioneeShellCommands.cpp +++ b/examples/platform/linux/CommissioneeShellCommands.cpp @@ -46,7 +46,7 @@ static CHIP_ERROR SendUDC(bool printHeader, chip::Transport::PeerAddress commiss streamer_printf(sout, "SendUDC: "); } - Server::GetServer().SendUserDirectedCommissioningRequest(commissioner); + Server::GetInstance().SendUserDirectedCommissioningRequest(commissioner); streamer_printf(sout, "done\r\n"); diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp index 82fee5ff063eb6..dc98dac5b73ccc 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -146,7 +146,7 @@ int AppTask::Init() // Init ZCL Data Model and start server PLAT_LOG("Initialize Server"); - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -335,7 +335,8 @@ void AppTask::DispatchEvent(AppEvent * aEvent) // Enable BLE advertisements if (!ConnectivityMgr().IsBLEAdvertisingEnabled()) { - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == + CHIP_NO_ERROR) { PLAT_LOG("Enabled BLE Advertisement"); } diff --git a/examples/pump-app/nrfconnect/main/AppTask.cpp b/examples/pump-app/nrfconnect/main/AppTask.cpp index 2062acededb451..5fceff922cbc29 100644 --- a/examples/pump-app/nrfconnect/main/AppTask.cpp +++ b/examples/pump-app/nrfconnect/main/AppTask.cpp @@ -97,7 +97,7 @@ int AppTask::Init() PumpMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -352,7 +352,7 @@ void AppTask::StartThreadHandler(AppEvent * aEvent) if (aEvent->ButtonEvent.PinNo != THREAD_START_BUTTON) return; - if (chip::Server::GetServer().AddTestCommissioning() != CHIP_NO_ERROR) + if (chip::Server::GetInstance().AddTestCommissioning() != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); } @@ -386,7 +386,7 @@ void AppTask::StartBLEAdvertisementHandler(AppEvent * aEvent) return; } - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) { LOG_ERR("OpenBasicCommissioningWindow() failed"); } diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp index 78d34e4230fd91..f575e9a371581c 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -146,7 +146,7 @@ int AppTask::Init() // Init ZCL Data Model and start server PLAT_LOG("Initialize Server"); - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -335,7 +335,8 @@ void AppTask::DispatchEvent(AppEvent * aEvent) // Enable BLE advertisements if (!ConnectivityMgr().IsBLEAdvertisingEnabled()) { - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) == + CHIP_NO_ERROR) { PLAT_LOG("Enabled BLE Advertisement"); } diff --git a/examples/pump-controller-app/nrfconnect/main/AppTask.cpp b/examples/pump-controller-app/nrfconnect/main/AppTask.cpp index 2062acededb451..5fceff922cbc29 100644 --- a/examples/pump-controller-app/nrfconnect/main/AppTask.cpp +++ b/examples/pump-controller-app/nrfconnect/main/AppTask.cpp @@ -97,7 +97,7 @@ int AppTask::Init() PumpMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Init ZCL Data Model and start server - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -352,7 +352,7 @@ void AppTask::StartThreadHandler(AppEvent * aEvent) if (aEvent->ButtonEvent.PinNo != THREAD_START_BUTTON) return; - if (chip::Server::GetServer().AddTestCommissioning() != CHIP_NO_ERROR) + if (chip::Server::GetInstance().AddTestCommissioning() != CHIP_NO_ERROR) { LOG_ERR("Failed to add test pairing"); } @@ -386,7 +386,7 @@ void AppTask::StartBLEAdvertisementHandler(AppEvent * aEvent) return; } - if (chip::Server::GetServer().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) + if (chip::Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(chip::ResetFabrics::kNo) != CHIP_NO_ERROR) { LOG_ERR("OpenBasicCommissioningWindow() failed"); } diff --git a/examples/temperature-measurement-app/esp32/main/main.cpp b/examples/temperature-measurement-app/esp32/main/main.cpp index 8726c712701f57..df3072eac0cab0 100644 --- a/examples/temperature-measurement-app/esp32/main/main.cpp +++ b/examples/temperature-measurement-app/esp32/main/main.cpp @@ -80,7 +80,7 @@ extern "C" void app_main() return; } - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/examples/tv-casting-app/linux/main.cpp b/examples/tv-casting-app/linux/main.cpp index be006537728c9f..6a442ca5479262 100644 --- a/examples/tv-casting-app/linux/main.cpp +++ b/examples/tv-casting-app/linux/main.cpp @@ -42,8 +42,9 @@ chip::System::SocketWatchToken token; void PrepareForCommissioning(const Mdns::DiscoveredNodeData * selectedCommissioner = nullptr) { // Enter commissioning mode, open commissioning window - Server::GetServer().Init(); - ReturnOnFailure(Server::GetServer().OpenBasicCommissioningWindow(ResetFabrics::kYes, commissioningWindowTimeoutInSec)); + Server::GetInstance().Init(); + ReturnOnFailure(Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(ResetFabrics::kYes, + commissioningWindowTimeoutInSec)); // Display onboarding payload chip::DeviceLayer::ConfigurationMgr().LogDeviceConfig(); diff --git a/examples/window-app/common/src/WindowApp.cpp b/examples/window-app/common/src/WindowApp.cpp index abca6e309c7708..afe6c5b48c0148 100644 --- a/examples/window-app/common/src/WindowApp.cpp +++ b/examples/window-app/common/src/WindowApp.cpp @@ -69,7 +69,7 @@ WindowApp::Cover * WindowApp::GetCover(chip::EndpointId endpoint) CHIP_ERROR WindowApp::Init() { // Init ZCL Data Model - chip::Server::GetServer().Init(); + chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp b/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp index ff9aade50d4620..d00de79d158dfc 100644 --- a/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp +++ b/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp @@ -43,7 +43,7 @@ bool emberAfAdministratorCommissioningClusterOpenCommissioningWindowCallback(End ChipLogProgress(Zcl, "Received command to open commissioning window"); - VerifyOrExit(!Server::GetServer().IsPairingWindowOpen(), status = EMBER_ZCL_STATUS_FAILURE); + VerifyOrExit(!Server::GetInstance().GetCommissionManager().IsPairingWindowOpen(), status = EMBER_ZCL_STATUS_FAILURE); VerifyOrExit(sizeof(verifier) == pakeVerifier.size(), status = EMBER_ZCL_STATUS_FAILURE); VerifyOrExit(iterations >= kPBKDFMinimumIterations, status = EMBER_ZCL_STATUS_FAILURE); VerifyOrExit(iterations <= kPBKDFMaximumIterations, status = EMBER_ZCL_STATUS_FAILURE); @@ -55,8 +55,8 @@ bool emberAfAdministratorCommissioningClusterOpenCommissioningWindowCallback(End memcpy(verifier.mW0, &verifierData[0], kSpake2p_WS_Length); memcpy(verifier.mL, &verifierData[kSpake2p_WS_Length], kSpake2p_WS_Length); - VerifyOrExit(Server::GetServer().OpenEnhancedCommissioningWindow(commissioningTimeout, discriminator, verifier, iterations, - salt, passcodeID) == CHIP_NO_ERROR, + VerifyOrExit(Server::GetInstance().GetCommissionManager().OpenEnhancedCommissioningWindow( + commissioningTimeout, discriminator, verifier, iterations, salt, passcodeID) == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); ChipLogProgress(Zcl, "Commissioning window is now open"); @@ -75,9 +75,10 @@ bool emberAfAdministratorCommissioningClusterOpenBasicCommissioningWindowCallbac { EmberAfStatus status = EMBER_ZCL_STATUS_SUCCESS; ChipLogProgress(Zcl, "Received command to open basic commissioning window"); - VerifyOrExit(!Server::GetServer().IsPairingWindowOpen(), status = EMBER_ZCL_STATUS_FAILURE); + VerifyOrExit(!Server::GetInstance().GetCommissionManager().IsPairingWindowOpen(), status = EMBER_ZCL_STATUS_FAILURE); VerifyOrExit(commissioningTimeout <= kMaxCommissionioningTimeoutSeconds, status = EMBER_ZCL_STATUS_FAILURE); - VerifyOrExit(Server::GetServer().OpenBasicCommissioningWindow(ResetFabrics::kNo, commissioningTimeout) == CHIP_NO_ERROR, + VerifyOrExit(Server::GetInstance().GetCommissionManager().OpenBasicCommissioningWindow(ResetFabrics::kNo, + commissioningTimeout) == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); ChipLogProgress(Zcl, "Commissioning window is now open"); @@ -93,7 +94,7 @@ bool emberAfAdministratorCommissioningClusterOpenBasicCommissioningWindowCallbac bool emberAfAdministratorCommissioningClusterRevokeCommissioningCallback(EndpointId endpoint, app::CommandHandler * commandObj) { ChipLogProgress(Zcl, "Received command to close commissioning window"); - Server::GetServer().ClosePairingWindow(); + Server::GetInstance().GetCommissionManager().CloseCommissioningWindow(); ChipLogProgress(Zcl, "Commissioning window is now closed"); emberAfSendImmediateDefaultResponse(EMBER_ZCL_STATUS_SUCCESS); return true; diff --git a/src/app/clusters/operational-credentials-server/operational-credentials-server.cpp b/src/app/clusters/operational-credentials-server/operational-credentials-server.cpp index be6e8a7e43daa6..d61676e531a728 100644 --- a/src/app/clusters/operational-credentials-server/operational-credentials-server.cpp +++ b/src/app/clusters/operational-credentials-server/operational-credentials-server.cpp @@ -121,7 +121,7 @@ CHIP_ERROR writeFabricsIntoFabricsListAttribute() // Loop through fabrics uint8_t fabricIndex = 0; - for (auto & fabricInfo : Server::GetServer().GetFabricTable()) + for (auto & fabricInfo : Server::GetInstance().GetFabricTable()) { NodeId nodeId = fabricInfo.GetPeerId().GetNodeId(); uint64_t fabricId = fabricInfo.GetFabricId(); @@ -187,7 +187,7 @@ static FabricInfo * retrieveCurrentFabric() FabricIndex index = emberAfCurrentCommand()->source->GetSecureSession().GetFabricIndex(); emberAfPrintln(EMBER_AF_PRINT_DEBUG, "OpCreds: Finding fabric with fabricIndex %d", index); - return Server::GetServer().GetFabricTable().FindFabricWithIndex(index); + return Server::GetInstance().GetFabricTable().FindFabricWithIndex(index); } // TODO: The code currently has two sources of truths for fabrics, the fabricInfo table + the attributes. There should only be one, @@ -234,7 +234,7 @@ OpCredsFabricTableDelegate gFabricDelegate; void emberAfPluginOperationalCredentialsServerInitCallback(void) { emberAfPrintln(EMBER_AF_PRINT_DEBUG, "OpCreds: Initiating OpCreds cluster by writing fabrics list from fabric table."); - Server::GetServer().GetFabricTable().SetFabricDelegate(&gFabricDelegate); + Server::GetInstance().GetFabricTable().SetFabricDelegate(&gFabricDelegate); writeFabricsIntoFabricsListAttribute(); } @@ -244,7 +244,7 @@ bool emberAfOperationalCredentialsClusterRemoveFabricCallback(EndpointId endpoin emberAfPrintln(EMBER_AF_PRINT_DEBUG, "OpCreds: RemoveFabric"); // TODO: Generate emberAfFabricClusterPrintln EmberAfStatus status = EMBER_ZCL_STATUS_SUCCESS; - CHIP_ERROR err = Server::GetServer().GetFabricTable().Delete(fabricIndex); + CHIP_ERROR err = Server::GetInstance().GetFabricTable().Delete(fabricIndex); VerifyOrExit(err == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); exit: @@ -270,7 +270,7 @@ bool emberAfOperationalCredentialsClusterUpdateFabricLabelCallback(EndpointId en VerifyOrExit(err == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); // Persist updated fabric - err = Server::GetServer().GetFabricTable().Store(fabric->GetFabricIndex()); + err = Server::GetInstance().GetFabricTable().Store(fabric->GetFabricIndex()); VerifyOrExit(err == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE); exit: @@ -359,10 +359,10 @@ bool emberAfOperationalCredentialsClusterAddNOCCallback(EndpointId endpoint, app gFabricBeingCommissioned.SetVendorId(adminVendorId); - err = Server::GetServer().GetFabricTable().AddNewFabric(gFabricBeingCommissioned, &fabricIndex); + err = Server::GetInstance().GetFabricTable().AddNewFabric(gFabricBeingCommissioned, &fabricIndex); VerifyOrExit(err == CHIP_NO_ERROR, nocResponse = ConvertToNOCResponseStatus(err)); - err = Server::GetServer().GetFabricTable().Store(fabricIndex); + err = Server::GetInstance().GetFabricTable().Store(fabricIndex); VerifyOrExit(err == CHIP_NO_ERROR, nocResponse = ConvertToNOCResponseStatus(err)); // We might have a new operational identity, so we should start advertising it right away. diff --git a/src/app/server/BUILD.gn b/src/app/server/BUILD.gn index 2d5c3fa6dfde66..508f3a703a4d30 100644 --- a/src/app/server/BUILD.gn +++ b/src/app/server/BUILD.gn @@ -27,6 +27,8 @@ static_library("server") { output_name = "libCHIPAppServer" sources = [ + "CommissionManager.cpp", + "CommissionManager.h", "EchoHandler.cpp", "EchoHandler.h", "Mdns.cpp", diff --git a/src/app/server/CommissionManager.cpp b/src/app/server/CommissionManager.cpp new file mode 100644 index 00000000000000..effb99fc6a64f4 --- /dev/null +++ b/src/app/server/CommissionManager.cpp @@ -0,0 +1,174 @@ +/* + * + * 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 +#include +#include + +namespace { + +void HandleCommissioningWindowTimeout(chip::System::Layer * aSystemLayer, void * aAppState) +{ + chip::CommissionManager * commissionMgr = static_cast(aAppState); + commissionMgr->CloseCommissioningWindow(); +} + +} // namespace + +namespace chip { + +CHIP_ERROR CommissionManager::OpenBasicCommissioningWindow(ResetFabrics resetFabrics, uint16_t commissioningTimeoutSeconds, + CommissioningWindowAdvertisement advertisementMode) +{ + // TODO(cecille): If this is re-called when the window is already open, what should happen? + RestoreDiscriminator(); + + uint32_t pinCode; + ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSetupPinCode(pinCode)); + + RendezvousParameters params; + + params.SetSetupPINCode(pinCode); +#if CONFIG_NETWORK_LAYER_BLE + SetBLE(advertisementMode == chip::CommissioningWindowAdvertisement::kBle); + params.SetAdvertisementDelegate(this); + if (advertisementMode == chip::CommissioningWindowAdvertisement::kBle) + { + params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); + } +#endif // CONFIG_NETWORK_LAYER_BLE + + if (resetFabrics == ResetFabrics::kYes) + { + mServer->GetFabricTable().DeleteAllFabrics(); + // Only resetting gNextAvailableFabricIndex at reboot otherwise previously paired device with fabricID 0 + // can continue sending messages to accessory as next available fabric will also be 0. + // This logic is not up to spec, will be implemented up to spec once AddOptCert is implemented. + mServer->GetFabricTable().Reset(); + } + + ReturnErrorOnFailure(mServer->GetRendezvousServer().WaitForPairing( + std::move(params), kSpake2p_Iteration_Count, + ByteSpan(reinterpret_cast(kSpake2pKeyExchangeSalt), strlen(kSpake2pKeyExchangeSalt)), 0, + &mServer->GetExchangManager(), &mServer->GetTransportManager(), &mServer->GetSecureSessionManager())); + + if (commissioningTimeoutSeconds != kNoCommissioningTimeout) + { + ReturnErrorOnFailure( + DeviceLayer::SystemLayer.StartTimer(commissioningTimeoutSeconds * 1000, HandleCommissioningWindowTimeout, this)); + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR CommissionManager::OpenEnhancedCommissioningWindow(uint16_t commissioningTimeoutSeconds, uint16_t discriminator, + PASEVerifier & verifier, uint32_t iterations, ByteSpan salt, + uint16_t passcodeID) +{ + RendezvousParameters params; + + ReturnErrorOnFailure(SetTemporaryDiscriminator(discriminator)); + + SetBLE(false); +#if CONFIG_NETWORK_LAYER_BLE + SetBLE(true); + params.SetAdvertisementDelegate(this); + params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); +#endif + + params.SetPASEVerifier(verifier).SetAdvertisementDelegate(this); + + ReturnErrorOnFailure(mServer->GetRendezvousServer().WaitForPairing( + std::move(params), iterations, salt, passcodeID, &mServer->GetExchangManager(), &mServer->GetTransportManager(), + &mServer->GetSecureSessionManager())); + + if (commissioningTimeoutSeconds != kNoCommissioningTimeout) + { + ReturnErrorOnFailure( + DeviceLayer::SystemLayer.StartTimer(commissioningTimeoutSeconds * 1000, HandleCommissioningWindowTimeout, this)); + } + + return CHIP_NO_ERROR; +} + +void CommissionManager::CloseCommissioningWindow() +{ + if (mCommissioningWindowOpen) + { + ChipLogProgress(AppServer, "Closing pairing window"); + mServer->GetRendezvousServer().Cleanup(); + } +} + +CHIP_ERROR CommissionManager::StartAdvertisement() +{ + if (mIsBLE) + { + ReturnErrorOnFailure(chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true)); + } + if (mAppDelegate != nullptr) + { + mAppDelegate->OnPairingWindowOpened(); + } + mCommissioningWindowOpen = true; + return CHIP_NO_ERROR; +} + +CHIP_ERROR CommissionManager::StopAdvertisement() +{ + RestoreDiscriminator(); + + mCommissioningWindowOpen = false; + + if (mIsBLE) + { + ReturnErrorOnFailure(chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false)); + } + + if (mAppDelegate != nullptr) + { + mAppDelegate->OnPairingWindowClosed(); + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR CommissionManager::SetTemporaryDiscriminator(uint16_t discriminator) +{ + if (!mOriginalDiscriminatorCached) + { + // Cache the original discriminator + ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSetupDiscriminator(mOriginalDiscriminator)); + mOriginalDiscriminatorCached = true; + } + + return DeviceLayer::ConfigurationMgr().StoreSetupDiscriminator(discriminator); +} + +CHIP_ERROR CommissionManager::RestoreDiscriminator() +{ + if (mOriginalDiscriminatorCached) + { + // Restore the original discriminator + ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().StoreSetupDiscriminator(mOriginalDiscriminator)); + mOriginalDiscriminatorCached = false; + } + + return CHIP_NO_ERROR; +} + +} // namespace chip diff --git a/src/app/server/CommissionManager.h b/src/app/server/CommissionManager.h new file mode 100644 index 00000000000000..288dd0d2cb02da --- /dev/null +++ b/src/app/server/CommissionManager.h @@ -0,0 +1,84 @@ +/* + * + * 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. + */ + +#pragma once + +#include +#include + +namespace chip { + +enum class ResetFabrics +{ + kYes, + kNo, +}; + +constexpr uint16_t kNoCommissioningTimeout = UINT16_MAX; + +enum class CommissioningWindowAdvertisement +{ + kBle, + kMdns, +}; + +class Server; + +class CommissionManager : public RendezvousAdvertisementDelegate +{ +public: + CommissionManager(Server * server) : mAppDelegate(nullptr), mServer(server) {} + + void SetAppDelegate(AppDelegate * delegate) { mAppDelegate = delegate; } + + void SetBLE(bool ble) { mIsBLE = ble; } + + /** + * Open the pairing window using default configured parameters. + */ + CHIP_ERROR + OpenBasicCommissioningWindow(ResetFabrics resetFabrics, uint16_t commissioningTimeoutSeconds = kNoCommissioningTimeout, + CommissioningWindowAdvertisement advertisementMode = chip::CommissioningWindowAdvertisement::kBle); + + CHIP_ERROR OpenEnhancedCommissioningWindow(uint16_t commissioningTimeoutSeconds, uint16_t discriminator, + PASEVerifier & verifier, uint32_t iterations, chip::ByteSpan salt, + uint16_t passcodeID); + + void CloseCommissioningWindow(); + + bool IsPairingWindowOpen() { return mCommissioningWindowOpen; } + + CHIP_ERROR StartAdvertisement() override; + + CHIP_ERROR StopAdvertisement() override; + +private: + CHIP_ERROR SetTemporaryDiscriminator(uint16_t discriminator); + + CHIP_ERROR RestoreDiscriminator(); + + AppDelegate * mAppDelegate = nullptr; + Server * mServer = nullptr; + + bool mCommissioningWindowOpen = false; + bool mIsBLE = true; + + bool mOriginalDiscriminatorCached = false; + uint16_t mOriginalDiscriminator = 0; +}; + +} // namespace chip diff --git a/src/app/server/Mdns.cpp b/src/app/server/Mdns.cpp index 854568eb2f45ad..92d03782307a2e 100644 --- a/src/app/server/Mdns.cpp +++ b/src/app/server/Mdns.cpp @@ -42,7 +42,7 @@ namespace { bool HaveOperationalCredentials() { // Look for any fabric info that has a useful operational identity. - for (const Transport::FabricInfo & fabricInfo : Server::GetServer().GetFabricTable()) + for (const Transport::FabricInfo & fabricInfo : Server::GetInstance().GetFabricTable()) { if (fabricInfo.IsInitialized()) { @@ -110,7 +110,7 @@ CHIP_ERROR GetCommissionableInstanceName(char * buffer, size_t bufferLen) /// Set MDNS operational advertisement CHIP_ERROR AdvertiseOperational() { - for (const Transport::FabricInfo & fabricInfo : Server::GetServer().GetFabricTable()) + for (const Transport::FabricInfo & fabricInfo : Server::GetInstance().GetFabricTable()) { if (fabricInfo.IsInitialized()) { diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index 06bf359eb7249b..2fd635cce3d4b0 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -15,6 +15,7 @@ * limitations under the License. */ +#include "core/CHIPError.h" #include #include @@ -65,12 +66,6 @@ constexpr bool isRendezvousBypassed() #endif } -void HandlePairingWindowTimeout(chip::System::Layer * aSystemLayer, void * aAppState) -{ - chip::Server * server = static_cast(aAppState); - server->ClosePairingWindow(); -} - } // namespace namespace chip { @@ -79,7 +74,7 @@ Server Server::sServer; CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint16_t unsecureServicePort) { - mAppDelgate = delegate; + mAppDelegate = delegate; mSecuredServicePort = secureServicePort; mUnsecuredServicePort = unsecureServicePort; @@ -87,6 +82,7 @@ CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint chip::Platform::MemoryInit(); + mCommissionManager.SetAppDelegate(delegate); InitDataModelHandler(&mExchangeMgr); #if CHIP_DEVICE_LAYER_TARGET_DARWIN @@ -96,10 +92,10 @@ CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint DeviceLayer::PersistedStorage::KeyValueStoreMgrImpl().Init(CHIP_CONFIG_KVS_PATH); #endif - err = mRendezvousServer.Init(mAppDelgate, &mSessionIDAllocator); + err = mRendezvousServer.Init(mAppDelegate, &mSessionIDAllocator); SuccessOrExit(err); - err = mFabrics.Init(this); + err = mFabrics.Init(&mServerStorage); SuccessOrExit(err); // Init transport before operations with secure session mgr. @@ -151,7 +147,7 @@ CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint else { #if CHIP_DEVICE_CONFIG_ENABLE_PAIRING_AUTOSTART - SuccessOrExit(err = OpenBasicCommissioningWindow(ResetFabrics::kYes)); + SuccessOrExit(err = mCommissionManager.OpenBasicCommissioningWindow(ResetFabrics::kYes)); #endif } @@ -159,16 +155,20 @@ CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint app::Mdns::SetSecuredPort(mSecuredServicePort); app::Mdns::SetUnsecuredPort(mUnsecuredServicePort); #endif // CHIP_DEVICE_CONFIG_ENABLE_MDNS -// ESP32 and Mbed OS examples have a custom logic for enabling DNS-SD + + // TODO @bzbarsky-apple @cecille Move to examples + // ESP32 and Mbed OS examples have a custom logic for enabling DNS-SD #if CHIP_DEVICE_CONFIG_ENABLE_MDNS && !CHIP_DEVICE_LAYER_TARGET_ESP32 && !CHIP_DEVICE_LAYER_TARGET_MBED // StartServer only enables commissioning mode if device has not been commissioned app::Mdns::StartServer(); #endif + // TODO @pan-apple Use IM protocol ID. // Register to receive unsolicited legacy ZCL messages from the exchange manager. err = mExchangeMgr.RegisterUnsolicitedMessageHandlerForProtocol(Protocols::TempZCL::Id, this); SuccessOrExit(err); + // TODO @pan-apple Remove service provisioniong, maybe multi-admin? // Register to receive unsolicited Service Provisioning messages from the exchange manager. err = mExchangeMgr.RegisterUnsolicitedMessageHandlerForProtocol(Protocols::ServiceProvisioning::Id, this); SuccessOrExit(err); @@ -227,92 +227,6 @@ CHIP_ERROR Server::SendUserDirectedCommissioningRequest(chip::Transport::PeerAdd } #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT -CHIP_ERROR Server::OpenBasicCommissioningWindow(ResetFabrics resetFabrics, uint16_t commissioningTimeoutSeconds, - PairingWindowAdvertisement advertisementMode) -{ - // TODO(cecille): If this is re-called when the window is already open, what should happen? - mDeviceDiscriminatorCache.RestoreDiscriminator(); - - uint32_t pinCode; - ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSetupPinCode(pinCode)); - - RendezvousParameters params; - - params.SetSetupPINCode(pinCode); - SetBLE(false); -#if CONFIG_NETWORK_LAYER_BLE - SetBLE(advertisementMode == chip::PairingWindowAdvertisement::kBle); - params.SetAdvertisementDelegate(this); - if (advertisementMode == chip::PairingWindowAdvertisement::kBle) - { - params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); - } -#endif // CONFIG_NETWORK_LAYER_BLE - - if (resetFabrics == ResetFabrics::kYes) - { - mFabrics.DeleteAllFabrics(); - // Only resetting gNextAvailableFabricIndex at reboot otherwise previously paired device with fabricID 0 - // can continue sending messages to accessory as next available fabric will also be 0. - // This logic is not up to spec, will be implemented up to spec once AddOptCert is implemented. - mFabrics.Reset(); - } - - ReturnErrorOnFailure(mRendezvousServer.WaitForPairing( - std::move(params), kSpake2p_Iteration_Count, - ByteSpan(reinterpret_cast(kSpake2pKeyExchangeSalt), strlen(kSpake2pKeyExchangeSalt)), 0, &mExchangeMgr, - &mTransports, &mSessions)); - - if (commissioningTimeoutSeconds != kNoCommissioningTimeout) - { - ReturnErrorOnFailure( - DeviceLayer::SystemLayer.StartTimer(commissioningTimeoutSeconds * 1000, HandlePairingWindowTimeout, this)); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Server::OpenEnhancedCommissioningWindow(uint16_t commissioningTimeoutSeconds, uint16_t discriminator, - PASEVerifier & verifier, uint32_t iterations, ByteSpan salt, uint16_t passcodeID) -{ - RendezvousParameters params; - - ReturnErrorOnFailure(mDeviceDiscriminatorCache.UpdateDiscriminator(discriminator)); - - SetBLE(false); -#if CONFIG_NETWORK_LAYER_BLE - SetBLE(true); - params.SetAdvertisementDelegate(this); - params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); -#endif - params.SetPASEVerifier(verifier).SetAdvertisementDelegate(this); - - ReturnErrorOnFailure( - mRendezvousServer.WaitForPairing(std::move(params), iterations, salt, passcodeID, &mExchangeMgr, &mTransports, &mSessions)); - - if (commissioningTimeoutSeconds != kNoCommissioningTimeout) - { - ReturnErrorOnFailure( - DeviceLayer::SystemLayer.StartTimer(commissioningTimeoutSeconds * 1000, HandlePairingWindowTimeout, this)); - } - - return CHIP_NO_ERROR; -} - -void Server::ClosePairingWindow() -{ - if (mPairingWindowOpen) - { - ChipLogProgress(AppServer, "Closing pairing window"); - mRendezvousServer.Cleanup(); - } -} - -bool Server::IsPairingWindowOpen() -{ - return mPairingWindowOpen; -} - CHIP_ERROR Server::AddTestCommissioning() { CHIP_ERROR err = CHIP_NO_ERROR; @@ -340,75 +254,23 @@ CHIP_ERROR Server::AddTestCommissioning() return err; } -CHIP_ERROR Server::SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) -{ - ChipLogDetail(AppServer, "Retrieved value from server storage."); - return KeyValueStoreMgr().Get(key, buffer, size); -} - -CHIP_ERROR Server::SyncSetKeyValue(const char * key, const void * value, uint16_t size) -{ - ChipLogDetail(AppServer, "Stored value in server storage"); - return KeyValueStoreMgr().Put(key, value, size); -} - -CHIP_ERROR Server::SyncDeleteKeyValue(const char * key) -{ - ChipLogDetail(AppServer, "Delete value in server storage"); - return KeyValueStoreMgr().Delete(key); -} - -CHIP_ERROR Server::StartAdvertisement() -{ - if (mIsBLE) - { - ReturnErrorOnFailure(chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true)); - } - if (mAppDelgate != nullptr) - { - mAppDelgate->OnPairingWindowOpened(); - } - mPairingWindowOpen = true; - return CHIP_NO_ERROR; -} - -CHIP_ERROR Server::StopAdvertisement() -{ - mDeviceDiscriminatorCache.RestoreDiscriminator(); - - mPairingWindowOpen = false; - - if (mIsBLE) - { - ReturnErrorOnFailure(chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(false)); - } - - if (mAppDelgate != nullptr) - { - mAppDelgate->OnPairingWindowClosed(); - } - - return CHIP_NO_ERROR; -} - CHIP_ERROR Server::OnMessageReceived(Messaging::ExchangeContext * exchangeContext, const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, System::PacketBufferHandle && buffer) { CHIP_ERROR err = CHIP_NO_ERROR; - // as soon as a client connects, assume it is connected - VerifyOrExit(!buffer.IsNull(), ChipLogError(AppServer, "Received data but couldn't process it...")); + VerifyOrReturnError(!buffer.IsNull(), err = CHIP_ERROR_INVALID_ARGUMENT); + // TODO: BDX messages will also be possible in the future. HandleDataModelMessage(exchangeContext, std::move(buffer)); -exit: return err; } void Server::OnResponseTimeout(Messaging::ExchangeContext * ec) { ChipLogProgress(AppServer, "Failed to receive response"); - if (mAppDelgate != nullptr) + if (mAppDelegate != nullptr) { - mAppDelgate->OnReceiveError(); + mAppDelegate->OnReceiveError(); } } diff --git a/src/app/server/Server.h b/src/app/server/Server.h index db0d358844d3b8..1046ba82c05551 100644 --- a/src/app/server/Server.h +++ b/src/app/server/Server.h @@ -17,15 +17,19 @@ #pragma once +#include "transport/TransportMgrBase.h" #include +#include #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -36,32 +40,18 @@ namespace chip { constexpr size_t kMaxBlePendingPackets = 1; -using DemoTransportMgr = chip::TransportMgr + , + chip::Transport::BLE #endif - >; + >; -enum class ResetFabrics -{ - kYes, - kNo, -}; - -enum class PairingWindowAdvertisement -{ - kBle, - kMdns, -}; - -constexpr uint16_t kNoCommissioningTimeout = UINT16_MAX; - -class Server : public RendezvousAdvertisementDelegate, public PersistentStorageDelegate, public Messaging::ExchangeDelegate +class Server : public Messaging::ExchangeDelegate { public: CHIP_ERROR Init(AppDelegate * delegate = nullptr, uint16_t secureServicePort = CHIP_PORT, @@ -71,25 +61,8 @@ class Server : public RendezvousAdvertisementDelegate, public PersistentStorageD CHIP_ERROR SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner); #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT - /** - * Open the pairing window using default configured parameters. - */ - CHIP_ERROR OpenBasicCommissioningWindow(ResetFabrics resetFabrics, - uint16_t commissioningTimeoutSeconds = kNoCommissioningTimeout, - PairingWindowAdvertisement advertisementMode = chip::PairingWindowAdvertisement::kBle); - - CHIP_ERROR OpenEnhancedCommissioningWindow(uint16_t commissioningTimeoutSeconds, uint16_t discriminator, - PASEVerifier & verifier, uint32_t iterations, chip::ByteSpan salt, - uint16_t passcodeID); - CHIP_ERROR AddTestCommissioning(); - void ClosePairingWindow(); - - bool IsPairingWindowOpen(); - - void SetBLE(bool ble) { mIsBLE = ble; } - void SetFabricIndex(FabricIndex id) { mFabricIndex = id; } Transport::FabricTable & GetFabricTable() { return mFabrics; } @@ -100,10 +73,16 @@ class Server : public RendezvousAdvertisementDelegate, public PersistentStorageD SecureSessionMgr & GetSecureSessionManager() { return mSessions; } - static Server & GetServer() { return sServer; } + RendezvousServer & GetRendezvousServer() { return mRendezvousServer; } + + TransportMgrBase & GetTransportManager() { return mTransports; } + + CommissionManager & GetCommissionManager() { return mCommissionManager; } + + static Server & GetInstance() { return sServer; } private: - Server() {} + Server() : mCommissionManager(this) {} static Server sServer; @@ -119,23 +98,35 @@ class Server : public RendezvousAdvertisementDelegate, public PersistentStorageD uint16_t mOriginalDiscriminator = 0; }; - /// PersistentStorageDelegate implementation - CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override; - CHIP_ERROR SyncSetKeyValue(const char * key, const void * value, uint16_t size) override; - CHIP_ERROR SyncDeleteKeyValue(const char * key) override; - - /// RendezvousAdvertisementDelegate implementation - CHIP_ERROR StartAdvertisement() override; - CHIP_ERROR StopAdvertisement() override; + class ServerStorageDelegate : public PersistentStorageDelegate + { + CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override + { + ChipLogProgress(AppServer, "Retrieved value from server storage."); + return DeviceLayer::PersistedStorage::KeyValueStoreMgr().Get(key, buffer, size); + } + + CHIP_ERROR SyncSetKeyValue(const char * key, const void * value, uint16_t size) override + { + ChipLogProgress(AppServer, "Stored value in server storage"); + return DeviceLayer::PersistedStorage::KeyValueStoreMgr().Put(key, value, size); + } + + CHIP_ERROR SyncDeleteKeyValue(const char * key) override + { + ChipLogProgress(AppServer, "Delete value in server storage"); + return DeviceLayer::PersistedStorage::KeyValueStoreMgr().Delete(key); + } + }; // Messaging::ExchangeDelegate CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * exchangeContext, const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, System::PacketBufferHandle && buffer) override; void OnResponseTimeout(Messaging::ExchangeContext * ec) override; - AppDelegate * mAppDelgate; + AppDelegate * mAppDelegate = nullptr; - DemoTransportMgr mTransports; + ServerTransportMgr mTransports; SecureSessionMgr mSessions; RendezvousServer mRendezvousServer; CASEServer mCASEServer; @@ -149,12 +140,13 @@ class Server : public RendezvousAdvertisementDelegate, public PersistentStorageD SecurePairingUsingTestSecret mTestPairing; DeviceDiscriminatorCache mDeviceDiscriminatorCache; + ServerStorageDelegate mServerStorage; + CommissionManager mCommissionManager; + // TODO @ceille: Maybe use OperationalServicePort and CommissionableServicePort uint16_t mSecuredServicePort; uint16_t mUnsecuredServicePort; - bool mPairingWindowOpen = false; FabricIndex mFabricIndex; - bool mIsBLE = true; }; } // namespace chip From 12a7cb7a0268a4dd4a48bbd72c77011091724fae Mon Sep 17 00:00:00 2001 From: Jiacheng Guo Date: Tue, 31 Aug 2021 11:34:06 +0800 Subject: [PATCH 3/8] fix build on zephyr --- examples/lighting-app/mbed/CMakeLists.txt | 1 + examples/lighting-app/nrfconnect/CMakeLists.txt | 1 + examples/lighting-app/telink/CMakeLists.txt | 1 + examples/lock-app/mbed/CMakeLists.txt | 1 + examples/lock-app/nrfconnect/CMakeLists.txt | 1 + examples/pump-app/nrfconnect/CMakeLists.txt | 1 + examples/pump-controller-app/nrfconnect/CMakeLists.txt | 1 + src/app/server/Server.cpp | 1 - src/app/server/Server.h | 3 +-- 9 files changed, 8 insertions(+), 3 deletions(-) diff --git a/examples/lighting-app/mbed/CMakeLists.txt b/examples/lighting-app/mbed/CMakeLists.txt index b1e213d986e63f..09b957bc817706 100644 --- a/examples/lighting-app/mbed/CMakeLists.txt +++ b/examples/lighting-app/mbed/CMakeLists.txt @@ -74,6 +74,7 @@ target_sources(${APP_TARGET} PRIVATE ${CHIP_ROOT}/src/app/server/OnboardingCodesUtil.cpp ${CHIP_ROOT}/src/app/server/RendezvousServer.cpp ${CHIP_ROOT}/src/app/server/Server.cpp + ${CHIP_ROOT}/src/app/server/CommissionManager.cpp ${CHIP_ROOT}/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp ${CHIP_ROOT}/src/app/clusters/basic/basic.cpp ${CHIP_ROOT}/src/app/clusters/bindings/bindings.cpp diff --git a/examples/lighting-app/nrfconnect/CMakeLists.txt b/examples/lighting-app/nrfconnect/CMakeLists.txt index 085aa62b850504..d9f311efc10e7d 100644 --- a/examples/lighting-app/nrfconnect/CMakeLists.txt +++ b/examples/lighting-app/nrfconnect/CMakeLists.txt @@ -94,6 +94,7 @@ target_sources(app PRIVATE ${CHIP_ROOT}/src/app/server/OnboardingCodesUtil.cpp ${CHIP_ROOT}/src/app/server/RendezvousServer.cpp ${CHIP_ROOT}/src/app/server/Server.cpp + ${CHIP_ROOT}/src/app/server/CommissionManager.cpp ${CHIP_ROOT}/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp ${CHIP_ROOT}/src/app/clusters/basic/basic.cpp ${CHIP_ROOT}/src/app/clusters/bindings/bindings.cpp diff --git a/examples/lighting-app/telink/CMakeLists.txt b/examples/lighting-app/telink/CMakeLists.txt index 435718cce09672..00a4502e868e2a 100644 --- a/examples/lighting-app/telink/CMakeLists.txt +++ b/examples/lighting-app/telink/CMakeLists.txt @@ -76,6 +76,7 @@ target_sources(app PRIVATE ${CHIP_ROOT}/src/app/server/OnboardingCodesUtil.cpp ${CHIP_ROOT}/src/app/server/RendezvousServer.cpp ${CHIP_ROOT}/src/app/server/Server.cpp + ${CHIP_ROOT}/src/app/server/CommissionManager.cpp ${CHIP_ROOT}/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp ${CHIP_ROOT}/src/app/clusters/basic/basic.cpp ${CHIP_ROOT}/src/app/clusters/bindings/bindings.cpp diff --git a/examples/lock-app/mbed/CMakeLists.txt b/examples/lock-app/mbed/CMakeLists.txt index 5400170fb73864..07f08335ac9658 100644 --- a/examples/lock-app/mbed/CMakeLists.txt +++ b/examples/lock-app/mbed/CMakeLists.txt @@ -73,6 +73,7 @@ target_sources(${APP_TARGET} PRIVATE ${CHIP_ROOT}/src/app/server/OnboardingCodesUtil.cpp ${CHIP_ROOT}/src/app/server/RendezvousServer.cpp ${CHIP_ROOT}/src/app/server/Server.cpp + ${CHIP_ROOT}/src/app/server/CommissionManager.cpp ${CHIP_ROOT}/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp ${CHIP_ROOT}/src/app/clusters/basic/basic.cpp ${CHIP_ROOT}/src/app/clusters/diagnostic-logs-server/diagnostic-logs-server.cpp diff --git a/examples/lock-app/nrfconnect/CMakeLists.txt b/examples/lock-app/nrfconnect/CMakeLists.txt index 3e3406e4e65af5..37f2d81233b37e 100644 --- a/examples/lock-app/nrfconnect/CMakeLists.txt +++ b/examples/lock-app/nrfconnect/CMakeLists.txt @@ -92,6 +92,7 @@ target_sources(app PRIVATE ${CHIP_ROOT}/src/app/server/OnboardingCodesUtil.cpp ${CHIP_ROOT}/src/app/server/RendezvousServer.cpp ${CHIP_ROOT}/src/app/server/Server.cpp + ${CHIP_ROOT}/src/app/server/CommissionManager.cpp ${CHIP_ROOT}/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp ${CHIP_ROOT}/src/app/clusters/basic/basic.cpp ${CHIP_ROOT}/src/app/clusters/bindings/bindings.cpp diff --git a/examples/pump-app/nrfconnect/CMakeLists.txt b/examples/pump-app/nrfconnect/CMakeLists.txt index f2e81074cdf1a5..11ccf3ea1cd0d7 100644 --- a/examples/pump-app/nrfconnect/CMakeLists.txt +++ b/examples/pump-app/nrfconnect/CMakeLists.txt @@ -92,6 +92,7 @@ target_sources(app PRIVATE ${CHIP_ROOT}/src/app/server/OnboardingCodesUtil.cpp ${CHIP_ROOT}/src/app/server/RendezvousServer.cpp ${CHIP_ROOT}/src/app/server/Server.cpp + ${CHIP_ROOT}/src/app/server/CommissionManager.cpp ${CHIP_ROOT}/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp ${CHIP_ROOT}/src/app/clusters/basic/basic.cpp ${CHIP_ROOT}/src/app/clusters/bindings/bindings.cpp diff --git a/examples/pump-controller-app/nrfconnect/CMakeLists.txt b/examples/pump-controller-app/nrfconnect/CMakeLists.txt index e0546b3e3f62da..8e34f835ec2030 100644 --- a/examples/pump-controller-app/nrfconnect/CMakeLists.txt +++ b/examples/pump-controller-app/nrfconnect/CMakeLists.txt @@ -92,6 +92,7 @@ target_sources(app PRIVATE ${CHIP_ROOT}/src/app/server/OnboardingCodesUtil.cpp ${CHIP_ROOT}/src/app/server/RendezvousServer.cpp ${CHIP_ROOT}/src/app/server/Server.cpp + ${CHIP_ROOT}/src/app/server/CommissionManager.cpp ${CHIP_ROOT}/src/app/clusters/administrator-commissioning-server/administrator-commissioning-server.cpp ${CHIP_ROOT}/src/app/clusters/basic/basic.cpp ${CHIP_ROOT}/src/app/clusters/bindings/bindings.cpp diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index 2fd635cce3d4b0..e18b85b42d54ae 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -15,7 +15,6 @@ * limitations under the License. */ -#include "core/CHIPError.h" #include #include diff --git a/src/app/server/Server.h b/src/app/server/Server.h index 1046ba82c05551..f472756890717d 100644 --- a/src/app/server/Server.h +++ b/src/app/server/Server.h @@ -17,7 +17,6 @@ #pragma once -#include "transport/TransportMgrBase.h" #include #include #include @@ -29,10 +28,10 @@ #include #include #include -#include #include #include #include +#include #include #include From 9589f519cbbcde8c18722fbee9dd236bf52aa706 Mon Sep 17 00:00:00 2001 From: Jiacheng Guo Date: Thu, 9 Sep 2021 14:51:00 +0800 Subject: [PATCH 4/8] add unit test --- src/app/server/CommissionManager.cpp | 4 +- src/app/server/Server.cpp | 24 ----- src/app/server/Server.h | 13 --- src/app/tests/BUILD.gn | 2 + src/app/tests/TestCommissionManager.cpp | 136 ++++++++++++++++++++++++ 5 files changed, 140 insertions(+), 39 deletions(-) create mode 100644 src/app/tests/TestCommissionManager.cpp diff --git a/src/app/server/CommissionManager.cpp b/src/app/server/CommissionManager.cpp index effb99fc6a64f4..72da9fdc73e4e4 100644 --- a/src/app/server/CommissionManager.cpp +++ b/src/app/server/CommissionManager.cpp @@ -43,9 +43,9 @@ CHIP_ERROR CommissionManager::OpenBasicCommissioningWindow(ResetFabrics resetFab RendezvousParameters params; params.SetSetupPINCode(pinCode); + params.SetAdvertisementDelegate(this); #if CONFIG_NETWORK_LAYER_BLE SetBLE(advertisementMode == chip::CommissioningWindowAdvertisement::kBle); - params.SetAdvertisementDelegate(this); if (advertisementMode == chip::CommissioningWindowAdvertisement::kBle) { params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); @@ -84,9 +84,9 @@ CHIP_ERROR CommissionManager::OpenEnhancedCommissioningWindow(uint16_t commissio ReturnErrorOnFailure(SetTemporaryDiscriminator(discriminator)); SetBLE(false); + params.SetAdvertisementDelegate(this); #if CONFIG_NETWORK_LAYER_BLE SetBLE(true); - params.SetAdvertisementDelegate(this); params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); #endif diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index e18b85b42d54ae..6ff7bd15f97d46 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -273,28 +273,4 @@ void Server::OnResponseTimeout(Messaging::ExchangeContext * ec) } } -CHIP_ERROR Server::DeviceDiscriminatorCache::UpdateDiscriminator(uint16_t discriminator) -{ - if (!mOriginalDiscriminatorCached) - { - // Cache the original discriminator - ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSetupDiscriminator(mOriginalDiscriminator)); - mOriginalDiscriminatorCached = true; - } - - return DeviceLayer::ConfigurationMgr().StoreSetupDiscriminator(discriminator); -} - -CHIP_ERROR Server::DeviceDiscriminatorCache::RestoreDiscriminator() -{ - if (mOriginalDiscriminatorCached) - { - // Restore the original discriminator - ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().StoreSetupDiscriminator(mOriginalDiscriminator)); - mOriginalDiscriminatorCached = false; - } - - return CHIP_NO_ERROR; -} - } // namespace chip diff --git a/src/app/server/Server.h b/src/app/server/Server.h index f472756890717d..a87ec1803c2aa9 100644 --- a/src/app/server/Server.h +++ b/src/app/server/Server.h @@ -85,18 +85,6 @@ class Server : public Messaging::ExchangeDelegate static Server sServer; - class DeviceDiscriminatorCache - { - public: - CHIP_ERROR UpdateDiscriminator(uint16_t discriminator); - - CHIP_ERROR RestoreDiscriminator(); - - private: - bool mOriginalDiscriminatorCached = false; - uint16_t mOriginalDiscriminator = 0; - }; - class ServerStorageDelegate : public PersistentStorageDelegate { CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override @@ -138,7 +126,6 @@ class Server : public Messaging::ExchangeDelegate #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT SecurePairingUsingTestSecret mTestPairing; - DeviceDiscriminatorCache mDeviceDiscriminatorCache; ServerStorageDelegate mServerStorage; CommissionManager mCommissionManager; diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 53053889538fb6..e951fedcf6e4d7 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -26,6 +26,7 @@ chip_test_suite("tests") { "TestClusterInfo.cpp", "TestCommandInteraction.cpp", "TestCommandPathParams.cpp", + "TestCommissionManager.cpp", "TestEventLogging.cpp", "TestEventPathParams.cpp", "TestInteractionModelEngine.cpp", @@ -40,6 +41,7 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/app", "${chip_root}/src/app/util:device_callbacks_manager", + "${chip_root}/src/app/server", "${chip_root}/src/lib/core", "${chip_root}/src/messaging/tests:helpers", "${chip_root}/src/protocols", diff --git a/src/app/tests/TestCommissionManager.cpp b/src/app/tests/TestCommissionManager.cpp new file mode 100644 index 00000000000000..20e986c68e90c4 --- /dev/null +++ b/src/app/tests/TestCommissionManager.cpp @@ -0,0 +1,136 @@ +/* + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using chip::CommissioningWindowAdvertisement; +using chip::CommissionManager; +using chip::kNoCommissioningTimeout; +using chip::ResetFabrics; +using chip::Server; + +// Mock function for linking +void InitDataModelHandler(chip::Messaging::ExchangeManager * exchangeMgr) {} +void HandleDataModelMessage(chip::Messaging::ExchangeContext * exchange, chip::System::PacketBufferHandle && buffer) {} + +namespace { + +void InitializeChip(nlTestSuite * suite) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + err = chip::Platform::MemoryInit(); + NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); + err = chip::DeviceLayer::PlatformMgr().InitChipStack(); + NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); + err = chip::DeviceLayer::PlatformMgr().StartEventLoopTask(); + err = Server::GetInstance().Init(); + NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); +} + +void CheckCommissionManagerBasicWindowOpenClose(nlTestSuite * suite, void *) +{ + CommissionManager & commissionMgr = Server::GetInstance().GetCommissionManager(); + CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindow(ResetFabrics::kNo, kNoCommissioningTimeout, + CommissioningWindowAdvertisement::kMdns); + NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); + NL_TEST_ASSERT(suite, commissionMgr.IsPairingWindowOpen()); + commissionMgr.CloseCommissioningWindow(); + NL_TEST_ASSERT(suite, !commissionMgr.IsPairingWindowOpen()); +} + +void CheckCommissionManagerWindowTimeout(nlTestSuite * suite, void *) +{ + CommissionManager & commissionMgr = Server::GetInstance().GetCommissionManager(); + constexpr uint16_t kTimeoutSeconds = 1; + constexpr unsigned kUsPerSecond = 1000 * 1000; + constexpr unsigned kSleepPadding = 1000 * 10; + CHIP_ERROR err = + commissionMgr.OpenBasicCommissioningWindow(ResetFabrics::kNo, kTimeoutSeconds, CommissioningWindowAdvertisement::kMdns); + NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); + NL_TEST_ASSERT(suite, commissionMgr.IsPairingWindowOpen()); + usleep(kTimeoutSeconds * kUsPerSecond + kSleepPadding); + NL_TEST_ASSERT(suite, !commissionMgr.IsPairingWindowOpen()); + commissionMgr.CloseCommissioningWindow(); +} + +void CheckCommissionManagerEnhancedWindow(nlTestSuite * suite, void *) +{ + CommissionManager & commissionMgr = Server::GetInstance().GetCommissionManager(); + uint16_t originDiscriminator; + CHIP_ERROR err = chip::DeviceLayer::ConfigurationMgr().GetSetupDiscriminator(originDiscriminator); + NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); + uint16_t newDiscriminator = static_cast(originDiscriminator + 1); + chip::PASEVerifier verifier; + constexpr uint32_t kIterations = chip::kPBKDFMinimumIterations; + uint8_t salt[chip::kPBKDFMinimumSaltLen]; + chip::ByteSpan saltData(salt); + constexpr uint16_t kPasscodeID = 1; + uint16_t currentDiscriminator; + + err = commissionMgr.OpenEnhancedCommissioningWindow(kNoCommissioningTimeout, newDiscriminator, verifier, kIterations, saltData, + kPasscodeID); + NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); + NL_TEST_ASSERT(suite, commissionMgr.IsPairingWindowOpen()); + err = chip::DeviceLayer::ConfigurationMgr().GetSetupDiscriminator(currentDiscriminator); + NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); + NL_TEST_ASSERT(suite, currentDiscriminator == newDiscriminator); + + commissionMgr.CloseCommissioningWindow(); + NL_TEST_ASSERT(suite, !commissionMgr.IsPairingWindowOpen()); + err = chip::DeviceLayer::ConfigurationMgr().GetSetupDiscriminator(currentDiscriminator); + NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); + NL_TEST_ASSERT(suite, currentDiscriminator == originDiscriminator); +} + +const nlTest sTests[] = { NL_TEST_DEF("CheckCommissionManagerBasicWindowOpenClose", CheckCommissionManagerBasicWindowOpenClose), + NL_TEST_DEF("CheckCommissionManagerWindowTimeout", CheckCommissionManagerWindowTimeout), + NL_TEST_DEF("CheckCommissionManagerEnhancedWindow", CheckCommissionManagerEnhancedWindow), + NL_TEST_SENTINEL() }; + +} // namespace + +int TestCommissionManager() +{ + // clang-format off + nlTestSuite theSuite = + { + "CommissionManager", + &sTests[0], + nullptr, + nullptr + }; + // clang-format on + + InitializeChip(&theSuite); + nlTestRunner(&theSuite, nullptr); + chip::DeviceLayer::PlatformMgr().Shutdown(); + + return (nlTestRunnerStats(&theSuite)); +} + +CHIP_REGISTER_TEST_SUITE(TestCommissionManager) From 096e067d64e3b8b6c664c8cfa000268b536cb0b5 Mon Sep 17 00:00:00 2001 From: Jiacheng Guo Date: Thu, 9 Sep 2021 15:48:49 +0800 Subject: [PATCH 5/8] gn restyle --- src/app/tests/BUILD.gn | 2 +- src/app/tests/TestCommissionManager.cpp | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index e951fedcf6e4d7..42e2b12f1bf3b1 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -40,8 +40,8 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/app", - "${chip_root}/src/app/util:device_callbacks_manager", "${chip_root}/src/app/server", + "${chip_root}/src/app/util:device_callbacks_manager", "${chip_root}/src/lib/core", "${chip_root}/src/messaging/tests:helpers", "${chip_root}/src/protocols", diff --git a/src/app/tests/TestCommissionManager.cpp b/src/app/tests/TestCommissionManager.cpp index 20e986c68e90c4..1d5415b996cb8c 100644 --- a/src/app/tests/TestCommissionManager.cpp +++ b/src/app/tests/TestCommissionManager.cpp @@ -17,7 +17,6 @@ #include #include -#include #include #include #include From 97b2e16422269f239190b24ac6a97c97ab0acb11 Mon Sep 17 00:00:00 2001 From: Jiacheng Guo Date: Fri, 10 Sep 2021 11:52:08 +0800 Subject: [PATCH 6/8] fix android build --- src/app/tests/BUILD.gn | 9 +++++++-- src/app/tests/TestCommissionManager.cpp | 5 +++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 42e2b12f1bf3b1..aafac491c33878 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -17,6 +17,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") +import("${chip_root}/src/platform/device.gni") chip_test_suite("tests") { output_name = "libAppTests" @@ -26,7 +27,6 @@ chip_test_suite("tests") { "TestClusterInfo.cpp", "TestCommandInteraction.cpp", "TestCommandPathParams.cpp", - "TestCommissionManager.cpp", "TestEventLogging.cpp", "TestEventPathParams.cpp", "TestInteractionModelEngine.cpp", @@ -40,7 +40,6 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/app", - "${chip_root}/src/app/server", "${chip_root}/src/app/util:device_callbacks_manager", "${chip_root}/src/lib/core", "${chip_root}/src/messaging/tests:helpers", @@ -48,4 +47,10 @@ chip_test_suite("tests") { "${chip_root}/src/transport/raw/tests:helpers", "${nlunit_test_root}:nlunit-test", ] + + if (chip_config_network_layer_ble && + (chip_device_platform == "linux" || chip_device_platform == "Darwin")) { + test_sources += [ "TestCommissionManager.cpp" ] + public_deps += [ "${chip_root}/src/app/server" ] + } } diff --git a/src/app/tests/TestCommissionManager.cpp b/src/app/tests/TestCommissionManager.cpp index 1d5415b996cb8c..98f8057386880c 100644 --- a/src/app/tests/TestCommissionManager.cpp +++ b/src/app/tests/TestCommissionManager.cpp @@ -15,6 +15,7 @@ * limitations under the License. */ +#include "app/server/Mdns.h" #include #include #include @@ -106,9 +107,9 @@ void CheckCommissionManagerEnhancedWindow(nlTestSuite * suite, void *) NL_TEST_ASSERT(suite, currentDiscriminator == originDiscriminator); } -const nlTest sTests[] = { NL_TEST_DEF("CheckCommissionManagerBasicWindowOpenClose", CheckCommissionManagerBasicWindowOpenClose), +const nlTest sTests[] = { NL_TEST_DEF("CheckCommissionManagerEnhancedWindow", CheckCommissionManagerEnhancedWindow), + NL_TEST_DEF("CheckCommissionManagerBasicWindowOpenClose", CheckCommissionManagerBasicWindowOpenClose), NL_TEST_DEF("CheckCommissionManagerWindowTimeout", CheckCommissionManagerWindowTimeout), - NL_TEST_DEF("CheckCommissionManagerEnhancedWindow", CheckCommissionManagerEnhancedWindow), NL_TEST_SENTINEL() }; } // namespace From 4b83dd3dd49795912daa4775c2d67a7ef95413b5 Mon Sep 17 00:00:00 2001 From: Jiacheng Guo Date: Fri, 10 Sep 2021 13:37:58 +0800 Subject: [PATCH 7/8] add clean shutdown --- src/app/server/CommissionManager.cpp | 5 ++++- src/app/server/Server.cpp | 16 ++++++++++++++++ src/app/server/Server.h | 2 ++ src/app/tests/TestCommissionManager.cpp | 5 ++++- 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/app/server/CommissionManager.cpp b/src/app/server/CommissionManager.cpp index 72da9fdc73e4e4..bc02c27562375d 100644 --- a/src/app/server/CommissionManager.cpp +++ b/src/app/server/CommissionManager.cpp @@ -50,6 +50,8 @@ CHIP_ERROR CommissionManager::OpenBasicCommissioningWindow(ResetFabrics resetFab { params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); } +#else + SetBLE(false); #endif // CONFIG_NETWORK_LAYER_BLE if (resetFabrics == ResetFabrics::kYes) @@ -83,11 +85,12 @@ CHIP_ERROR CommissionManager::OpenEnhancedCommissioningWindow(uint16_t commissio ReturnErrorOnFailure(SetTemporaryDiscriminator(discriminator)); - SetBLE(false); params.SetAdvertisementDelegate(this); #if CONFIG_NETWORK_LAYER_BLE SetBLE(true); params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()).SetPeerAddress(Transport::PeerAddress::BLE()); +#else + SetBLE(false); #endif params.SetPASEVerifier(verifier).SetAdvertisementDelegate(this); diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index 6ff7bd15f97d46..9b0b20a65a4387 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -15,6 +15,8 @@ * limitations under the License. */ +#include "lib/support/CHIPMem.h" +#include "platform/internal/CHIPDeviceLayerInternal.h" #include #include @@ -28,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -98,6 +101,7 @@ CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint SuccessOrExit(err); // Init transport before operations with secure session mgr. + printf("Init transports\n"); err = mTransports.Init(UdpListenParameters(&DeviceLayer::InetLayer) .SetAddressType(IPAddressType::kIPAddressType_IPv6) .SetListenPort(mSecuredServicePort) @@ -113,6 +117,7 @@ CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint BleListenParameters(DeviceLayer::ConnectivityMgr().GetBleLayer()) #endif ); + printf("Init transports done\n"); SuccessOrExit(err); @@ -188,6 +193,17 @@ CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint return err; } +void Server::Shutdown() +{ + chip::Mdns::ServiceAdvertiser::Instance().StopPublishDevice(); + chip::app::InteractionModelEngine::GetInstance()->Shutdown(); + mExchangeMgr.Shutdown(); + mSessions.Shutdown(); + mTransports.Close(); + mRendezvousServer.Cleanup(); + chip::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 diff --git a/src/app/server/Server.h b/src/app/server/Server.h index a87ec1803c2aa9..f5efb4613728de 100644 --- a/src/app/server/Server.h +++ b/src/app/server/Server.h @@ -78,6 +78,8 @@ class Server : public Messaging::ExchangeDelegate CommissionManager & GetCommissionManager() { return mCommissionManager; } + void Shutdown(); + static Server & GetInstance() { return sServer; } private: diff --git a/src/app/tests/TestCommissionManager.cpp b/src/app/tests/TestCommissionManager.cpp index 98f8057386880c..c9bb54d9ebbbec 100644 --- a/src/app/tests/TestCommissionManager.cpp +++ b/src/app/tests/TestCommissionManager.cpp @@ -16,6 +16,7 @@ */ #include "app/server/Mdns.h" +#include "lib/support/CHIPMem.h" #include #include #include @@ -75,7 +76,6 @@ void CheckCommissionManagerWindowTimeout(nlTestSuite * suite, void *) NL_TEST_ASSERT(suite, commissionMgr.IsPairingWindowOpen()); usleep(kTimeoutSeconds * kUsPerSecond + kSleepPadding); NL_TEST_ASSERT(suite, !commissionMgr.IsPairingWindowOpen()); - commissionMgr.CloseCommissioningWindow(); } void CheckCommissionManagerEnhancedWindow(nlTestSuite * suite, void *) @@ -128,7 +128,10 @@ int TestCommissionManager() InitializeChip(&theSuite); nlTestRunner(&theSuite, nullptr); + + chip::Server::GetInstance().Shutdown(); chip::DeviceLayer::PlatformMgr().Shutdown(); + // TODO: The platform memory was intentionally left not deinitialized so that minimal mdns can destruct return (nlTestRunnerStats(&theSuite)); } From cf24923187808f389c2acbd7516c6a634d37d59a Mon Sep 17 00:00:00 2001 From: Jiacheng Guo Date: Fri, 10 Sep 2021 15:28:03 +0800 Subject: [PATCH 8/8] resolve multithread race --- src/app/server/Server.cpp | 4 -- src/app/tests/TestCommissionManager.cpp | 58 ++++++++++++++++++++----- 2 files changed, 46 insertions(+), 16 deletions(-) diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index 9b0b20a65a4387..2b232fdaf6f5bd 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -15,8 +15,6 @@ * limitations under the License. */ -#include "lib/support/CHIPMem.h" -#include "platform/internal/CHIPDeviceLayerInternal.h" #include #include @@ -101,7 +99,6 @@ CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint SuccessOrExit(err); // Init transport before operations with secure session mgr. - printf("Init transports\n"); err = mTransports.Init(UdpListenParameters(&DeviceLayer::InetLayer) .SetAddressType(IPAddressType::kIPAddressType_IPv6) .SetListenPort(mSecuredServicePort) @@ -117,7 +114,6 @@ CHIP_ERROR Server::Init(AppDelegate * delegate, uint16_t secureServicePort, uint BleListenParameters(DeviceLayer::ConnectivityMgr().GetBleLayer()) #endif ); - printf("Init transports done\n"); SuccessOrExit(err); diff --git a/src/app/tests/TestCommissionManager.cpp b/src/app/tests/TestCommissionManager.cpp index c9bb54d9ebbbec..fb35a717726c83 100644 --- a/src/app/tests/TestCommissionManager.cpp +++ b/src/app/tests/TestCommissionManager.cpp @@ -15,8 +15,6 @@ * limitations under the License. */ -#include "app/server/Mdns.h" -#include "lib/support/CHIPMem.h" #include #include #include @@ -41,6 +39,8 @@ void HandleDataModelMessage(chip::Messaging::ExchangeContext * exchange, chip::S namespace { +static constexpr int kTestTaskWaitSeconds = 2; + void InitializeChip(nlTestSuite * suite) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -48,13 +48,14 @@ void InitializeChip(nlTestSuite * suite) NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); err = chip::DeviceLayer::PlatformMgr().InitChipStack(); NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - err = chip::DeviceLayer::PlatformMgr().StartEventLoopTask(); err = Server::GetInstance().Init(); + chip::DeviceLayer::PlatformMgr().StartEventLoopTask(); NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); } -void CheckCommissionManagerBasicWindowOpenClose(nlTestSuite * suite, void *) +void CheckCommissionManagerBasicWindowOpenCloseTask(intptr_t context) { + nlTestSuite * suite = reinterpret_cast(context); CommissionManager & commissionMgr = Server::GetInstance().GetCommissionManager(); CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindow(ResetFabrics::kNo, kNoCommissioningTimeout, CommissioningWindowAdvertisement::kMdns); @@ -64,22 +65,43 @@ void CheckCommissionManagerBasicWindowOpenClose(nlTestSuite * suite, void *) NL_TEST_ASSERT(suite, !commissionMgr.IsPairingWindowOpen()); } -void CheckCommissionManagerWindowTimeout(nlTestSuite * suite, void *) +void CheckCommissionManagerBasicWindowOpenClose(nlTestSuite * suite, void *) { + chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissionManagerBasicWindowOpenCloseTask, + reinterpret_cast(suite)); + sleep(kTestTaskWaitSeconds); +} + +void CheckCommissionManagerWindowClosedTask(chip::System::Layer *, void * context) +{ + nlTestSuite * suite = static_cast(context); + CommissionManager & commissionMgr = Server::GetInstance().GetCommissionManager(); + NL_TEST_ASSERT(suite, !commissionMgr.IsPairingWindowOpen()); +} + +void CheckCommissionManagerWindowTimeoutTask(intptr_t context) +{ + nlTestSuite * suite = reinterpret_cast(context); CommissionManager & commissionMgr = Server::GetInstance().GetCommissionManager(); constexpr uint16_t kTimeoutSeconds = 1; - constexpr unsigned kUsPerSecond = 1000 * 1000; - constexpr unsigned kSleepPadding = 1000 * 10; + constexpr uint16_t kTimeoutMs = 1000; + constexpr unsigned kSleepPadding = 100; CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindow(ResetFabrics::kNo, kTimeoutSeconds, CommissioningWindowAdvertisement::kMdns); NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(suite, commissionMgr.IsPairingWindowOpen()); - usleep(kTimeoutSeconds * kUsPerSecond + kSleepPadding); - NL_TEST_ASSERT(suite, !commissionMgr.IsPairingWindowOpen()); + chip::DeviceLayer::SystemLayer.StartTimer(kTimeoutMs + kSleepPadding, CheckCommissionManagerWindowClosedTask, suite); } -void CheckCommissionManagerEnhancedWindow(nlTestSuite * suite, void *) +void CheckCommissionManagerWindowTimeout(nlTestSuite * suite, void *) { + chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissionManagerWindowTimeoutTask, reinterpret_cast(suite)); + sleep(kTestTaskWaitSeconds); +} + +void CheckCommissionManagerEnhancedWindowTask(intptr_t context) +{ + nlTestSuite * suite = reinterpret_cast(context); CommissionManager & commissionMgr = Server::GetInstance().GetCommissionManager(); uint16_t originDiscriminator; CHIP_ERROR err = chip::DeviceLayer::ConfigurationMgr().GetSetupDiscriminator(originDiscriminator); @@ -107,6 +129,18 @@ void CheckCommissionManagerEnhancedWindow(nlTestSuite * suite, void *) NL_TEST_ASSERT(suite, currentDiscriminator == originDiscriminator); } +void CheckCommissionManagerEnhancedWindow(nlTestSuite * suite, void *) +{ + chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissionManagerEnhancedWindowTask, reinterpret_cast(suite)); + sleep(kTestTaskWaitSeconds); +} + +void TearDownTask(intptr_t context) +{ + chip::Server::GetInstance().Shutdown(); + chip::DeviceLayer::PlatformMgr().Shutdown(); +} + const nlTest sTests[] = { NL_TEST_DEF("CheckCommissionManagerEnhancedWindow", CheckCommissionManagerEnhancedWindow), NL_TEST_DEF("CheckCommissionManagerBasicWindowOpenClose", CheckCommissionManagerBasicWindowOpenClose), NL_TEST_DEF("CheckCommissionManagerWindowTimeout", CheckCommissionManagerWindowTimeout), @@ -129,9 +163,9 @@ int TestCommissionManager() InitializeChip(&theSuite); nlTestRunner(&theSuite, nullptr); - chip::Server::GetInstance().Shutdown(); - chip::DeviceLayer::PlatformMgr().Shutdown(); // TODO: The platform memory was intentionally left not deinitialized so that minimal mdns can destruct + chip::DeviceLayer::PlatformMgr().ScheduleWork(TearDownTask, 0); + sleep(kTestTaskWaitSeconds); return (nlTestRunnerStats(&theSuite)); }