AppMain.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /*
  2. *
  3. * Copyright (c) 2021 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 <iostream>
  19. #include <thread>
  20. #include <platform/CHIPDeviceLayer.h>
  21. #include <platform/PlatformManager.h>
  22. #include <app/server/OnboardingCodesUtil.h>
  23. #include <app/server/Server.h>
  24. #include <core/CHIPError.h>
  25. #include <core/NodeId.h>
  26. #include <credentials/DeviceAttestationCredsProvider.h>
  27. #include <credentials/examples/DeviceAttestationCredsExample.h>
  28. #include <setup_payload/QRCodeSetupPayloadGenerator.h>
  29. #include <setup_payload/SetupPayload.h>
  30. #include <support/CHIPMem.h>
  31. #include <support/RandUtils.h>
  32. #include <support/ScopedBuffer.h>
  33. #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  34. #include <ControllerShellCommands.h>
  35. #include <controller/CHIPDeviceController.h>
  36. #include <controller/ExampleOperationalCredentialsIssuer.h>
  37. #include <core/CHIPPersistentStorageDelegate.h>
  38. #include <platform/KeyValueStoreManager.h>
  39. #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  40. #if defined(ENABLE_CHIP_SHELL)
  41. #include <CommissioneeShellCommands.h>
  42. #include <lib/shell/Engine.h>
  43. #endif
  44. #if defined(PW_RPC_ENABLED)
  45. #include <CommonRpc.h>
  46. #endif
  47. #include "Options.h"
  48. using namespace chip;
  49. using namespace chip::Credentials;
  50. using namespace chip::DeviceLayer;
  51. using namespace chip::Inet;
  52. using namespace chip::Transport;
  53. #if defined(ENABLE_CHIP_SHELL)
  54. using chip::Shell::Engine;
  55. #endif
  56. namespace {
  57. void EventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
  58. {
  59. (void) arg;
  60. if (event->Type == chip::DeviceLayer::DeviceEventType::kCHIPoBLEConnectionEstablished)
  61. {
  62. ChipLogProgress(DeviceLayer, "Receive kCHIPoBLEConnectionEstablished");
  63. }
  64. }
  65. } // namespace
  66. int ChipLinuxAppInit(int argc, char ** argv)
  67. {
  68. CHIP_ERROR err = CHIP_NO_ERROR;
  69. chip::RendezvousInformationFlags rendezvousFlags = chip::RendezvousInformationFlag::kBLE;
  70. #ifdef CONFIG_RENDEZVOUS_MODE
  71. rendezvousFlags = static_cast<chip::RendezvousInformationFlags>(CONFIG_RENDEZVOUS_MODE);
  72. #endif
  73. err = chip::Platform::MemoryInit();
  74. SuccessOrExit(err);
  75. err = GetSetupPayload(LinuxDeviceOptions::GetInstance().payload, rendezvousFlags);
  76. SuccessOrExit(err);
  77. err = ParseArguments(argc, argv);
  78. SuccessOrExit(err);
  79. err = chip::DeviceLayer::PlatformMgr().InitChipStack();
  80. SuccessOrExit(err);
  81. ConfigurationMgr().LogDeviceConfig();
  82. PrintOnboardingCodes(LinuxDeviceOptions::GetInstance().payload);
  83. #if defined(PW_RPC_ENABLED)
  84. chip::rpc::Init();
  85. ChipLogProgress(NotSpecified, "PW_RPC initialized.");
  86. #endif // defined(PW_RPC_ENABLED)
  87. chip::DeviceLayer::PlatformMgrImpl().AddEventHandler(EventHandler, 0);
  88. chip::DeviceLayer::ConnectivityMgr().SetBLEDeviceName(nullptr); // Use default device name (CHIP-XXXX)
  89. #if CONFIG_NETWORK_LAYER_BLE
  90. chip::DeviceLayer::Internal::BLEMgrImpl().ConfigureBle(LinuxDeviceOptions::GetInstance().mBleDevice, false);
  91. #endif
  92. chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true);
  93. #if CHIP_DEVICE_CONFIG_ENABLE_WPA
  94. if (LinuxDeviceOptions::GetInstance().mWiFi)
  95. {
  96. chip::DeviceLayer::ConnectivityMgrImpl().StartWiFiManagement();
  97. }
  98. #endif // CHIP_DEVICE_CONFIG_ENABLE_WPA
  99. #if CHIP_ENABLE_OPENTHREAD
  100. if (LinuxDeviceOptions::GetInstance().mThread)
  101. {
  102. SuccessOrExit(err = chip::DeviceLayer::ThreadStackMgrImpl().InitThreadStack());
  103. ChipLogProgress(NotSpecified, "Thread initialized.");
  104. }
  105. #endif // CHIP_ENABLE_OPENTHREAD
  106. exit:
  107. if (err != CHIP_NO_ERROR)
  108. {
  109. ChipLogProgress(NotSpecified, "Failed to run Linux Lighting App: %s ", ErrorStr(err));
  110. // End the program with non zero error code to indicate a error.
  111. return 1;
  112. }
  113. return 0;
  114. }
  115. #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  116. using namespace ::chip;
  117. using namespace ::chip::Inet;
  118. using namespace ::chip::Transport;
  119. using namespace ::chip::Credentials;
  120. using namespace ::chip::DeviceLayer;
  121. using namespace ::chip::Messaging;
  122. using namespace ::chip::Controller;
  123. class MyServerStorageDelegate : public PersistentStorageDelegate
  124. {
  125. CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override
  126. {
  127. ChipLogProgress(AppServer, "Retrieved value from server storage.");
  128. return PersistedStorage::KeyValueStoreMgr().Get(key, buffer, size);
  129. }
  130. CHIP_ERROR SyncSetKeyValue(const char * key, const void * value, uint16_t size) override
  131. {
  132. ChipLogProgress(AppServer, "Stored value in server storage");
  133. return PersistedStorage::KeyValueStoreMgr().Put(key, value, size);
  134. }
  135. CHIP_ERROR SyncDeleteKeyValue(const char * key) override
  136. {
  137. ChipLogProgress(AppServer, "Delete value in server storage");
  138. return PersistedStorage::KeyValueStoreMgr().Delete(key);
  139. }
  140. };
  141. DeviceCommissioner gCommissioner;
  142. MyServerStorageDelegate gServerStorage;
  143. ExampleOperationalCredentialsIssuer gOpCredsIssuer;
  144. CHIP_ERROR InitCommissioner()
  145. {
  146. NodeId localId = chip::kPlaceholderNodeId;
  147. chip::Controller::CommissionerInitParams params;
  148. params.storageDelegate = &gServerStorage;
  149. params.mDeviceAddressUpdateDelegate = nullptr;
  150. params.operationalCredentialsDelegate = &gOpCredsIssuer;
  151. ReturnErrorOnFailure(gOpCredsIssuer.Initialize(gServerStorage));
  152. // use a different listen port for the commissioner.
  153. ReturnErrorOnFailure(gCommissioner.SetUdpListenPort(LinuxDeviceOptions::GetInstance().securedCommissionerPort));
  154. // No need to explicitly set the UDC port since we will use default
  155. ReturnErrorOnFailure(gCommissioner.SetUdcListenPort(LinuxDeviceOptions::GetInstance().unsecuredCommissionerPort));
  156. chip::Platform::ScopedMemoryBuffer<uint8_t> noc;
  157. VerifyOrReturnError(noc.Alloc(chip::Controller::kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY);
  158. chip::MutableByteSpan nocSpan(noc.Get(), chip::Controller::kMaxCHIPDERCertLength);
  159. chip::Platform::ScopedMemoryBuffer<uint8_t> icac;
  160. VerifyOrReturnError(icac.Alloc(chip::Controller::kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY);
  161. chip::MutableByteSpan icacSpan(icac.Get(), chip::Controller::kMaxCHIPDERCertLength);
  162. chip::Platform::ScopedMemoryBuffer<uint8_t> rcac;
  163. VerifyOrReturnError(rcac.Alloc(chip::Controller::kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY);
  164. chip::MutableByteSpan rcacSpan(rcac.Get(), chip::Controller::kMaxCHIPDERCertLength);
  165. chip::Crypto::P256Keypair ephemeralKey;
  166. ReturnErrorOnFailure(ephemeralKey.Initialize());
  167. ReturnErrorOnFailure(
  168. gOpCredsIssuer.GenerateNOCChainAfterValidation(localId, 0, ephemeralKey.Pubkey(), rcacSpan, icacSpan, nocSpan));
  169. params.ephemeralKeypair = &ephemeralKey;
  170. params.controllerRCAC = rcacSpan;
  171. params.controllerICAC = icacSpan;
  172. params.controllerNOC = nocSpan;
  173. ReturnErrorOnFailure(gCommissioner.Init(params));
  174. return CHIP_NO_ERROR;
  175. }
  176. CHIP_ERROR ShutdownCommissioner()
  177. {
  178. gCommissioner.Shutdown();
  179. return CHIP_NO_ERROR;
  180. }
  181. #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  182. void ChipLinuxAppMainLoop()
  183. {
  184. #if defined(ENABLE_CHIP_SHELL)
  185. std::thread shellThread([]() { Engine::Root().RunMainLoop(); });
  186. chip::Shell::RegisterCommissioneeCommands();
  187. #endif
  188. #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  189. // use a different service port to make testing possible with other sample devices running on same host
  190. ServerConfigParams params;
  191. params.securedServicePort = LinuxDeviceOptions::GetInstance().securedDevicePort;
  192. params.unsecuredServicePort = LinuxDeviceOptions::GetInstance().unsecuredCommissionerPort;
  193. SetServerConfig(params);
  194. #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  195. // Init ZCL Data Model and CHIP App Server
  196. InitServer();
  197. // Initialize device attestation config
  198. SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider());
  199. #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  200. InitCommissioner();
  201. #if defined(ENABLE_CHIP_SHELL)
  202. chip::Shell::RegisterDiscoverCommands(&gCommissioner);
  203. #endif // defined(ENABLE_CHIP_SHELL)
  204. #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  205. chip::DeviceLayer::PlatformMgr().RunEventLoop();
  206. #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  207. ShutdownCommissioner();
  208. #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
  209. #if defined(ENABLE_CHIP_SHELL)
  210. shellThread.join();
  211. #endif
  212. }