AppMain.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. /*
  2. *
  3. * Copyright (c) 2021-2022 Project CHIP Authors
  4. * All rights reserved.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include <platform/CHIPDeviceLayer.h>
  19. #include <platform/PlatformManager.h>
  20. #include "app/clusters/network-commissioning/network-commissioning.h"
  21. #include <app/server/OnboardingCodesUtil.h>
  22. #include <app/server/Server.h>
  23. #include <app/util/endpoint-config-api.h>
  24. #include <crypto/CHIPCryptoPAL.h>
  25. #include <lib/core/CHIPError.h>
  26. #include <lib/core/NodeId.h>
  27. #include <lib/core/Optional.h>
  28. #include <lib/support/logging/CHIPLogging.h>
  29. #include <credentials/DeviceAttestationCredsProvider.h>
  30. #include <credentials/attestation_verifier/DefaultDeviceAttestationVerifier.h>
  31. #include <credentials/attestation_verifier/DeviceAttestationVerifier.h>
  32. #include <lib/support/CHIPMem.h>
  33. #include <lib/support/ScopedBuffer.h>
  34. #include <lib/support/TestGroupData.h>
  35. #include <setup_payload/QRCodeSetupPayloadGenerator.h>
  36. #include <setup_payload/SetupPayload.h>
  37. #include <platform/CommissionableDataProvider.h>
  38. #include <platform/DiagnosticDataProvider.h>
  39. #include <platform/RuntimeOptionsProvider.h>
  40. #include <DeviceInfoProviderImpl.h>
  41. #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  42. #include "CommissionerMain.h"
  43. #include <ControllerShellCommands.h>
  44. #include <controller/CHIPDeviceControllerFactory.h>
  45. #include <controller/ExampleOperationalCredentialsIssuer.h>
  46. #include <lib/core/CHIPPersistentStorageDelegate.h>
  47. #include <platform/KeyValueStoreManager.h>
  48. #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  49. #if defined(ENABLE_CHIP_SHELL)
  50. #include <CommissioneeShellCommands.h>
  51. #include <lib/shell/Engine.h> // nogncheck
  52. #include <thread>
  53. #endif
  54. #if defined(PW_RPC_ENABLED)
  55. #include <Rpc.h>
  56. #endif
  57. #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED
  58. #include "TraceDecoder.h"
  59. #include "TraceHandlers.h"
  60. #endif // CHIP_CONFIG_TRANSPORT_TRACE_ENABLED
  61. #if ENABLE_TRACING
  62. #include <TracingCommandLineArgument.h> // nogncheck
  63. #endif
  64. #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR
  65. #include <app/clusters/ota-requestor/OTATestEventTriggerDelegate.h>
  66. #endif
  67. #if CHIP_DEVICE_CONFIG_ENABLE_SMOKE_CO_TRIGGER
  68. #include <app/clusters/smoke-co-alarm-server/SmokeCOTestEventTriggerDelegate.h>
  69. #endif
  70. #include <app/TestEventTriggerDelegate.h>
  71. #include <signal.h>
  72. #include "AppMain.h"
  73. #include "CommissionableInit.h"
  74. #if CHIP_DEVICE_LAYER_TARGET_DARWIN
  75. #include <platform/Darwin/NetworkCommissioningDriver.h>
  76. #if CHIP_DEVICE_CONFIG_ENABLE_WIFI
  77. #include <platform/Darwin/WiFi/NetworkCommissioningWiFiDriver.h>
  78. #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI
  79. #endif // CHIP_DEVICE_LAYER_TARGET_DARWIN
  80. #if CHIP_DEVICE_LAYER_TARGET_LINUX
  81. #include <platform/Linux/NetworkCommissioningDriver.h>
  82. #endif // CHIP_DEVICE_LAYER_TARGET_LINUX
  83. using namespace chip;
  84. using namespace chip::ArgParser;
  85. using namespace chip::Credentials;
  86. using namespace chip::DeviceLayer;
  87. using namespace chip::Inet;
  88. using namespace chip::Transport;
  89. using namespace chip::app::Clusters;
  90. // Network comissioning implementation
  91. namespace {
  92. // If secondaryNetworkCommissioningEndpoint has a value and both Thread and WiFi
  93. // are enabled, we put the WiFi network commissioning cluster on
  94. // secondaryNetworkCommissioningEndpoint.
  95. Optional<EndpointId> sSecondaryNetworkCommissioningEndpoint;
  96. #if CHIP_DEVICE_LAYER_TARGET_LINUX
  97. #if CHIP_DEVICE_CONFIG_ENABLE_THREAD
  98. #define CHIP_APP_MAIN_HAS_THREAD_DRIVER 1
  99. DeviceLayer::NetworkCommissioning::LinuxThreadDriver sThreadDriver;
  100. #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD
  101. #if CHIP_DEVICE_CONFIG_ENABLE_WIFI
  102. #define CHIP_APP_MAIN_HAS_WIFI_DRIVER 1
  103. DeviceLayer::NetworkCommissioning::LinuxWiFiDriver sWiFiDriver;
  104. #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI
  105. #define CHIP_APP_MAIN_HAS_ETHERNET_DRIVER 1
  106. DeviceLayer::NetworkCommissioning::LinuxEthernetDriver sEthernetDriver;
  107. #endif // CHIP_DEVICE_LAYER_TARGET_LINUX
  108. #if CHIP_DEVICE_LAYER_TARGET_DARWIN
  109. #if CHIP_DEVICE_CONFIG_ENABLE_WIFI
  110. #define CHIP_APP_MAIN_HAS_WIFI_DRIVER 1
  111. DeviceLayer::NetworkCommissioning::DarwinWiFiDriver sWiFiDriver;
  112. #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI
  113. #define CHIP_APP_MAIN_HAS_ETHERNET_DRIVER 1
  114. DeviceLayer::NetworkCommissioning::DarwinEthernetDriver sEthernetDriver;
  115. #endif // CHIP_DEVICE_LAYER_TARGET_DARWIN
  116. #ifndef CHIP_APP_MAIN_HAS_THREAD_DRIVER
  117. #define CHIP_APP_MAIN_HAS_THREAD_DRIVER 0
  118. #endif // CHIP_APP_MAIN_HAS_THREAD_DRIVER
  119. #ifndef CHIP_APP_MAIN_HAS_WIFI_DRIVER
  120. #define CHIP_APP_MAIN_HAS_WIFI_DRIVER 0
  121. #endif // CHIP_APP_MAIN_HAS_WIFI_DRIVER
  122. #ifndef CHIP_APP_MAIN_HAS_ETHERNET_DRIVER
  123. #define CHIP_APP_MAIN_HAS_ETHERNET_DRIVER 0
  124. #endif // CHIP_APP_MAIN_HAS_ETHERNET_DRIVER
  125. #if CHIP_APP_MAIN_HAS_THREAD_DRIVER
  126. app::Clusters::NetworkCommissioning::Instance sThreadNetworkCommissioningInstance(kRootEndpointId, &sThreadDriver);
  127. #endif // CHIP_APP_MAIN_HAS_THREAD_DRIVER
  128. #if CHIP_APP_MAIN_HAS_WIFI_DRIVER
  129. // The WiFi network commissioning instance cannot be constructed until we know
  130. // whether we have an sSecondaryNetworkCommissioningEndpoint.
  131. Optional<app::Clusters::NetworkCommissioning::Instance> sWiFiNetworkCommissioningInstance;
  132. #endif // CHIP_APP_MAIN_HAS_WIFI_DRIVER
  133. #if CHIP_APP_MAIN_HAS_ETHERNET_DRIVER
  134. app::Clusters::NetworkCommissioning::Instance sEthernetNetworkCommissioningInstance(kRootEndpointId, &sEthernetDriver);
  135. #endif // CHIP_APP_MAIN_HAS_ETHERNET_DRIVER
  136. void EnableThreadNetworkCommissioning()
  137. {
  138. #if CHIP_APP_MAIN_HAS_THREAD_DRIVER
  139. sThreadNetworkCommissioningInstance.Init();
  140. #endif // CHIP_APP_MAIN_HAS_THREAD_DRIVER
  141. }
  142. void EnableWiFiNetworkCommissioning(EndpointId endpoint)
  143. {
  144. #if CHIP_APP_MAIN_HAS_WIFI_DRIVER
  145. sWiFiNetworkCommissioningInstance.Emplace(endpoint, &sWiFiDriver);
  146. sWiFiNetworkCommissioningInstance.Value().Init();
  147. #endif // CHIP_APP_MAIN_HAS_WIFI_DRIVER
  148. }
  149. void InitNetworkCommissioning()
  150. {
  151. if (sSecondaryNetworkCommissioningEndpoint.HasValue())
  152. {
  153. // Enable secondary endpoint only when we need it, this should be applied to all platforms.
  154. emberAfEndpointEnableDisable(sSecondaryNetworkCommissioningEndpoint.Value(), false);
  155. }
  156. const bool kThreadEnabled = {
  157. #if CHIP_APP_MAIN_HAS_THREAD_DRIVER
  158. LinuxDeviceOptions::GetInstance().mThread
  159. #else
  160. false
  161. #endif
  162. };
  163. const bool kWiFiEnabled = {
  164. #if CHIP_APP_MAIN_HAS_WIFI_DRIVER
  165. LinuxDeviceOptions::GetInstance().mWiFi
  166. #else
  167. false
  168. #endif
  169. };
  170. if (kThreadEnabled && kWiFiEnabled)
  171. {
  172. if (sSecondaryNetworkCommissioningEndpoint.HasValue())
  173. {
  174. EnableThreadNetworkCommissioning();
  175. EnableWiFiNetworkCommissioning(sSecondaryNetworkCommissioningEndpoint.Value());
  176. // Only enable secondary endpoint for network commissioning cluster when both WiFi and Thread are enabled.
  177. emberAfEndpointEnableDisable(sSecondaryNetworkCommissioningEndpoint.Value(), true);
  178. }
  179. else
  180. {
  181. // Just use the Thread one.
  182. EnableThreadNetworkCommissioning();
  183. }
  184. }
  185. else if (kThreadEnabled)
  186. {
  187. EnableThreadNetworkCommissioning();
  188. }
  189. else if (kWiFiEnabled)
  190. {
  191. EnableWiFiNetworkCommissioning(kRootEndpointId);
  192. }
  193. else
  194. {
  195. #if CHIP_APP_MAIN_HAS_ETHERNET_DRIVER
  196. sEthernetNetworkCommissioningInstance.Init();
  197. #endif // CHIP_APP_MAIN_HAS_ETHERNET_DRIVER
  198. }
  199. }
  200. } // anonymous namespace
  201. #if defined(ENABLE_CHIP_SHELL)
  202. using chip::Shell::Engine;
  203. #endif
  204. #if CHIP_DEVICE_CONFIG_ENABLE_WPA
  205. /*
  206. * The device shall check every kWiFiStartCheckTimeUsec whether Wi-Fi management
  207. * has been fully initialized. If after kWiFiStartCheckAttempts Wi-Fi management
  208. * still hasn't been initialized, the device configuration is reset, and device
  209. * needs to be paired again.
  210. */
  211. static constexpr useconds_t kWiFiStartCheckTimeUsec = 100 * 1000; // 100 ms
  212. static constexpr uint8_t kWiFiStartCheckAttempts = 5;
  213. #endif
  214. namespace {
  215. AppMainLoopImplementation * gMainLoopImplementation = nullptr;
  216. // To hold SPAKE2+ verifier, discriminator, passcode
  217. LinuxCommissionableDataProvider gCommissionableDataProvider;
  218. chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider;
  219. void EventHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
  220. {
  221. (void) arg;
  222. if (event->Type == DeviceLayer::DeviceEventType::kCHIPoBLEConnectionEstablished)
  223. {
  224. ChipLogProgress(DeviceLayer, "Receive kCHIPoBLEConnectionEstablished");
  225. }
  226. }
  227. void Cleanup()
  228. {
  229. #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED
  230. chip::trace::DeInitTrace();
  231. #endif // CHIP_CONFIG_TRANSPORT_TRACE_ENABLED
  232. // TODO(16968): Lifecycle management of storage-using components like GroupDataProvider, etc
  233. }
  234. // TODO(#20664) REPL test will fail if signal SIGINT is not caught, temporarily keep following logic.
  235. // when the shell is enabled, don't intercept signals since it prevents the user from
  236. // using expected commands like CTRL-C to quit the application. (see issue #17845)
  237. // We should stop using signals for those faults, and move to a different notification
  238. // means, like a pipe. (see issue #19114)
  239. #if !defined(ENABLE_CHIP_SHELL)
  240. void StopSignalHandler(int signal)
  241. {
  242. if (gMainLoopImplementation != nullptr)
  243. {
  244. gMainLoopImplementation->SignalSafeStopMainLoop();
  245. }
  246. else
  247. {
  248. Server::GetInstance().GenerateShutDownEvent();
  249. PlatformMgr().ScheduleWork([](intptr_t) { PlatformMgr().StopEventLoopTask(); });
  250. }
  251. }
  252. #endif // !defined(ENABLE_CHIP_SHELL)
  253. } // namespace
  254. #if CHIP_DEVICE_CONFIG_ENABLE_WPA
  255. static bool EnsureWiFiIsStarted()
  256. {
  257. for (int cnt = 0; cnt < kWiFiStartCheckAttempts; cnt++)
  258. {
  259. if (DeviceLayer::ConnectivityMgrImpl().IsWiFiManagementStarted())
  260. {
  261. return true;
  262. }
  263. usleep(kWiFiStartCheckTimeUsec);
  264. }
  265. return DeviceLayer::ConnectivityMgrImpl().IsWiFiManagementStarted();
  266. }
  267. #endif
  268. class SampleTestEventTriggerDelegate : public TestEventTriggerDelegate
  269. {
  270. public:
  271. /// NOTE: If you copy this, please use the reserved range FFFF_FFFF_<VID_HEX>_xxxx for your trigger codes.
  272. static constexpr uint64_t kSampleTestEventTriggerAlwaysSuccess = static_cast<uint64_t>(0xFFFF'FFFF'FFF1'0000ull);
  273. SampleTestEventTriggerDelegate() { memset(&mEnableKey[0], 0, sizeof(mEnableKey)); }
  274. /**
  275. * @brief Initialize the delegate with a key and an optional other handler
  276. *
  277. * The `otherDelegate` will be called if there is no match of the eventTrigger
  278. * when HandleEventTrigger is called, if it is non-null.
  279. *
  280. * @param enableKey - EnableKey to use for this instance.
  281. * @param otherDelegate - Other delegate (e.g. OTA delegate) where defer trigger. Can be nullptr
  282. * @return CHIP_NO_ERROR on success, CHIP_ERROR_INVALID_ARGUMENT if enableKey is wrong size.
  283. */
  284. CHIP_ERROR Init(ByteSpan enableKey, TestEventTriggerDelegate * otherDelegate)
  285. {
  286. VerifyOrReturnError(enableKey.size() == sizeof(mEnableKey), CHIP_ERROR_INVALID_ARGUMENT);
  287. mOtherDelegate = otherDelegate;
  288. MutableByteSpan ourEnableKeySpan(mEnableKey);
  289. return CopySpanToMutableSpan(enableKey, ourEnableKeySpan);
  290. }
  291. bool DoesEnableKeyMatch(const ByteSpan & enableKey) const override { return enableKey.data_equal(ByteSpan(mEnableKey)); }
  292. CHIP_ERROR HandleEventTrigger(uint64_t eventTrigger) override
  293. {
  294. ChipLogProgress(Support, "Saw TestEventTrigger: " ChipLogFormatX64, ChipLogValueX64(eventTrigger));
  295. if (eventTrigger == kSampleTestEventTriggerAlwaysSuccess)
  296. {
  297. // Do nothing, successfully
  298. ChipLogProgress(Support, "Handling \"Always success\" internal test event");
  299. return CHIP_NO_ERROR;
  300. }
  301. return (mOtherDelegate != nullptr) ? mOtherDelegate->HandleEventTrigger(eventTrigger) : CHIP_ERROR_INVALID_ARGUMENT;
  302. }
  303. private:
  304. uint8_t mEnableKey[TestEventTriggerDelegate::kEnableKeyLength];
  305. TestEventTriggerDelegate * mOtherDelegate = nullptr;
  306. };
  307. int ChipLinuxAppInit(int argc, char * const argv[], OptionSet * customOptions,
  308. const Optional<EndpointId> secondaryNetworkCommissioningEndpoint)
  309. {
  310. CHIP_ERROR err = CHIP_NO_ERROR;
  311. #if CONFIG_NETWORK_LAYER_BLE
  312. RendezvousInformationFlags rendezvousFlags = RendezvousInformationFlag::kBLE;
  313. #else // CONFIG_NETWORK_LAYER_BLE
  314. RendezvousInformationFlag rendezvousFlags = RendezvousInformationFlag::kOnNetwork;
  315. #endif // CONFIG_NETWORK_LAYER_BLE
  316. #ifdef CONFIG_RENDEZVOUS_MODE
  317. rendezvousFlags = static_cast<RendezvousInformationFlags>(CONFIG_RENDEZVOUS_MODE);
  318. #endif
  319. err = Platform::MemoryInit();
  320. SuccessOrExit(err);
  321. err = ParseArguments(argc, argv, customOptions);
  322. SuccessOrExit(err);
  323. sSecondaryNetworkCommissioningEndpoint = secondaryNetworkCommissioningEndpoint;
  324. #ifdef CHIP_CONFIG_KVS_PATH
  325. if (LinuxDeviceOptions::GetInstance().KVS == nullptr)
  326. {
  327. err = DeviceLayer::PersistedStorage::KeyValueStoreMgrImpl().Init(CHIP_CONFIG_KVS_PATH);
  328. }
  329. else
  330. {
  331. err = DeviceLayer::PersistedStorage::KeyValueStoreMgrImpl().Init(LinuxDeviceOptions::GetInstance().KVS);
  332. }
  333. SuccessOrExit(err);
  334. #endif
  335. err = DeviceLayer::PlatformMgr().InitChipStack();
  336. SuccessOrExit(err);
  337. // Init the commissionable data provider based on command line options
  338. // to handle custom verifiers, discriminators, etc.
  339. err = chip::examples::InitCommissionableDataProvider(gCommissionableDataProvider, LinuxDeviceOptions::GetInstance());
  340. SuccessOrExit(err);
  341. DeviceLayer::SetCommissionableDataProvider(&gCommissionableDataProvider);
  342. err = chip::examples::InitConfigurationManager(reinterpret_cast<ConfigurationManagerImpl &>(ConfigurationMgr()),
  343. LinuxDeviceOptions::GetInstance());
  344. SuccessOrExit(err);
  345. if (LinuxDeviceOptions::GetInstance().payload.rendezvousInformation.HasValue())
  346. {
  347. rendezvousFlags = LinuxDeviceOptions::GetInstance().payload.rendezvousInformation.Value();
  348. }
  349. err = GetPayloadContents(LinuxDeviceOptions::GetInstance().payload, rendezvousFlags);
  350. SuccessOrExit(err);
  351. ConfigurationMgr().LogDeviceConfig();
  352. {
  353. ChipLogProgress(NotSpecified, "==== Onboarding payload for Standard Commissioning Flow ====");
  354. PrintOnboardingCodes(LinuxDeviceOptions::GetInstance().payload);
  355. }
  356. #if defined(PW_RPC_ENABLED)
  357. rpc::Init();
  358. ChipLogProgress(NotSpecified, "PW_RPC initialized.");
  359. #endif // defined(PW_RPC_ENABLED)
  360. DeviceLayer::PlatformMgrImpl().AddEventHandler(EventHandler, 0);
  361. #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED
  362. if (LinuxDeviceOptions::GetInstance().traceStreamFilename.HasValue())
  363. {
  364. const char * traceFilename = LinuxDeviceOptions::GetInstance().traceStreamFilename.Value().c_str();
  365. auto traceStream = new chip::trace::TraceStreamFile(traceFilename);
  366. chip::trace::AddTraceStream(traceStream);
  367. }
  368. else if (LinuxDeviceOptions::GetInstance().traceStreamToLogEnabled)
  369. {
  370. auto traceStream = new chip::trace::TraceStreamLog();
  371. chip::trace::AddTraceStream(traceStream);
  372. }
  373. if (LinuxDeviceOptions::GetInstance().traceStreamDecodeEnabled)
  374. {
  375. chip::trace::TraceDecoderOptions options;
  376. options.mEnableProtocolInteractionModelResponse = false;
  377. chip::trace::TraceDecoder * decoder = new chip::trace::TraceDecoder();
  378. decoder->SetOptions(options);
  379. chip::trace::AddTraceStream(decoder);
  380. }
  381. chip::trace::InitTrace();
  382. #endif // CHIP_CONFIG_TRANSPORT_TRACE_ENABLED
  383. #if CONFIG_NETWORK_LAYER_BLE
  384. DeviceLayer::ConnectivityMgr().SetBLEDeviceName(nullptr); // Use default device name (CHIP-XXXX)
  385. DeviceLayer::Internal::BLEMgrImpl().ConfigureBle(LinuxDeviceOptions::GetInstance().mBleDevice, false);
  386. DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true);
  387. #endif
  388. #if CHIP_DEVICE_CONFIG_ENABLE_WPA
  389. if (LinuxDeviceOptions::GetInstance().mWiFi)
  390. {
  391. DeviceLayer::ConnectivityMgrImpl().StartWiFiManagement();
  392. if (!EnsureWiFiIsStarted())
  393. {
  394. ChipLogError(NotSpecified, "Wi-Fi Management taking too long to start - device configuration will be reset.");
  395. }
  396. }
  397. #endif // CHIP_DEVICE_CONFIG_ENABLE_WPA
  398. #if CHIP_ENABLE_OPENTHREAD
  399. if (LinuxDeviceOptions::GetInstance().mThread)
  400. {
  401. SuccessOrExit(err = DeviceLayer::ThreadStackMgrImpl().InitThreadStack());
  402. ChipLogProgress(NotSpecified, "Thread initialized.");
  403. }
  404. #endif // CHIP_ENABLE_OPENTHREAD
  405. exit:
  406. if (err != CHIP_NO_ERROR)
  407. {
  408. ChipLogProgress(NotSpecified, "Failed to init Linux App: %s ", ErrorStr(err));
  409. Cleanup();
  410. // End the program with non zero error code to indicate a error.
  411. return 1;
  412. }
  413. return 0;
  414. }
  415. void ChipLinuxAppMainLoop(AppMainLoopImplementation * impl)
  416. {
  417. gMainLoopImplementation = impl;
  418. static chip::CommonCaseDeviceServerInitParams initParams;
  419. VerifyOrDie(initParams.InitializeStaticResourcesBeforeServerInit() == CHIP_NO_ERROR);
  420. #if defined(ENABLE_CHIP_SHELL)
  421. Engine::Root().Init();
  422. std::thread shellThread([]() { Engine::Root().RunMainLoop(); });
  423. Shell::RegisterCommissioneeCommands();
  424. #endif
  425. initParams.operationalServicePort = CHIP_PORT;
  426. initParams.userDirectedCommissioningPort = CHIP_UDC_PORT;
  427. #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE || CHIP_DEVICE_ENABLE_PORT_PARAMS
  428. // use a different service port to make testing possible with other sample devices running on same host
  429. initParams.operationalServicePort = LinuxDeviceOptions::GetInstance().securedDevicePort;
  430. initParams.userDirectedCommissioningPort = LinuxDeviceOptions::GetInstance().unsecuredCommissionerPort;
  431. #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  432. #if ENABLE_TRACING
  433. chip::CommandLineApp::TracingSetup tracing_setup;
  434. for (const auto & trace_destination : LinuxDeviceOptions::GetInstance().traceTo)
  435. {
  436. tracing_setup.EnableTracingFor(trace_destination.c_str());
  437. }
  438. #endif
  439. initParams.interfaceId = LinuxDeviceOptions::GetInstance().interfaceId;
  440. if (LinuxDeviceOptions::GetInstance().mCSRResponseOptions.csrExistingKeyPair)
  441. {
  442. LinuxDeviceOptions::GetInstance().mCSRResponseOptions.badCsrOperationalKeyStoreForTest.Init(
  443. initParams.persistentStorageDelegate);
  444. initParams.operationalKeystore = &LinuxDeviceOptions::GetInstance().mCSRResponseOptions.badCsrOperationalKeyStoreForTest;
  445. }
  446. TestEventTriggerDelegate * otherDelegate = nullptr;
  447. #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR
  448. // We want to allow triggering OTA queries if OTA requestor is enabled
  449. static OTATestEventTriggerDelegate otaTestEventTriggerDelegate{ ByteSpan(
  450. LinuxDeviceOptions::GetInstance().testEventTriggerEnableKey) };
  451. otherDelegate = &otaTestEventTriggerDelegate;
  452. #endif
  453. #if CHIP_DEVICE_CONFIG_ENABLE_SMOKE_CO_TRIGGER
  454. static SmokeCOTestEventTriggerDelegate smokeCOTestEventTriggerDelegate{
  455. ByteSpan(LinuxDeviceOptions::GetInstance().testEventTriggerEnableKey), otherDelegate
  456. };
  457. otherDelegate = &smokeCOTestEventTriggerDelegate;
  458. #endif
  459. // For general testing of TestEventTrigger, we have a common "core" event trigger delegate.
  460. static SampleTestEventTriggerDelegate testEventTriggerDelegate;
  461. VerifyOrDie(testEventTriggerDelegate.Init(ByteSpan(LinuxDeviceOptions::GetInstance().testEventTriggerEnableKey),
  462. otherDelegate) == CHIP_NO_ERROR);
  463. initParams.testEventTriggerDelegate = &testEventTriggerDelegate;
  464. // We need to set DeviceInfoProvider before Server::Init to setup the storage of DeviceInfoProvider properly.
  465. DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider);
  466. chip::app::RuntimeOptionsProvider::Instance().SetSimulateNoInternalTime(
  467. LinuxDeviceOptions::GetInstance().mSimulateNoInternalTime);
  468. // Init ZCL Data Model and CHIP App Server
  469. Server::GetInstance().Init(initParams);
  470. // Now that the server has started and we are done with our startup logging,
  471. // log our discovery/onboarding information again so it's not lost in the
  472. // noise.
  473. ConfigurationMgr().LogDeviceConfig();
  474. PrintOnboardingCodes(LinuxDeviceOptions::GetInstance().payload);
  475. // Initialize device attestation config
  476. SetDeviceAttestationCredentialsProvider(LinuxDeviceOptions::GetInstance().dacProvider);
  477. #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  478. ChipLogProgress(AppServer, "Starting commissioner");
  479. VerifyOrReturn(InitCommissioner(LinuxDeviceOptions::GetInstance().securedCommissionerPort,
  480. LinuxDeviceOptions::GetInstance().unsecuredCommissionerPort,
  481. LinuxDeviceOptions::GetInstance().commissionerFabricId) == CHIP_NO_ERROR);
  482. ChipLogProgress(AppServer, "Started commissioner");
  483. #if defined(ENABLE_CHIP_SHELL)
  484. Shell::RegisterControllerCommands();
  485. #endif // defined(ENABLE_CHIP_SHELL)
  486. #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  487. InitNetworkCommissioning();
  488. ApplicationInit();
  489. #if !defined(ENABLE_CHIP_SHELL)
  490. // NOLINTBEGIN(bugprone-signal-handler)
  491. signal(SIGINT, StopSignalHandler);
  492. signal(SIGTERM, StopSignalHandler);
  493. // NOLINTEND(bugprone-signal-handler)
  494. #endif // !defined(ENABLE_CHIP_SHELL)
  495. if (impl != nullptr)
  496. {
  497. impl->RunMainLoop();
  498. }
  499. else
  500. {
  501. DeviceLayer::PlatformMgr().RunEventLoop();
  502. }
  503. gMainLoopImplementation = nullptr;
  504. ApplicationShutdown();
  505. #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  506. ShutdownCommissioner();
  507. #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  508. #if defined(ENABLE_CHIP_SHELL)
  509. shellThread.join();
  510. #endif
  511. Server::GetInstance().Shutdown();
  512. #if ENABLE_TRACING
  513. tracing_setup.StopTracing();
  514. #endif
  515. DeviceLayer::PlatformMgr().Shutdown();
  516. Cleanup();
  517. }