From 36bb9b37d5cc2bf89797d75d08d1aa6407194c85 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Thu, 14 Jul 2022 14:57:07 -0700 Subject: [PATCH 01/28] DRAFT: add ScanNetworks step to CHIPDeviceController --- src/controller/AutoCommissioner.cpp | 19 +++++++ src/controller/AutoCommissioner.h | 2 + src/controller/CHIPDeviceController.cpp | 71 +++++++++++++++++++++++++ src/controller/CHIPDeviceController.h | 4 ++ src/controller/CommissioningDelegate.h | 17 ++++++ 5 files changed, 113 insertions(+) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index 4ddd081e46ed04..e7f5b3c625c880 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -159,6 +159,25 @@ CommissioningStage AutoCommissioner::GetNextCommissioningStageInternal(Commissio } return CommissioningStage::kArmFailsafe; case CommissioningStage::kArmFailsafe: + if (mNeedsNetworkSetup) + { + // if there is a WiFi or a Thread endpoint, then perform scan + if ((mParams.GetAttemptWiFiNetworkScan() && mDeviceCommissioningInfo.network.wifi.endpoint != kInvalidEndpointId) || + (mParams.GetAttemptThreadNetworkScan() && mDeviceCommissioningInfo.network.thread.endpoint != kInvalidEndpointId)) + { + return CommissioningStage::kScanNetworks; + } + else + { + ChipLogProgress(Controller, "No NetworkScan enabled or WiFi/Thread endpoint not specified, skipping ScanNetworks"); + } + } + else + { + ChipLogProgress(Controller, "Not a BLE connection, skipping ScanNetworks"); + } + // fall through if no network scan is called for + case CommissioningStage::kScanNetworks: return CommissioningStage::kConfigRegulatory; case CommissioningStage::kConfigRegulatory: return CommissioningStage::kSendPAICertificateRequest; diff --git a/src/controller/AutoCommissioner.h b/src/controller/AutoCommissioner.h index b6df47deb6bf64..33bfe350b9fa34 100644 --- a/src/controller/AutoCommissioner.h +++ b/src/controller/AutoCommissioner.h @@ -38,6 +38,8 @@ class AutoCommissioner : public CommissioningDelegate CHIP_ERROR CommissioningStepFinished(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report) override; + ReadCommissioningInfo GetReadCommissioningInfo() const { return mDeviceCommissioningInfo; } + protected: CommissioningStage GetNextCommissioningStage(CommissioningStage currentStage, CHIP_ERROR & lastErr); DeviceCommissioner * GetCommissioner() { return mCommissioner; } diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 8466dc5723a423..f9ad570c6d5dcd 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1724,20 +1724,24 @@ void DeviceCommissioner::OnDone(app::ReadClient *) { if (features.Has(app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kWiFiNetworkInterface)) { + ChipLogError(Controller, "----- NetworkCommissioning Features: has WiFi."); info.network.wifi.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kThreadNetworkInterface)) { + ChipLogError(Controller, "----- NetworkCommissioning Features: has Thread."); info.network.thread.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kEthernetNetworkInterface)) { + ChipLogError(Controller, "----- NetworkCommissioning Features: has Ethernet."); info.network.eth.endpoint = path.mEndpointId; } else { + ChipLogError(Controller, "----- NetworkCommissioning Features: no features."); // TODO: Gross workaround for the empty feature map on all clusters. Remove. if (info.network.thread.endpoint == kInvalidEndpointId) { @@ -1824,6 +1828,63 @@ void DeviceCommissioner::OnSetRegulatoryConfigResponse( commissioner->CommissioningStageComplete(err, report); } +void OnScanNetworksFailure(void * context, CHIP_ERROR error) +{ + ChipLogProgress(Controller, "Received ScanNetworks failure response %s\n", chip::ErrorStr(error)); + // need to advance to next step + DeviceCommissioner * commissioner = static_cast(context); + // clear error so that we don't abort the commissioning when ScanNetworks fails + commissioner->CommissioningStageComplete(CHIP_NO_ERROR); +} + +void DeviceCommissioner::OnScanNetworksResponse(void * context, + const NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data) +{ + CommissioningDelegate::CommissioningReport report; + + ChipLogProgress(Controller, "Received ScanNetwork response, networkingStatus=%u debugText=%s", + to_underlying(data.networkingStatus), + (data.debugText.HasValue() ? std::string(data.debugText.Value().data(), data.debugText.Value().size()).c_str() + : "none provided")); + if (data.networkingStatus == NetworkCommissioning::NetworkCommissioningStatus::kSuccess) + { + if (data.wiFiScanResults.HasValue()) + { + ChipLogProgress(Controller, "ScanNetwork response, has WiFi results"); + + auto iter_WiFiScanResultsInsideOptional_1 = data.wiFiScanResults.Value().begin(); + while (iter_WiFiScanResultsInsideOptional_1.Next()) + { + auto & entry_1 = iter_WiFiScanResultsInsideOptional_1.GetValue(); + ChipLogProgress(Controller, "ScanNetwork response, next WiFi channel=%d", entry_1.channel); + } + } + else + { + ChipLogProgress(Controller, "ScanNetwork response, no WiFi results"); + } + if (data.threadScanResults.HasValue()) + { + ChipLogProgress(Controller, "ScanNetwork response, has Thread results"); + + auto iter_ThreadScanResultsInsideOptional_1 = data.threadScanResults.Value().begin(); + while (iter_ThreadScanResultsInsideOptional_1.Next()) + { + auto & entry_1 = iter_ThreadScanResultsInsideOptional_1.GetValue(); + ChipLogProgress(Controller, "ScanNetwork response, next Thread network name=%s", + std::string(entry_1.networkName.data(), entry_1.networkName.size()).c_str()); + } + } + else + { + ChipLogProgress(Controller, "ScanNetwork response, no Thread results"); + } + } + DeviceCommissioner * commissioner = static_cast(context); + // clear error so that we don't abort the commissioning when ScanNetworks fails + commissioner->CommissioningStageComplete(CHIP_NO_ERROR); +} + void DeviceCommissioner::OnNetworkConfigResponse(void * context, const NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data) { @@ -1953,6 +2014,16 @@ void DeviceCommissioner::PerformCommissioningStep(DeviceProxy * proxy, Commissio mReadClient = std::move(readClient); } break; + case CommissioningStage::kScanNetworks: { + NetworkCommissioning::Commands::ScanNetworks::Type request; + if (params.GetWiFiCredentials().HasValue()) + { + request.ssid.Emplace(params.GetWiFiCredentials().Value().ssid); + } + request.breadcrumb.Emplace(breadcrumb); + SendCommand(proxy, request, OnScanNetworksResponse, OnScanNetworksFailure, endpoint, timeout); + break; + } case CommissioningStage::kConfigRegulatory: { // To set during config phase: // UTC time diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index 3ac9f77ebfa2d7..0b91ddc3b4a174 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -84,6 +84,7 @@ constexpr uint16_t kNumMaxActiveDevices = CHIP_CONFIG_CONTROLLER_MAX_ACTIVE_DEVI // Raw functions for cluster callbacks void OnBasicFailure(void * context, CHIP_ERROR err); +void OnScanNetworksFailure(void * context, CHIP_ERROR err); struct ControllerInitParams { @@ -764,6 +765,9 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, void * context, const chip::app::Clusters::GeneralCommissioning::Commands::SetRegulatoryConfigResponse::DecodableType & data); static void + OnScanNetworksResponse(void * context, + const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data); + static void OnNetworkConfigResponse(void * context, const chip::app::Clusters::NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data); static void OnConnectNetworkResponse( diff --git a/src/controller/CommissioningDelegate.h b/src/controller/CommissioningDelegate.h index 58cc4131569690..a29e6b218baac7 100644 --- a/src/controller/CommissioningDelegate.h +++ b/src/controller/CommissioningDelegate.h @@ -35,6 +35,7 @@ enum CommissioningStage : uint8_t kSecurePairing, kReadCommissioningInfo, kArmFailsafe, + kScanNetworks, kConfigRegulatory, kSendPAICertificateRequest, kSendDACCertificateRequest, @@ -352,6 +353,20 @@ class CommissioningParameters Credentials::DeviceAttestationDelegate * GetDeviceAttestationDelegate() const { return mDeviceAttestationDelegate; } + bool GetAttemptWiFiNetworkScan() const { return mAttemptWiFiNetworkScan; } + CommissioningParameters & SetAttemptWiFiNetworkScan(bool attemptWiFiNetworkScan) + { + mAttemptWiFiNetworkScan = attemptWiFiNetworkScan; + return *this; + } + + bool GetAttemptThreadNetworkScan() const { return mAttemptThreadNetworkScan; } + CommissioningParameters & SetAttemptThreadNetworkScan(bool attemptThreadNetworkScan) + { + mAttemptThreadNetworkScan = attemptThreadNetworkScan; + return *this; + } + private: // Items that can be set by the commissioner Optional mFailsafeTimerSeconds; @@ -379,6 +394,8 @@ class CommissioningParameters CompletionStatus completionStatus; Credentials::DeviceAttestationDelegate * mDeviceAttestationDelegate = nullptr; // Delegate to handle device attestation failures during commissioning + bool mAttemptWiFiNetworkScan = false; + bool mAttemptThreadNetworkScan = true; // TODO: consider whether default value should be enabled or disabled }; struct RequestedCertificate From 0aec701c51a6c98846ab17b2aee203625ea6e341 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 08:20:23 -0700 Subject: [PATCH 02/28] Add android hooks and callbacks for network scan --- src/controller/AutoCommissioner.cpp | 1 + src/controller/CHIPDeviceController.cpp | 59 ++++- src/controller/CHIPDeviceController.h | 16 +- src/controller/DevicePairingDelegate.h | 14 ++ .../java/AndroidDeviceControllerWrapper.cpp | 227 ++++++++++++++++++ .../java/AndroidDeviceControllerWrapper.h | 12 + .../java/CHIPDeviceController-JNI.cpp | 34 +++ .../ChipDeviceController.java | 59 +++++ 8 files changed, 418 insertions(+), 4 deletions(-) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index e7f5b3c625c880..bec1a73f2355e8 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -177,6 +177,7 @@ CommissioningStage AutoCommissioner::GetNextCommissioningStageInternal(Commissio ChipLogProgress(Controller, "Not a BLE connection, skipping ScanNetworks"); } // fall through if no network scan is called for + FALLTHROUGH; case CommissioningStage::kScanNetworks: return CommissioningStage::kConfigRegulatory; case CommissioningStage::kConfigRegulatory: diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index f9ad570c6d5dcd..ed14e3497cc7d8 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1557,6 +1557,41 @@ void DeviceCommissioner::SendCommissioningCompleteCallbacks(NodeId nodeId, const } } +void DeviceCommissioner::PauseCommissioning() +{ + VerifyOrReturn(mDeviceBeingCommissioned != nullptr); + mCommissioningPaused = true; +} + +void DeviceCommissioner::ResumeCommissioning() +{ + VerifyOrReturn(mCommissioningPaused); + VerifyOrReturn(mDeviceBeingCommissioned != nullptr); + + NodeId nodeId = mDeviceBeingCommissioned->GetDeviceId(); + DeviceProxy * proxy = mDeviceBeingCommissioned; + mDeviceBeingCommissioned = nullptr; + CommissioningDelegate::CommissioningReport report; + + if (mCommissioningDelegate == nullptr) + { + return; + } + report.stageCompleted = mCommissioningStage; + CHIP_ERROR status = mCommissioningDelegate->CommissioningStepFinished(mCommissioningPausedErr, report); + if (status != CHIP_NO_ERROR) + { + // Commissioning delegate will only return error if it failed to perform the appropriate commissioning step. + // In this case, we should complete the commissioning for it. + CompletionStatus completionStatus; + completionStatus.err = status; + completionStatus.failedStage = MakeOptional(report.stageCompleted); + mCommissioningStage = CommissioningStage::kCleanup; + mDeviceBeingCommissioned = proxy; + CleanupCommissioning(proxy, nodeId, completionStatus); + } +} + void DeviceCommissioner::CommissioningStageComplete(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report) { // Once this stage is complete, reset mDeviceBeingCommissioned - this will be reset when the delegate calls the next step. @@ -1569,6 +1604,13 @@ void DeviceCommissioner::CommissioningStageComplete(CHIP_ERROR err, Commissionin { mPairingDelegate->OnCommissioningStatusUpdate(PeerId(GetCompressedFabricId(), nodeId), mCommissioningStage, err); } + + if (mCommissioningPaused) + { + mDeviceBeingCommissioned = proxy; + mCommissioningPausedErr = err; + return; + } if (mCommissioningDelegate == nullptr) { return; @@ -1828,11 +1870,16 @@ void DeviceCommissioner::OnSetRegulatoryConfigResponse( commissioner->CommissioningStageComplete(err, report); } -void OnScanNetworksFailure(void * context, CHIP_ERROR error) +void DeviceCommissioner::OnScanNetworksFailure(void * context, CHIP_ERROR error) { ChipLogProgress(Controller, "Received ScanNetworks failure response %s\n", chip::ErrorStr(error)); - // need to advance to next step + DeviceCommissioner * commissioner = static_cast(context); + if (commissioner->GetPairingDelegate() != nullptr) + { + commissioner->GetPairingDelegate()->OnScanNetworksFailure(error); + } + // need to advance to next step // clear error so that we don't abort the commissioning when ScanNetworks fails commissioner->CommissioningStageComplete(CHIP_NO_ERROR); } @@ -1880,8 +1927,14 @@ void DeviceCommissioner::OnScanNetworksResponse(void * context, ChipLogProgress(Controller, "ScanNetwork response, no Thread results"); } } + DeviceCommissioner * commissioner = static_cast(context); - // clear error so that we don't abort the commissioning when ScanNetworks fails + + if (commissioner->GetPairingDelegate() != nullptr) + { + commissioner->GetPairingDelegate()->OnScanNetworksSuccess(data); + } + // need to advance to next step commissioner->CommissioningStageComplete(CHIP_NO_ERROR); } diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index 0b91ddc3b4a174..bce9ec70e5b02d 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -84,7 +84,6 @@ constexpr uint16_t kNumMaxActiveDevices = CHIP_CONFIG_CONTROLLER_MAX_ACTIVE_DEVI // Raw functions for cluster callbacks void OnBasicFailure(void * context, CHIP_ERROR err); -void OnScanNetworksFailure(void * context, CHIP_ERROR err); struct ControllerInitParams { @@ -561,6 +560,18 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, */ CHIP_ERROR ValidateAttestationInfo(const Credentials::DeviceAttestationVerifier::AttestationInfo & info); + /** + * @brief + * This function puts the commissioner in a paused state to prevent advancing to the next stage. + * It is expected that a DevicePairingDelegate may call this method when processing the + * OnCommissioningStatusUpdate, for example, in order to obtain network credentials from the user based + * upon the results of the NetworkScan. + * Use ResumeCommissioning to continue the commissioning process. + * + */ + void PauseCommissioning(); + void ResumeCommissioning(); + /** * @brief * Sends CommissioningStepComplete report to the commissioning delegate. Function will fill in current step. @@ -767,6 +778,7 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, static void OnScanNetworksResponse(void * context, const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data); + static void OnScanNetworksFailure(void * context, CHIP_ERROR err); static void OnNetworkConfigResponse(void * context, const chip::app::Clusters::NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data); @@ -875,6 +887,8 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, Platform::UniquePtr mReadClient; Credentials::AttestationVerificationResult mAttestationResult; Credentials::DeviceAttestationVerifier * mDeviceAttestationVerifier = nullptr; + bool mCommissioningPaused = false; + CHIP_ERROR mCommissioningPausedErr = CHIP_NO_ERROR; }; } // namespace Controller diff --git a/src/controller/DevicePairingDelegate.h b/src/controller/DevicePairingDelegate.h index 8f89cea7050723..edfefc285079b4 100644 --- a/src/controller/DevicePairingDelegate.h +++ b/src/controller/DevicePairingDelegate.h @@ -75,6 +75,20 @@ class DLL_EXPORT DevicePairingDelegate {} virtual void OnCommissioningStatusUpdate(PeerId peerId, CommissioningStage stageCompleted, CHIP_ERROR error) {} + + /** + * @brief + * Called with the NetworkScanResponse returned from the target + */ + virtual void OnScanNetworksSuccess( + const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) + {} + + /** + * @brief + * Called when the NetworkScan request fails. + */ + virtual void OnScanNetworksFailure(CHIP_ERROR error) {} }; } // namespace Controller diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 9384f29d79b706..3a2b8112c9b197 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -145,6 +145,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( initParams.listenPort = listenPort; setupParams.pairingDelegate = wrapper.get(); setupParams.operationalCredentialsDelegate = opCredsIssuer; + setupParams.defaultCommissioner = &wrapper->mAutoCommissioner; initParams.fabricIndependentStorage = wrapperStorage; wrapper->mGroupDataProvider.SetStorageDelegate(wrapperStorage); @@ -357,6 +358,13 @@ CHIP_ERROR AndroidDeviceControllerWrapper::ApplyNetworkCredentials(chip::Control return err; } +CHIP_ERROR AndroidDeviceControllerWrapper::UpdateNetworkCredentials(chip::Controller::CommissioningParameters & params) +{ + // this will wipe out any custom attestationNonce and csrNonce that was being used. + // however, Android APIs don't allow these to be set to custom values today. + return mAutoCommissioner.SetCommissioningParameters(params); +} + void AndroidDeviceControllerWrapper::OnStatusUpdate(chip::Controller::DevicePairingDelegate::Status status) { chip::DeviceLayer::StackUnlock unlock; @@ -402,6 +410,225 @@ void AndroidDeviceControllerWrapper::OnCommissioningComplete(NodeId deviceId, CH } } +void AndroidDeviceControllerWrapper::OnCommissioningStatusUpdate(PeerId peerId, chip::Controller::CommissioningStage stageCompleted, + CHIP_ERROR error) +{ + chip::DeviceLayer::StackUnlock unlock; + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + jmethodID onCommissioningStatusUpdateMethod; + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onCommissioningStatusUpdate", "(JI)V", + &onCommissioningStatusUpdateMethod); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); + + UtfString jStageCompleted(env, StageToString(stageCompleted)); + env->CallVoidMethod(mJavaObjectRef, onCommissioningStatusUpdateMethod, static_cast(peerId.GetNodeId()), + jStageCompleted.jniValue(), error.AsInteger()); +} + +void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( + const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) +{ + chip::DeviceLayer::StackUnlock unlock; + CHIP_ERROR err = CHIP_NO_ERROR; + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + jmethodID javaMethod; + + VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Error invoking Java callback: no JNIEnv")); + + err = JniReferences::GetInstance().FindMethod( + env, mJavaObjectRef, "onScanNetworksSuccess", + "(Ljava/lang/Integer;Ljava/util/Optional;Ljava/util/Optional;Ljava/util/Optional;)V", &javaMethod); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error invoking Java callback: %s", ErrorStr(err))); + + jobject NetworkingStatus; + std::string NetworkingStatusClassName = "java/lang/Integer"; + std::string NetworkingStatusCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + NetworkingStatusClassName.c_str(), NetworkingStatusCtorSignature.c_str(), + static_cast(dataResponse.networkingStatus), NetworkingStatus); + jobject DebugText; + if (!dataResponse.debugText.HasValue()) + { + chip::JniReferences::GetInstance().CreateOptional(nullptr, DebugText); + } + else + { + jobject DebugTextInsideOptional; + DebugTextInsideOptional = + env->NewStringUTF(std::string(dataResponse.debugText.Value().data(), dataResponse.debugText.Value().size()).c_str()); + chip::JniReferences::GetInstance().CreateOptional(DebugTextInsideOptional, DebugText); + } + jobject WiFiScanResults; + if (!dataResponse.wiFiScanResults.HasValue()) + { + chip::JniReferences::GetInstance().CreateOptional(nullptr, WiFiScanResults); + } + else + { + // TODO: use this + jobject WiFiScanResultsInsideOptional; + chip::JniReferences::GetInstance().CreateArrayList(WiFiScanResultsInsideOptional); + + auto iter_WiFiScanResultsInsideOptional_1 = dataResponse.wiFiScanResults.Value().begin(); + while (iter_WiFiScanResultsInsideOptional_1.Next()) + { + auto & entry_1 = iter_WiFiScanResultsInsideOptional_1.GetValue(); + jobject newElement_1; + jobject newElement_1_security; + std::string newElement_1_securityClassName = "java/lang/Integer"; + std::string newElement_1_securityCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_securityClassName.c_str(), + newElement_1_securityCtorSignature.c_str(), + entry_1.security.Raw(), newElement_1_security); + jobject newElement_1_ssid; + jbyteArray newElement_1_ssidByteArray = env->NewByteArray(static_cast(entry_1.ssid.size())); + env->SetByteArrayRegion(newElement_1_ssidByteArray, 0, static_cast(entry_1.ssid.size()), + reinterpret_cast(entry_1.ssid.data())); + newElement_1_ssid = newElement_1_ssidByteArray; + jobject newElement_1_bssid; + jbyteArray newElement_1_bssidByteArray = env->NewByteArray(static_cast(entry_1.bssid.size())); + env->SetByteArrayRegion(newElement_1_bssidByteArray, 0, static_cast(entry_1.bssid.size()), + reinterpret_cast(entry_1.bssid.data())); + newElement_1_bssid = newElement_1_bssidByteArray; + jobject newElement_1_channel; + std::string newElement_1_channelClassName = "java/lang/Integer"; + std::string newElement_1_channelCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_channelClassName.c_str(), + newElement_1_channelCtorSignature.c_str(), + entry_1.channel, newElement_1_channel); + jobject newElement_1_wiFiBand; + std::string newElement_1_wiFiBandClassName = "java/lang/Integer"; + std::string newElement_1_wiFiBandCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_wiFiBandClassName.c_str(), newElement_1_wiFiBandCtorSignature.c_str(), + static_cast(entry_1.wiFiBand), newElement_1_wiFiBand); + jobject newElement_1_rssi; + std::string newElement_1_rssiClassName = "java/lang/Integer"; + std::string newElement_1_rssiCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_rssiClassName.c_str(), newElement_1_rssiCtorSignature.c_str(), entry_1.rssi, newElement_1_rssi); + + jclass wiFiInterfaceScanResultStructClass_2; + err = chip::JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/ChipStructs$NetworkCommissioningClusterWiFiInterfaceScanResult", + wiFiInterfaceScanResultStructClass_2); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "Could not find class ChipStructs$NetworkCommissioningClusterWiFiInterfaceScanResult"); + return; + } + jmethodID wiFiInterfaceScanResultStructCtor_2 = + env->GetMethodID(wiFiInterfaceScanResultStructClass_2, "", + "(Ljava/lang/Integer;[B[BLjava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;)V"); + if (wiFiInterfaceScanResultStructCtor_2 == nullptr) + { + ChipLogError(Zcl, "Could not find ChipStructs$NetworkCommissioningClusterWiFiInterfaceScanResult constructor"); + return; + } + + newElement_1 = env->NewObject(wiFiInterfaceScanResultStructClass_2, wiFiInterfaceScanResultStructCtor_2, + newElement_1_security, newElement_1_ssid, newElement_1_bssid, newElement_1_channel, + newElement_1_wiFiBand, newElement_1_rssi); + chip::JniReferences::GetInstance().AddToList(WiFiScanResultsInsideOptional, newElement_1); + } + chip::JniReferences::GetInstance().CreateOptional(WiFiScanResultsInsideOptional, WiFiScanResults); + } + jobject ThreadScanResults; + if (!dataResponse.threadScanResults.HasValue()) + { + chip::JniReferences::GetInstance().CreateOptional(nullptr, ThreadScanResults); + } + else + { + jobject ThreadScanResultsInsideOptional; + chip::JniReferences::GetInstance().CreateArrayList(ThreadScanResultsInsideOptional); + + auto iter_ThreadScanResultsInsideOptional_1 = dataResponse.threadScanResults.Value().begin(); + while (iter_ThreadScanResultsInsideOptional_1.Next()) + { + auto & entry_1 = iter_ThreadScanResultsInsideOptional_1.GetValue(); + jobject newElement_1; + jobject newElement_1_panId; + std::string newElement_1_panIdClassName = "java/lang/Integer"; + std::string newElement_1_panIdCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_panIdClassName.c_str(), newElement_1_panIdCtorSignature.c_str(), entry_1.panId, newElement_1_panId); + jobject newElement_1_extendedPanId; + std::string newElement_1_extendedPanIdClassName = "java/lang/Long"; + std::string newElement_1_extendedPanIdCtorSignature = "(J)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_extendedPanIdClassName.c_str(), + newElement_1_extendedPanIdCtorSignature.c_str(), + entry_1.extendedPanId, newElement_1_extendedPanId); + jobject newElement_1_networkName; + newElement_1_networkName = + env->NewStringUTF(std::string(entry_1.networkName.data(), entry_1.networkName.size()).c_str()); + jobject newElement_1_channel; + std::string newElement_1_channelClassName = "java/lang/Integer"; + std::string newElement_1_channelCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_channelClassName.c_str(), + newElement_1_channelCtorSignature.c_str(), + entry_1.channel, newElement_1_channel); + jobject newElement_1_version; + std::string newElement_1_versionClassName = "java/lang/Integer"; + std::string newElement_1_versionCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_versionClassName.c_str(), + newElement_1_versionCtorSignature.c_str(), + entry_1.version, newElement_1_version); + jobject newElement_1_extendedAddress; + jbyteArray newElement_1_extendedAddressByteArray = + env->NewByteArray(static_cast(entry_1.extendedAddress.size())); + env->SetByteArrayRegion(newElement_1_extendedAddressByteArray, 0, static_cast(entry_1.extendedAddress.size()), + reinterpret_cast(entry_1.extendedAddress.data())); + newElement_1_extendedAddress = newElement_1_extendedAddressByteArray; + jobject newElement_1_rssi; + std::string newElement_1_rssiClassName = "java/lang/Integer"; + std::string newElement_1_rssiCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_rssiClassName.c_str(), newElement_1_rssiCtorSignature.c_str(), entry_1.rssi, newElement_1_rssi); + jobject newElement_1_lqi; + std::string newElement_1_lqiClassName = "java/lang/Integer"; + std::string newElement_1_lqiCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_lqiClassName.c_str(), newElement_1_lqiCtorSignature.c_str(), entry_1.lqi, newElement_1_lqi); + + jclass threadInterfaceScanResultStructClass_2; + err = chip::JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/ChipStructs$NetworkCommissioningClusterThreadInterfaceScanResult", + threadInterfaceScanResultStructClass_2); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "Could not find class ChipStructs$NetworkCommissioningClusterThreadInterfaceScanResult"); + return; + } + jmethodID threadInterfaceScanResultStructCtor_2 = + env->GetMethodID(threadInterfaceScanResultStructClass_2, "", + "(Ljava/lang/Integer;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/" + "Integer;[BLjava/lang/Integer;Ljava/lang/Integer;)V"); + if (threadInterfaceScanResultStructCtor_2 == nullptr) + { + ChipLogError(Zcl, "Could not find ChipStructs$NetworkCommissioningClusterThreadInterfaceScanResult constructor"); + return; + } + + newElement_1 = + env->NewObject(threadInterfaceScanResultStructClass_2, threadInterfaceScanResultStructCtor_2, newElement_1_panId, + newElement_1_extendedPanId, newElement_1_networkName, newElement_1_channel, newElement_1_version, + newElement_1_extendedAddress, newElement_1_rssi, newElement_1_lqi); + chip::JniReferences::GetInstance().AddToList(ThreadScanResultsInsideOptional, newElement_1); + } + chip::JniReferences::GetInstance().CreateOptional(ThreadScanResultsInsideOptional, ThreadScanResults); + } + + env->CallVoidMethod(mJavaObjectRef, javaMethod, NetworkingStatus, DebugText, WiFiScanResults, ThreadScanResults); +} + +void AndroidDeviceControllerWrapper::OnScanNetworksFailure(CHIP_ERROR error) +{ + chip::DeviceLayer::StackUnlock unlock; + + CallJavaMethod("onScanNetworksFailure", static_cast(error.AsInteger())); +} + CHIP_ERROR AndroidDeviceControllerWrapper::SyncGetKeyValue(const char * key, void * value, uint16_t & size) { ChipLogProgress(chipTool, "KVS: Getting key %s", key); diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index a8c374ac7ede0f..4c3c78f1a440ed 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -70,11 +70,21 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel */ CHIP_ERROR ApplyNetworkCredentials(chip::Controller::CommissioningParameters & params, jobject networkCredentials); + /** + * Update the network credentials used by the active device commissioner + */ + CHIP_ERROR UpdateNetworkCredentials(chip::Controller::CommissioningParameters & params); + // DevicePairingDelegate implementation void OnStatusUpdate(chip::Controller::DevicePairingDelegate::Status status) override; void OnPairingComplete(CHIP_ERROR error) override; void OnPairingDeleted(CHIP_ERROR error) override; void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR error) override; + void OnCommissioningStatusUpdate(chip::PeerId peerId, chip::Controller::CommissioningStage stageCompleted, + CHIP_ERROR error) override; + void OnScanNetworksSuccess( + const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) override; + void OnScanNetworksFailure(CHIP_ERROR error) override; // PersistentStorageDelegate implementation CHIP_ERROR SyncSetKeyValue(const char * key, const void * value, uint16_t size) override; @@ -146,6 +156,8 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel jbyteArray operationalDatasetBytes = nullptr; jbyte * operationalDataset = nullptr; + chip::Controller::AutoCommissioner mAutoCommissioner; + AndroidDeviceControllerWrapper(ChipDeviceControllerPtr controller, AndroidOperationalCredentialsIssuerPtr opCredsIssuer) : mController(std::move(controller)), mOpCredsIssuer(std::move(opCredsIssuer)) {} diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 5499fee6909a75..90734ed9af2e78 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -378,6 +378,40 @@ JNI_METHOD(void, establishPaseConnectionByAddress) } } +JNI_METHOD(void, pauseCommissioning) +(JNIEnv * env, jobject self, jlong handle) +{ + ChipLogProgress(Controller, "pauseCommissioning() called"); + chip::DeviceLayer::StackLock lock; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + wrapper->Controller()->PauseCommissioning(); +} + +JNI_METHOD(void, resumeCommissioning) +(JNIEnv * env, jobject self, jlong handle) +{ + ChipLogProgress(Controller, "resumeCommissioning() called"); + chip::DeviceLayer::StackLock lock; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + wrapper->Controller()->ResumeCommissioning(); +} + +JNI_METHOD(void, updateCommissioningNetworkCredentials) +(JNIEnv * env, jobject self, jlong handle, jobject networkCredentials) +{ + ChipLogProgress(Controller, "updateCommissioningNetworkCredentials() called"); + chip::DeviceLayer::StackLock lock; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + wrapper->Controller()->ResumeCommissioning(); + + CommissioningParameters commissioningParams = CommissioningParameters(); + wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); + wrapper->UpdateNetworkCredentials(commissioningParams); +} + JNI_METHOD(jbyteArray, convertX509CertToMatterCert) (JNIEnv * env, jobject self, jbyteArray x509Cert) { diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 032f373e424a81..c564b74c397867 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -23,7 +23,9 @@ import chip.devicecontroller.GetConnectedDeviceCallbackJni.GetConnectedDeviceCallback; import chip.devicecontroller.model.ChipAttributePath; import chip.devicecontroller.model.ChipEventPath; +import java.util.ArrayList; import java.util.List; +import java.util.Optional; /** Controller to interact with the CHIP device. */ public class ChipDeviceController { @@ -168,6 +170,19 @@ public void commissionDevice( commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials); } + public void pauseCommissioning() { + pauseCommissioning(deviceControllerPtr); + } + + public void resumeCommissioning() { + resumeCommissioning(deviceControllerPtr); + } + + public void updateCommissioningNetworkCredentials( + NetworkCredentials networkCredentials) { + updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); + } + public void unpairDevice(long deviceId) { unpairDevice(deviceControllerPtr, deviceId); } @@ -220,6 +235,29 @@ public void onCommissioningComplete(long nodeId, int errorCode) { } } + public void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode) { + if (completionListener != null) { + completionListener.onCommissioningStatusUpdate(nodeId, stage, errorCode); + } + } + + public void onScanNetworksFailure(int errorCode) { + if (completionListener != null) { + completionListener.onScanNetworksFailure(errorCode); + } + } + + public void onScanNetworksSuccess(Integer networkingStatus, + Optional debugText, + Optional> + wiFiScanResults, + Optional> + threadScanResults) { + if (completionListener != null) { + completionListener.onScanNetworksSuccess(networkingStatus, debugText, wiFiScanResults, threadScanResults); + } + } + public void onOpCSRGenerationComplete(byte[] csr) { if (completionListener != null) { completionListener.onOpCSRGenerationComplete(csr); @@ -567,6 +605,13 @@ private native boolean openPairingWindowWithPINCallback( private native byte[] getAttestationChallenge(long deviceControllerPtr, long devicePtr); + private native void pauseCommissioning(long deviceControllerPtr); + + private native void resumeCommissioning(long deviceControllerPtr); + + private native void updateCommissioningNetworkCredentials(long deviceControllerPtr, + NetworkCredentials networkCredentials); + private native void shutdownSubscriptions(long deviceControllerPtr, long devicePtr); private native void shutdownCommissioning(long deviceControllerPtr); @@ -603,6 +648,20 @@ public interface CompletionListener { /** Notifies the completion of commissioning. */ void onCommissioningComplete(long nodeId, int errorCode); + /** Notifies the completion of each stage of commissioning. */ + void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode); + + /** Notifies when scan networks call fails. */ + void onScanNetworksFailure(int errorCode); + + void onScanNetworksSuccess( + Integer networkingStatus, + Optional debugText, + Optional> + wiFiScanResults, + Optional> + threadScanResults); + /** Notifies that the Chip connection has been closed. */ void onNotifyChipConnectionClosed(); From 2ec5b411d5c46458ff0101a096c48372fb6c3273 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 11:21:06 -0700 Subject: [PATCH 03/28] Add controller parameters for failsafe timeout, and scans --- src/controller/AutoCommissioner.cpp | 4 +- .../java/AndroidDeviceControllerWrapper.cpp | 8 +++- .../java/AndroidDeviceControllerWrapper.h | 19 ++++++---- .../java/CHIPDeviceController-JNI.cpp | 20 +++++++++- .../devicecontroller/ControllerParams.java | 38 ++++++++++++++++++- 5 files changed, 76 insertions(+), 13 deletions(-) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index bec1a73f2355e8..1fcbf6eb32134a 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -176,8 +176,8 @@ CommissioningStage AutoCommissioner::GetNextCommissioningStageInternal(Commissio { ChipLogProgress(Controller, "Not a BLE connection, skipping ScanNetworks"); } - // fall through if no network scan is called for - FALLTHROUGH; + // skip scan step + return CommissioningStage::kConfigRegulatory; case CommissioningStage::kScanNetworks: return CommissioningStage::kConfigRegulatory; case CommissioningStage::kConfigRegulatory: diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 3a2b8112c9b197..7d38c63e20fa96 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -74,7 +74,8 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( chip::Inet::EndPointManager * tcpEndPointManager, chip::Inet::EndPointManager * udpEndPointManager, AndroidOperationalCredentialsIssuerPtr opCredsIssuerPtr, jobject keypairDelegate, jbyteArray rootCertificate, jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, - jbyteArray ipkEpochKey, uint16_t listenPort, CHIP_ERROR * errInfoOnFailure) + jbyteArray ipkEpochKey, uint16_t listenPort, uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, + bool attemptNetworkScanThread, CHIP_ERROR * errInfoOnFailure) { if (errInfoOnFailure == nullptr) { @@ -150,6 +151,11 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( wrapper->mGroupDataProvider.SetStorageDelegate(wrapperStorage); + CommissioningParameters params = wrapper->mAutoCommissioner.GetCommissioningParameters(); + params.SetFailsafeTimerSeconds(failsafeTimerSeconds); + params.SetAttemptWiFiNetworkScan(attemptNetworkScanWiFi); + params.SetAttemptThreadNetworkScan(attemptNetworkScanThread); + CHIP_ERROR err = wrapper->mGroupDataProvider.Init(); if (err != CHIP_NO_ERROR) { diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 4c3c78f1a440ed..525ed21415502e 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -123,16 +123,19 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel * @param[in] nodeOperationalCertificate an X.509 DER-encoded operational certificate for this node * @param[in] ipkEpochKey the IPK epoch key to use for this node * @param[in] listenPort the UDP port to listen on + * @param[in] failsafeTimerSeconds the failsafe timer in seconds + * @param[in] attemptNetworkScanWiFi whether to attempt a network scan when configuring the network for a WiFi device + * @param[in] attemptNetworkScanThread whether to attempt a network scan when configuring the network for a Thread device * @param[out] errInfoOnFailure a pointer to a CHIP_ERROR that will be populated if this method returns nullptr */ - static AndroidDeviceControllerWrapper * AllocateNew(JavaVM * vm, jobject deviceControllerObj, chip::NodeId nodeId, - const chip::CATValues & cats, chip::System::Layer * systemLayer, - chip::Inet::EndPointManager * tcpEndPointManager, - chip::Inet::EndPointManager * udpEndPointManager, - AndroidOperationalCredentialsIssuerPtr opCredsIssuer, - jobject keypairDelegate, jbyteArray rootCertificate, - jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, - jbyteArray ipkEpochKey, uint16_t listenPort, CHIP_ERROR * errInfoOnFailure); + static AndroidDeviceControllerWrapper * + AllocateNew(JavaVM * vm, jobject deviceControllerObj, chip::NodeId nodeId, const chip::CATValues & cats, + chip::System::Layer * systemLayer, chip::Inet::EndPointManager * tcpEndPointManager, + chip::Inet::EndPointManager * udpEndPointManager, + AndroidOperationalCredentialsIssuerPtr opCredsIssuer, jobject keypairDelegate, jbyteArray rootCertificate, + jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, + uint16_t listenPort, uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, + CHIP_ERROR * errInfoOnFailure); private: using ChipDeviceControllerPtr = std::unique_ptr; diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 90734ed9af2e78..fb8a838f1a6f7c 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -169,6 +169,21 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getUdpListenPort", "()I", &getUdpListenPort); SuccessOrExit(err); + jmethodID getFailsafeTimerSeconds; + err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getFailsafeTimerSeconds", "()I", + &getFailsafeTimerSeconds); + SuccessOrExit(err); + + jmethodID getAttemptNetworkScanWiFi; + err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getAttemptNetworkScanWiFi", "()Z", + &getAttemptNetworkScanWiFi); + SuccessOrExit(err); + + jmethodID getAttemptNetworkScanThread; + err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getAttemptNetworkScanThread", "()Z", + &getAttemptNetworkScanThread); + SuccessOrExit(err); + jmethodID getKeypairDelegate; err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getKeypairDelegate", "()Lchip/devicecontroller/KeypairDelegate;", &getKeypairDelegate); @@ -199,13 +214,16 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr jbyteArray intermediateCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getIntermediateCertificate); jbyteArray operationalCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getOperationalCertificate); jbyteArray ipk = (jbyteArray) env->CallObjectMethod(controllerParams, getIpk); + uint16_t failsafeTimerSeconds = env->CallIntMethod(controllerParams, getFailsafeTimerSeconds); + bool attemptNetworkScanWiFi = env->CallIntMethod(controllerParams, getAttemptNetworkScanWiFi); + bool attemptNetworkScanThread = env->CallIntMethod(controllerParams, getAttemptNetworkScanThread); std::unique_ptr opCredsIssuer( new chip::Controller::AndroidOperationalCredentialsIssuer()); wrapper = AndroidDeviceControllerWrapper::AllocateNew( sJVM, self, kLocalDeviceId, chip::kUndefinedCATs, &DeviceLayer::SystemLayer(), DeviceLayer::TCPEndPointManager(), DeviceLayer::UDPEndPointManager(), std::move(opCredsIssuer), keypairDelegate, rootCertificate, intermediateCertificate, - operationalCertificate, ipk, listenPort, &err); + operationalCertificate, ipk, listenPort, failsafeTimerSeconds, attemptNetworkScanWiFi, attemptNetworkScanThread, &err); SuccessOrExit(err); } diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index ee7f7d09d63faa..e5b0ecb2467b8f 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -11,6 +11,9 @@ public final class ControllerParams { @Nullable private final byte[] intermediateCertificate; @Nullable private final byte[] operationalCertificate; @Nullable private final byte[] ipk; + private final int failsafeTimerSeconds = 30; + private final boolean attemptNetworkScanWiFi = false; + private final boolean attemptNetworkScanThread = true; private static final int LEGACY_GLOBAL_CHIP_PORT = 5540; @@ -49,6 +52,18 @@ public byte[] getIpk() { return ipk; } + public int getFailsafeTimerSeconds() { + return failsafeTimerSeconds; + } + + public boolean getAttemptNetworkScanWiFi() { + return attemptNetworkScanWiFi; + } + + public boolean getAttemptNetworkScanThread() { + return attemptNetworkScanThread; + } + /** Returns parameters with ephemerally generated operational credentials */ public static Builder newBuilder() { return new Builder(); @@ -75,7 +90,10 @@ public static class Builder { @Nullable private byte[] intermediateCertificate = null; @Nullable private byte[] operationalCertificate = null; @Nullable private byte[] ipk = null; - + private int failsafeTimerSeconds = 30; + private boolean attemptNetworkScanWiFi = false; + private boolean attemptNetworkScanThread = true; + private Builder() {} public Builder setUdpListenPort(int udpListenPort) { @@ -86,6 +104,24 @@ public Builder setUdpListenPort(int udpListenPort) { return this; } + public Builder setFailsafeTimerSeconds(int failsafeTimerSeconds) { + if (failsafeTimerSeconds < 1 || failsafeTimerSeconds > 900) { + throw new IllegalArgumentException("failsafeTimerSeconds must be between 0 and 900"); + } + this.failsafeTimerSeconds = failsafeTimerSeconds; + return this; + } + + public Builder setAttemptNetworkScanWiFi(boolean attemptNetworkScanWiFi) { + this.attemptNetworkScanWiFi = attemptNetworkScanWiFi; + return this; + } + + public Builder setAttemptNetworkScanThread(boolean attemptNetworkScanThread) { + this.attemptNetworkScanThread = attemptNetworkScanThread; + return this; + } + public Builder setKeypairDelegate(KeypairDelegate keypairDelegate) { this.keypairDelegate = keypairDelegate; return this; From f01e003a1fb54c47c79ca36bf5f80a3477a6c83b Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 12:25:03 -0700 Subject: [PATCH 04/28] Add callback for ReadCommissioningInfo --- src/controller/DevicePairingDelegate.h | 6 ++++++ .../java/AndroidDeviceControllerWrapper.cpp | 15 +++++++++++++++ .../java/AndroidDeviceControllerWrapper.h | 1 + .../devicecontroller/ChipDeviceController.java | 9 +++++++++ 4 files changed, 31 insertions(+) diff --git a/src/controller/DevicePairingDelegate.h b/src/controller/DevicePairingDelegate.h index edfefc285079b4..9a726dec39459d 100644 --- a/src/controller/DevicePairingDelegate.h +++ b/src/controller/DevicePairingDelegate.h @@ -76,6 +76,12 @@ class DLL_EXPORT DevicePairingDelegate virtual void OnCommissioningStatusUpdate(PeerId peerId, CommissioningStage stageCompleted, CHIP_ERROR error) {} + /** + * @brief + * Called with the ReadCommissioningInfo returned from the target + */ + virtual void OnReadCommissioningInfo(ReadCommissioningInfo info) {} + /** * @brief * Called with the NetworkScanResponse returned from the target diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 7d38c63e20fa96..ef0c2dac884a6d 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -431,6 +431,21 @@ void AndroidDeviceControllerWrapper::OnCommissioningStatusUpdate(PeerId peerId, jStageCompleted.jniValue(), error.AsInteger()); } +void AndroidDeviceControllerWrapper::OnReadCommissioningInfo(chip::Controller::ReadCommissioningInfo info) +{ + // calls: onReadCommissioningInfo(int vendorId, int productId, int wifiEndpointId, int threadEndpointId) + chip::DeviceLayer::StackUnlock unlock; + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + jmethodID onReadCommissioningInfoMethod; + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onReadCommissioningInfo", "(JI)V", + &onReadCommissioningInfoMethod); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); + + env->CallVoidMethod(mJavaObjectRef, onReadCommissioningInfoMethod, static_cast(info.basic.vendorId), + static_cast(info.basic.productId), static_cast(info.network.wifi.endpoint), + static_cast(info.network.thread.endpoint)); +} + void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) { diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 525ed21415502e..965dcd84b60cec 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -82,6 +82,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR error) override; void OnCommissioningStatusUpdate(chip::PeerId peerId, chip::Controller::CommissioningStage stageCompleted, CHIP_ERROR error) override; + void OnReadCommissioningInfo(chip::Controller::ReadCommissioningInfo info) override; void OnScanNetworksSuccess( const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) override; void OnScanNetworksFailure(CHIP_ERROR error) override; diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index c564b74c397867..c2517d92d27338 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -241,6 +241,12 @@ public void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode } } + public void onReadCommissioningInfo(int vendorId, int productId, int wifiEndpointId, int threadEndpointId) { + if (completionListener != null) { + completionListener.onReadCommissioningInfo(vendorId, productId, wifiEndpointId, threadEndpointId); + } + } + public void onScanNetworksFailure(int errorCode) { if (completionListener != null) { completionListener.onScanNetworksFailure(errorCode); @@ -648,6 +654,9 @@ public interface CompletionListener { /** Notifies the completion of commissioning. */ void onCommissioningComplete(long nodeId, int errorCode); + /** Notifies the completion of each stage of commissioning. */ + void onReadCommissioningInfo(int vendorId, int productId, int wifiEndpointId, int threadEndpointId); + /** Notifies the completion of each stage of commissioning. */ void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode); From 9e9a1423219bc56a8fd2f5de1f55f646dba1be6f Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 12:27:53 -0700 Subject: [PATCH 05/28] straggler file --- src/controller/CHIPDeviceController.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index ed14e3497cc7d8..64a3edf83766b9 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1832,6 +1832,13 @@ void DeviceCommissioner::OnDone(app::ReadClient *) } mAttributeCache = nullptr; mReadClient = nullptr; + + // todo - callback for read commissioning info + if (mPairingDelegate != nullptr) + { + mPairingDelegate->OnReadCommissioningInfo(info); + } + CommissioningDelegate::CommissioningReport report; report.Set(info); CommissioningStageComplete(return_err, report); From bd097762e02653ffcdb0b85007b24b779c78a10e Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 13:13:56 -0700 Subject: [PATCH 06/28] address comments --- src/controller/CHIPDeviceController.cpp | 35 ------------------- .../java/CHIPDeviceController-JNI.cpp | 16 ++++++--- .../ChipDeviceController.java | 10 ++++++ 3 files changed, 22 insertions(+), 39 deletions(-) diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 64a3edf83766b9..5f8ceb83383e5d 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1900,41 +1900,6 @@ void DeviceCommissioner::OnScanNetworksResponse(void * context, to_underlying(data.networkingStatus), (data.debugText.HasValue() ? std::string(data.debugText.Value().data(), data.debugText.Value().size()).c_str() : "none provided")); - if (data.networkingStatus == NetworkCommissioning::NetworkCommissioningStatus::kSuccess) - { - if (data.wiFiScanResults.HasValue()) - { - ChipLogProgress(Controller, "ScanNetwork response, has WiFi results"); - - auto iter_WiFiScanResultsInsideOptional_1 = data.wiFiScanResults.Value().begin(); - while (iter_WiFiScanResultsInsideOptional_1.Next()) - { - auto & entry_1 = iter_WiFiScanResultsInsideOptional_1.GetValue(); - ChipLogProgress(Controller, "ScanNetwork response, next WiFi channel=%d", entry_1.channel); - } - } - else - { - ChipLogProgress(Controller, "ScanNetwork response, no WiFi results"); - } - if (data.threadScanResults.HasValue()) - { - ChipLogProgress(Controller, "ScanNetwork response, has Thread results"); - - auto iter_ThreadScanResultsInsideOptional_1 = data.threadScanResults.Value().begin(); - while (iter_ThreadScanResultsInsideOptional_1.Next()) - { - auto & entry_1 = iter_ThreadScanResultsInsideOptional_1.GetValue(); - ChipLogProgress(Controller, "ScanNetwork response, next Thread network name=%s", - std::string(entry_1.networkName.data(), entry_1.networkName.size()).c_str()); - } - } - else - { - ChipLogProgress(Controller, "ScanNetwork response, no Thread results"); - } - } - DeviceCommissioner * commissioner = static_cast(context); if (commissioner->GetPairingDelegate() != nullptr) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index fb8a838f1a6f7c..ed6c8df9aea4b7 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -423,11 +423,19 @@ JNI_METHOD(void, updateCommissioningNetworkCredentials) chip::DeviceLayer::StackLock lock; AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); - wrapper->Controller()->ResumeCommissioning(); - CommissioningParameters commissioningParams = CommissioningParameters(); - wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); - wrapper->UpdateNetworkCredentials(commissioningParams); + CHIP_ERROR err = wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "ApplyNetworkCredentials failed. Err = %" CHIP_ERROR_FORMAT, err.Format()); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } + err = wrapper->UpdateNetworkCredentials(commissioningParams); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "UpdateNetworkCredentials failed. Err = %" CHIP_ERROR_FORMAT, err.Format()); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } } JNI_METHOD(jbyteArray, convertX509CertToMatterCert) diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index c2517d92d27338..49baff89d0be16 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -178,6 +178,16 @@ public void resumeCommissioning() { resumeCommissioning(deviceControllerPtr); } + /** + * Update the network credentials held by the commissioner for the current + * commissioning session. The updated values will be used by the commissioner + * if the network credentials haven't already been sent to the device. + * + * Its expected that this method will be called in response to the NetworkScan + * or the ReadCommissioningInfo callbacks. + * + * @param networkCredentials the credentials (Wi-Fi or Thread) to use in commissioning + */ public void updateCommissioningNetworkCredentials( NetworkCredentials networkCredentials) { updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); From 1b263dfff513b11145e4036977a188d6d4cd2989 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 13:27:04 -0700 Subject: [PATCH 07/28] fix android build --- .../chiptool/GenericChipDeviceListener.kt | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt b/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt index 1d38c9c5c9c244..f1e41d5fe3e43e 100644 --- a/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt +++ b/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt @@ -23,6 +23,26 @@ open class GenericChipDeviceListener : ChipDeviceController.CompletionListener { // No op } + override fun onReadCommissioningInfo(vendorId: Int,productId: Int, wifiEndpointId: Int, threadEndpointId: Int) { + // No op + } + + override fun onCommissioningStatusUpdate(nodeId: Long, stage: String, errorCode: Int) { + // No op + } + + override fun onScanNetworksFailure(errorCode: Int) { + // No op + } + + override fun onScanNetworksSuccess( + networkingStatus: Int, + debugText: Optional, + wiFiScanResults: Optional>, + threadScanResults: Optional>) { + // No op + } + override fun onNotifyChipConnectionClosed() { // No op } From 0a982ebaa3a9ede026d25eac889314cf00a3fe52 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Thu, 14 Jul 2022 14:57:07 -0700 Subject: [PATCH 08/28] DRAFT: add ScanNetworks step to CHIPDeviceController --- src/controller/AutoCommissioner.cpp | 19 +++++++ src/controller/AutoCommissioner.h | 2 + src/controller/CHIPDeviceController.cpp | 71 +++++++++++++++++++++++++ src/controller/CHIPDeviceController.h | 4 ++ src/controller/CommissioningDelegate.h | 17 ++++++ 5 files changed, 113 insertions(+) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index 4ddd081e46ed04..e7f5b3c625c880 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -159,6 +159,25 @@ CommissioningStage AutoCommissioner::GetNextCommissioningStageInternal(Commissio } return CommissioningStage::kArmFailsafe; case CommissioningStage::kArmFailsafe: + if (mNeedsNetworkSetup) + { + // if there is a WiFi or a Thread endpoint, then perform scan + if ((mParams.GetAttemptWiFiNetworkScan() && mDeviceCommissioningInfo.network.wifi.endpoint != kInvalidEndpointId) || + (mParams.GetAttemptThreadNetworkScan() && mDeviceCommissioningInfo.network.thread.endpoint != kInvalidEndpointId)) + { + return CommissioningStage::kScanNetworks; + } + else + { + ChipLogProgress(Controller, "No NetworkScan enabled or WiFi/Thread endpoint not specified, skipping ScanNetworks"); + } + } + else + { + ChipLogProgress(Controller, "Not a BLE connection, skipping ScanNetworks"); + } + // fall through if no network scan is called for + case CommissioningStage::kScanNetworks: return CommissioningStage::kConfigRegulatory; case CommissioningStage::kConfigRegulatory: return CommissioningStage::kSendPAICertificateRequest; diff --git a/src/controller/AutoCommissioner.h b/src/controller/AutoCommissioner.h index b6df47deb6bf64..33bfe350b9fa34 100644 --- a/src/controller/AutoCommissioner.h +++ b/src/controller/AutoCommissioner.h @@ -38,6 +38,8 @@ class AutoCommissioner : public CommissioningDelegate CHIP_ERROR CommissioningStepFinished(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report) override; + ReadCommissioningInfo GetReadCommissioningInfo() const { return mDeviceCommissioningInfo; } + protected: CommissioningStage GetNextCommissioningStage(CommissioningStage currentStage, CHIP_ERROR & lastErr); DeviceCommissioner * GetCommissioner() { return mCommissioner; } diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 8466dc5723a423..f9ad570c6d5dcd 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1724,20 +1724,24 @@ void DeviceCommissioner::OnDone(app::ReadClient *) { if (features.Has(app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kWiFiNetworkInterface)) { + ChipLogError(Controller, "----- NetworkCommissioning Features: has WiFi."); info.network.wifi.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kThreadNetworkInterface)) { + ChipLogError(Controller, "----- NetworkCommissioning Features: has Thread."); info.network.thread.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kEthernetNetworkInterface)) { + ChipLogError(Controller, "----- NetworkCommissioning Features: has Ethernet."); info.network.eth.endpoint = path.mEndpointId; } else { + ChipLogError(Controller, "----- NetworkCommissioning Features: no features."); // TODO: Gross workaround for the empty feature map on all clusters. Remove. if (info.network.thread.endpoint == kInvalidEndpointId) { @@ -1824,6 +1828,63 @@ void DeviceCommissioner::OnSetRegulatoryConfigResponse( commissioner->CommissioningStageComplete(err, report); } +void OnScanNetworksFailure(void * context, CHIP_ERROR error) +{ + ChipLogProgress(Controller, "Received ScanNetworks failure response %s\n", chip::ErrorStr(error)); + // need to advance to next step + DeviceCommissioner * commissioner = static_cast(context); + // clear error so that we don't abort the commissioning when ScanNetworks fails + commissioner->CommissioningStageComplete(CHIP_NO_ERROR); +} + +void DeviceCommissioner::OnScanNetworksResponse(void * context, + const NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data) +{ + CommissioningDelegate::CommissioningReport report; + + ChipLogProgress(Controller, "Received ScanNetwork response, networkingStatus=%u debugText=%s", + to_underlying(data.networkingStatus), + (data.debugText.HasValue() ? std::string(data.debugText.Value().data(), data.debugText.Value().size()).c_str() + : "none provided")); + if (data.networkingStatus == NetworkCommissioning::NetworkCommissioningStatus::kSuccess) + { + if (data.wiFiScanResults.HasValue()) + { + ChipLogProgress(Controller, "ScanNetwork response, has WiFi results"); + + auto iter_WiFiScanResultsInsideOptional_1 = data.wiFiScanResults.Value().begin(); + while (iter_WiFiScanResultsInsideOptional_1.Next()) + { + auto & entry_1 = iter_WiFiScanResultsInsideOptional_1.GetValue(); + ChipLogProgress(Controller, "ScanNetwork response, next WiFi channel=%d", entry_1.channel); + } + } + else + { + ChipLogProgress(Controller, "ScanNetwork response, no WiFi results"); + } + if (data.threadScanResults.HasValue()) + { + ChipLogProgress(Controller, "ScanNetwork response, has Thread results"); + + auto iter_ThreadScanResultsInsideOptional_1 = data.threadScanResults.Value().begin(); + while (iter_ThreadScanResultsInsideOptional_1.Next()) + { + auto & entry_1 = iter_ThreadScanResultsInsideOptional_1.GetValue(); + ChipLogProgress(Controller, "ScanNetwork response, next Thread network name=%s", + std::string(entry_1.networkName.data(), entry_1.networkName.size()).c_str()); + } + } + else + { + ChipLogProgress(Controller, "ScanNetwork response, no Thread results"); + } + } + DeviceCommissioner * commissioner = static_cast(context); + // clear error so that we don't abort the commissioning when ScanNetworks fails + commissioner->CommissioningStageComplete(CHIP_NO_ERROR); +} + void DeviceCommissioner::OnNetworkConfigResponse(void * context, const NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data) { @@ -1953,6 +2014,16 @@ void DeviceCommissioner::PerformCommissioningStep(DeviceProxy * proxy, Commissio mReadClient = std::move(readClient); } break; + case CommissioningStage::kScanNetworks: { + NetworkCommissioning::Commands::ScanNetworks::Type request; + if (params.GetWiFiCredentials().HasValue()) + { + request.ssid.Emplace(params.GetWiFiCredentials().Value().ssid); + } + request.breadcrumb.Emplace(breadcrumb); + SendCommand(proxy, request, OnScanNetworksResponse, OnScanNetworksFailure, endpoint, timeout); + break; + } case CommissioningStage::kConfigRegulatory: { // To set during config phase: // UTC time diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index 3ac9f77ebfa2d7..0b91ddc3b4a174 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -84,6 +84,7 @@ constexpr uint16_t kNumMaxActiveDevices = CHIP_CONFIG_CONTROLLER_MAX_ACTIVE_DEVI // Raw functions for cluster callbacks void OnBasicFailure(void * context, CHIP_ERROR err); +void OnScanNetworksFailure(void * context, CHIP_ERROR err); struct ControllerInitParams { @@ -764,6 +765,9 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, void * context, const chip::app::Clusters::GeneralCommissioning::Commands::SetRegulatoryConfigResponse::DecodableType & data); static void + OnScanNetworksResponse(void * context, + const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data); + static void OnNetworkConfigResponse(void * context, const chip::app::Clusters::NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data); static void OnConnectNetworkResponse( diff --git a/src/controller/CommissioningDelegate.h b/src/controller/CommissioningDelegate.h index 58cc4131569690..a29e6b218baac7 100644 --- a/src/controller/CommissioningDelegate.h +++ b/src/controller/CommissioningDelegate.h @@ -35,6 +35,7 @@ enum CommissioningStage : uint8_t kSecurePairing, kReadCommissioningInfo, kArmFailsafe, + kScanNetworks, kConfigRegulatory, kSendPAICertificateRequest, kSendDACCertificateRequest, @@ -352,6 +353,20 @@ class CommissioningParameters Credentials::DeviceAttestationDelegate * GetDeviceAttestationDelegate() const { return mDeviceAttestationDelegate; } + bool GetAttemptWiFiNetworkScan() const { return mAttemptWiFiNetworkScan; } + CommissioningParameters & SetAttemptWiFiNetworkScan(bool attemptWiFiNetworkScan) + { + mAttemptWiFiNetworkScan = attemptWiFiNetworkScan; + return *this; + } + + bool GetAttemptThreadNetworkScan() const { return mAttemptThreadNetworkScan; } + CommissioningParameters & SetAttemptThreadNetworkScan(bool attemptThreadNetworkScan) + { + mAttemptThreadNetworkScan = attemptThreadNetworkScan; + return *this; + } + private: // Items that can be set by the commissioner Optional mFailsafeTimerSeconds; @@ -379,6 +394,8 @@ class CommissioningParameters CompletionStatus completionStatus; Credentials::DeviceAttestationDelegate * mDeviceAttestationDelegate = nullptr; // Delegate to handle device attestation failures during commissioning + bool mAttemptWiFiNetworkScan = false; + bool mAttemptThreadNetworkScan = true; // TODO: consider whether default value should be enabled or disabled }; struct RequestedCertificate From bfcb784f4a64e629dc775681dfa81cec68167b84 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 08:20:23 -0700 Subject: [PATCH 09/28] Add android hooks and callbacks for network scan --- src/controller/AutoCommissioner.cpp | 1 + src/controller/CHIPDeviceController.cpp | 59 ++++- src/controller/CHIPDeviceController.h | 16 +- src/controller/DevicePairingDelegate.h | 14 ++ .../java/AndroidDeviceControllerWrapper.cpp | 227 ++++++++++++++++++ .../java/AndroidDeviceControllerWrapper.h | 12 + .../java/CHIPDeviceController-JNI.cpp | 34 +++ .../ChipDeviceController.java | 59 +++++ 8 files changed, 418 insertions(+), 4 deletions(-) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index e7f5b3c625c880..bec1a73f2355e8 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -177,6 +177,7 @@ CommissioningStage AutoCommissioner::GetNextCommissioningStageInternal(Commissio ChipLogProgress(Controller, "Not a BLE connection, skipping ScanNetworks"); } // fall through if no network scan is called for + FALLTHROUGH; case CommissioningStage::kScanNetworks: return CommissioningStage::kConfigRegulatory; case CommissioningStage::kConfigRegulatory: diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index f9ad570c6d5dcd..ed14e3497cc7d8 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1557,6 +1557,41 @@ void DeviceCommissioner::SendCommissioningCompleteCallbacks(NodeId nodeId, const } } +void DeviceCommissioner::PauseCommissioning() +{ + VerifyOrReturn(mDeviceBeingCommissioned != nullptr); + mCommissioningPaused = true; +} + +void DeviceCommissioner::ResumeCommissioning() +{ + VerifyOrReturn(mCommissioningPaused); + VerifyOrReturn(mDeviceBeingCommissioned != nullptr); + + NodeId nodeId = mDeviceBeingCommissioned->GetDeviceId(); + DeviceProxy * proxy = mDeviceBeingCommissioned; + mDeviceBeingCommissioned = nullptr; + CommissioningDelegate::CommissioningReport report; + + if (mCommissioningDelegate == nullptr) + { + return; + } + report.stageCompleted = mCommissioningStage; + CHIP_ERROR status = mCommissioningDelegate->CommissioningStepFinished(mCommissioningPausedErr, report); + if (status != CHIP_NO_ERROR) + { + // Commissioning delegate will only return error if it failed to perform the appropriate commissioning step. + // In this case, we should complete the commissioning for it. + CompletionStatus completionStatus; + completionStatus.err = status; + completionStatus.failedStage = MakeOptional(report.stageCompleted); + mCommissioningStage = CommissioningStage::kCleanup; + mDeviceBeingCommissioned = proxy; + CleanupCommissioning(proxy, nodeId, completionStatus); + } +} + void DeviceCommissioner::CommissioningStageComplete(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report) { // Once this stage is complete, reset mDeviceBeingCommissioned - this will be reset when the delegate calls the next step. @@ -1569,6 +1604,13 @@ void DeviceCommissioner::CommissioningStageComplete(CHIP_ERROR err, Commissionin { mPairingDelegate->OnCommissioningStatusUpdate(PeerId(GetCompressedFabricId(), nodeId), mCommissioningStage, err); } + + if (mCommissioningPaused) + { + mDeviceBeingCommissioned = proxy; + mCommissioningPausedErr = err; + return; + } if (mCommissioningDelegate == nullptr) { return; @@ -1828,11 +1870,16 @@ void DeviceCommissioner::OnSetRegulatoryConfigResponse( commissioner->CommissioningStageComplete(err, report); } -void OnScanNetworksFailure(void * context, CHIP_ERROR error) +void DeviceCommissioner::OnScanNetworksFailure(void * context, CHIP_ERROR error) { ChipLogProgress(Controller, "Received ScanNetworks failure response %s\n", chip::ErrorStr(error)); - // need to advance to next step + DeviceCommissioner * commissioner = static_cast(context); + if (commissioner->GetPairingDelegate() != nullptr) + { + commissioner->GetPairingDelegate()->OnScanNetworksFailure(error); + } + // need to advance to next step // clear error so that we don't abort the commissioning when ScanNetworks fails commissioner->CommissioningStageComplete(CHIP_NO_ERROR); } @@ -1880,8 +1927,14 @@ void DeviceCommissioner::OnScanNetworksResponse(void * context, ChipLogProgress(Controller, "ScanNetwork response, no Thread results"); } } + DeviceCommissioner * commissioner = static_cast(context); - // clear error so that we don't abort the commissioning when ScanNetworks fails + + if (commissioner->GetPairingDelegate() != nullptr) + { + commissioner->GetPairingDelegate()->OnScanNetworksSuccess(data); + } + // need to advance to next step commissioner->CommissioningStageComplete(CHIP_NO_ERROR); } diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index 0b91ddc3b4a174..bce9ec70e5b02d 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -84,7 +84,6 @@ constexpr uint16_t kNumMaxActiveDevices = CHIP_CONFIG_CONTROLLER_MAX_ACTIVE_DEVI // Raw functions for cluster callbacks void OnBasicFailure(void * context, CHIP_ERROR err); -void OnScanNetworksFailure(void * context, CHIP_ERROR err); struct ControllerInitParams { @@ -561,6 +560,18 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, */ CHIP_ERROR ValidateAttestationInfo(const Credentials::DeviceAttestationVerifier::AttestationInfo & info); + /** + * @brief + * This function puts the commissioner in a paused state to prevent advancing to the next stage. + * It is expected that a DevicePairingDelegate may call this method when processing the + * OnCommissioningStatusUpdate, for example, in order to obtain network credentials from the user based + * upon the results of the NetworkScan. + * Use ResumeCommissioning to continue the commissioning process. + * + */ + void PauseCommissioning(); + void ResumeCommissioning(); + /** * @brief * Sends CommissioningStepComplete report to the commissioning delegate. Function will fill in current step. @@ -767,6 +778,7 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, static void OnScanNetworksResponse(void * context, const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data); + static void OnScanNetworksFailure(void * context, CHIP_ERROR err); static void OnNetworkConfigResponse(void * context, const chip::app::Clusters::NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data); @@ -875,6 +887,8 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, Platform::UniquePtr mReadClient; Credentials::AttestationVerificationResult mAttestationResult; Credentials::DeviceAttestationVerifier * mDeviceAttestationVerifier = nullptr; + bool mCommissioningPaused = false; + CHIP_ERROR mCommissioningPausedErr = CHIP_NO_ERROR; }; } // namespace Controller diff --git a/src/controller/DevicePairingDelegate.h b/src/controller/DevicePairingDelegate.h index 8f89cea7050723..edfefc285079b4 100644 --- a/src/controller/DevicePairingDelegate.h +++ b/src/controller/DevicePairingDelegate.h @@ -75,6 +75,20 @@ class DLL_EXPORT DevicePairingDelegate {} virtual void OnCommissioningStatusUpdate(PeerId peerId, CommissioningStage stageCompleted, CHIP_ERROR error) {} + + /** + * @brief + * Called with the NetworkScanResponse returned from the target + */ + virtual void OnScanNetworksSuccess( + const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) + {} + + /** + * @brief + * Called when the NetworkScan request fails. + */ + virtual void OnScanNetworksFailure(CHIP_ERROR error) {} }; } // namespace Controller diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 9384f29d79b706..3a2b8112c9b197 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -145,6 +145,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( initParams.listenPort = listenPort; setupParams.pairingDelegate = wrapper.get(); setupParams.operationalCredentialsDelegate = opCredsIssuer; + setupParams.defaultCommissioner = &wrapper->mAutoCommissioner; initParams.fabricIndependentStorage = wrapperStorage; wrapper->mGroupDataProvider.SetStorageDelegate(wrapperStorage); @@ -357,6 +358,13 @@ CHIP_ERROR AndroidDeviceControllerWrapper::ApplyNetworkCredentials(chip::Control return err; } +CHIP_ERROR AndroidDeviceControllerWrapper::UpdateNetworkCredentials(chip::Controller::CommissioningParameters & params) +{ + // this will wipe out any custom attestationNonce and csrNonce that was being used. + // however, Android APIs don't allow these to be set to custom values today. + return mAutoCommissioner.SetCommissioningParameters(params); +} + void AndroidDeviceControllerWrapper::OnStatusUpdate(chip::Controller::DevicePairingDelegate::Status status) { chip::DeviceLayer::StackUnlock unlock; @@ -402,6 +410,225 @@ void AndroidDeviceControllerWrapper::OnCommissioningComplete(NodeId deviceId, CH } } +void AndroidDeviceControllerWrapper::OnCommissioningStatusUpdate(PeerId peerId, chip::Controller::CommissioningStage stageCompleted, + CHIP_ERROR error) +{ + chip::DeviceLayer::StackUnlock unlock; + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + jmethodID onCommissioningStatusUpdateMethod; + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onCommissioningStatusUpdate", "(JI)V", + &onCommissioningStatusUpdateMethod); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); + + UtfString jStageCompleted(env, StageToString(stageCompleted)); + env->CallVoidMethod(mJavaObjectRef, onCommissioningStatusUpdateMethod, static_cast(peerId.GetNodeId()), + jStageCompleted.jniValue(), error.AsInteger()); +} + +void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( + const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) +{ + chip::DeviceLayer::StackUnlock unlock; + CHIP_ERROR err = CHIP_NO_ERROR; + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + jmethodID javaMethod; + + VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Error invoking Java callback: no JNIEnv")); + + err = JniReferences::GetInstance().FindMethod( + env, mJavaObjectRef, "onScanNetworksSuccess", + "(Ljava/lang/Integer;Ljava/util/Optional;Ljava/util/Optional;Ljava/util/Optional;)V", &javaMethod); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error invoking Java callback: %s", ErrorStr(err))); + + jobject NetworkingStatus; + std::string NetworkingStatusClassName = "java/lang/Integer"; + std::string NetworkingStatusCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + NetworkingStatusClassName.c_str(), NetworkingStatusCtorSignature.c_str(), + static_cast(dataResponse.networkingStatus), NetworkingStatus); + jobject DebugText; + if (!dataResponse.debugText.HasValue()) + { + chip::JniReferences::GetInstance().CreateOptional(nullptr, DebugText); + } + else + { + jobject DebugTextInsideOptional; + DebugTextInsideOptional = + env->NewStringUTF(std::string(dataResponse.debugText.Value().data(), dataResponse.debugText.Value().size()).c_str()); + chip::JniReferences::GetInstance().CreateOptional(DebugTextInsideOptional, DebugText); + } + jobject WiFiScanResults; + if (!dataResponse.wiFiScanResults.HasValue()) + { + chip::JniReferences::GetInstance().CreateOptional(nullptr, WiFiScanResults); + } + else + { + // TODO: use this + jobject WiFiScanResultsInsideOptional; + chip::JniReferences::GetInstance().CreateArrayList(WiFiScanResultsInsideOptional); + + auto iter_WiFiScanResultsInsideOptional_1 = dataResponse.wiFiScanResults.Value().begin(); + while (iter_WiFiScanResultsInsideOptional_1.Next()) + { + auto & entry_1 = iter_WiFiScanResultsInsideOptional_1.GetValue(); + jobject newElement_1; + jobject newElement_1_security; + std::string newElement_1_securityClassName = "java/lang/Integer"; + std::string newElement_1_securityCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_securityClassName.c_str(), + newElement_1_securityCtorSignature.c_str(), + entry_1.security.Raw(), newElement_1_security); + jobject newElement_1_ssid; + jbyteArray newElement_1_ssidByteArray = env->NewByteArray(static_cast(entry_1.ssid.size())); + env->SetByteArrayRegion(newElement_1_ssidByteArray, 0, static_cast(entry_1.ssid.size()), + reinterpret_cast(entry_1.ssid.data())); + newElement_1_ssid = newElement_1_ssidByteArray; + jobject newElement_1_bssid; + jbyteArray newElement_1_bssidByteArray = env->NewByteArray(static_cast(entry_1.bssid.size())); + env->SetByteArrayRegion(newElement_1_bssidByteArray, 0, static_cast(entry_1.bssid.size()), + reinterpret_cast(entry_1.bssid.data())); + newElement_1_bssid = newElement_1_bssidByteArray; + jobject newElement_1_channel; + std::string newElement_1_channelClassName = "java/lang/Integer"; + std::string newElement_1_channelCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_channelClassName.c_str(), + newElement_1_channelCtorSignature.c_str(), + entry_1.channel, newElement_1_channel); + jobject newElement_1_wiFiBand; + std::string newElement_1_wiFiBandClassName = "java/lang/Integer"; + std::string newElement_1_wiFiBandCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_wiFiBandClassName.c_str(), newElement_1_wiFiBandCtorSignature.c_str(), + static_cast(entry_1.wiFiBand), newElement_1_wiFiBand); + jobject newElement_1_rssi; + std::string newElement_1_rssiClassName = "java/lang/Integer"; + std::string newElement_1_rssiCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_rssiClassName.c_str(), newElement_1_rssiCtorSignature.c_str(), entry_1.rssi, newElement_1_rssi); + + jclass wiFiInterfaceScanResultStructClass_2; + err = chip::JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/ChipStructs$NetworkCommissioningClusterWiFiInterfaceScanResult", + wiFiInterfaceScanResultStructClass_2); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "Could not find class ChipStructs$NetworkCommissioningClusterWiFiInterfaceScanResult"); + return; + } + jmethodID wiFiInterfaceScanResultStructCtor_2 = + env->GetMethodID(wiFiInterfaceScanResultStructClass_2, "", + "(Ljava/lang/Integer;[B[BLjava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;)V"); + if (wiFiInterfaceScanResultStructCtor_2 == nullptr) + { + ChipLogError(Zcl, "Could not find ChipStructs$NetworkCommissioningClusterWiFiInterfaceScanResult constructor"); + return; + } + + newElement_1 = env->NewObject(wiFiInterfaceScanResultStructClass_2, wiFiInterfaceScanResultStructCtor_2, + newElement_1_security, newElement_1_ssid, newElement_1_bssid, newElement_1_channel, + newElement_1_wiFiBand, newElement_1_rssi); + chip::JniReferences::GetInstance().AddToList(WiFiScanResultsInsideOptional, newElement_1); + } + chip::JniReferences::GetInstance().CreateOptional(WiFiScanResultsInsideOptional, WiFiScanResults); + } + jobject ThreadScanResults; + if (!dataResponse.threadScanResults.HasValue()) + { + chip::JniReferences::GetInstance().CreateOptional(nullptr, ThreadScanResults); + } + else + { + jobject ThreadScanResultsInsideOptional; + chip::JniReferences::GetInstance().CreateArrayList(ThreadScanResultsInsideOptional); + + auto iter_ThreadScanResultsInsideOptional_1 = dataResponse.threadScanResults.Value().begin(); + while (iter_ThreadScanResultsInsideOptional_1.Next()) + { + auto & entry_1 = iter_ThreadScanResultsInsideOptional_1.GetValue(); + jobject newElement_1; + jobject newElement_1_panId; + std::string newElement_1_panIdClassName = "java/lang/Integer"; + std::string newElement_1_panIdCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_panIdClassName.c_str(), newElement_1_panIdCtorSignature.c_str(), entry_1.panId, newElement_1_panId); + jobject newElement_1_extendedPanId; + std::string newElement_1_extendedPanIdClassName = "java/lang/Long"; + std::string newElement_1_extendedPanIdCtorSignature = "(J)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_extendedPanIdClassName.c_str(), + newElement_1_extendedPanIdCtorSignature.c_str(), + entry_1.extendedPanId, newElement_1_extendedPanId); + jobject newElement_1_networkName; + newElement_1_networkName = + env->NewStringUTF(std::string(entry_1.networkName.data(), entry_1.networkName.size()).c_str()); + jobject newElement_1_channel; + std::string newElement_1_channelClassName = "java/lang/Integer"; + std::string newElement_1_channelCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_channelClassName.c_str(), + newElement_1_channelCtorSignature.c_str(), + entry_1.channel, newElement_1_channel); + jobject newElement_1_version; + std::string newElement_1_versionClassName = "java/lang/Integer"; + std::string newElement_1_versionCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_versionClassName.c_str(), + newElement_1_versionCtorSignature.c_str(), + entry_1.version, newElement_1_version); + jobject newElement_1_extendedAddress; + jbyteArray newElement_1_extendedAddressByteArray = + env->NewByteArray(static_cast(entry_1.extendedAddress.size())); + env->SetByteArrayRegion(newElement_1_extendedAddressByteArray, 0, static_cast(entry_1.extendedAddress.size()), + reinterpret_cast(entry_1.extendedAddress.data())); + newElement_1_extendedAddress = newElement_1_extendedAddressByteArray; + jobject newElement_1_rssi; + std::string newElement_1_rssiClassName = "java/lang/Integer"; + std::string newElement_1_rssiCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_rssiClassName.c_str(), newElement_1_rssiCtorSignature.c_str(), entry_1.rssi, newElement_1_rssi); + jobject newElement_1_lqi; + std::string newElement_1_lqiClassName = "java/lang/Integer"; + std::string newElement_1_lqiCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_1_lqiClassName.c_str(), newElement_1_lqiCtorSignature.c_str(), entry_1.lqi, newElement_1_lqi); + + jclass threadInterfaceScanResultStructClass_2; + err = chip::JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/ChipStructs$NetworkCommissioningClusterThreadInterfaceScanResult", + threadInterfaceScanResultStructClass_2); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "Could not find class ChipStructs$NetworkCommissioningClusterThreadInterfaceScanResult"); + return; + } + jmethodID threadInterfaceScanResultStructCtor_2 = + env->GetMethodID(threadInterfaceScanResultStructClass_2, "", + "(Ljava/lang/Integer;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/" + "Integer;[BLjava/lang/Integer;Ljava/lang/Integer;)V"); + if (threadInterfaceScanResultStructCtor_2 == nullptr) + { + ChipLogError(Zcl, "Could not find ChipStructs$NetworkCommissioningClusterThreadInterfaceScanResult constructor"); + return; + } + + newElement_1 = + env->NewObject(threadInterfaceScanResultStructClass_2, threadInterfaceScanResultStructCtor_2, newElement_1_panId, + newElement_1_extendedPanId, newElement_1_networkName, newElement_1_channel, newElement_1_version, + newElement_1_extendedAddress, newElement_1_rssi, newElement_1_lqi); + chip::JniReferences::GetInstance().AddToList(ThreadScanResultsInsideOptional, newElement_1); + } + chip::JniReferences::GetInstance().CreateOptional(ThreadScanResultsInsideOptional, ThreadScanResults); + } + + env->CallVoidMethod(mJavaObjectRef, javaMethod, NetworkingStatus, DebugText, WiFiScanResults, ThreadScanResults); +} + +void AndroidDeviceControllerWrapper::OnScanNetworksFailure(CHIP_ERROR error) +{ + chip::DeviceLayer::StackUnlock unlock; + + CallJavaMethod("onScanNetworksFailure", static_cast(error.AsInteger())); +} + CHIP_ERROR AndroidDeviceControllerWrapper::SyncGetKeyValue(const char * key, void * value, uint16_t & size) { ChipLogProgress(chipTool, "KVS: Getting key %s", key); diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index a8c374ac7ede0f..4c3c78f1a440ed 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -70,11 +70,21 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel */ CHIP_ERROR ApplyNetworkCredentials(chip::Controller::CommissioningParameters & params, jobject networkCredentials); + /** + * Update the network credentials used by the active device commissioner + */ + CHIP_ERROR UpdateNetworkCredentials(chip::Controller::CommissioningParameters & params); + // DevicePairingDelegate implementation void OnStatusUpdate(chip::Controller::DevicePairingDelegate::Status status) override; void OnPairingComplete(CHIP_ERROR error) override; void OnPairingDeleted(CHIP_ERROR error) override; void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR error) override; + void OnCommissioningStatusUpdate(chip::PeerId peerId, chip::Controller::CommissioningStage stageCompleted, + CHIP_ERROR error) override; + void OnScanNetworksSuccess( + const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) override; + void OnScanNetworksFailure(CHIP_ERROR error) override; // PersistentStorageDelegate implementation CHIP_ERROR SyncSetKeyValue(const char * key, const void * value, uint16_t size) override; @@ -146,6 +156,8 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel jbyteArray operationalDatasetBytes = nullptr; jbyte * operationalDataset = nullptr; + chip::Controller::AutoCommissioner mAutoCommissioner; + AndroidDeviceControllerWrapper(ChipDeviceControllerPtr controller, AndroidOperationalCredentialsIssuerPtr opCredsIssuer) : mController(std::move(controller)), mOpCredsIssuer(std::move(opCredsIssuer)) {} diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 5499fee6909a75..90734ed9af2e78 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -378,6 +378,40 @@ JNI_METHOD(void, establishPaseConnectionByAddress) } } +JNI_METHOD(void, pauseCommissioning) +(JNIEnv * env, jobject self, jlong handle) +{ + ChipLogProgress(Controller, "pauseCommissioning() called"); + chip::DeviceLayer::StackLock lock; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + wrapper->Controller()->PauseCommissioning(); +} + +JNI_METHOD(void, resumeCommissioning) +(JNIEnv * env, jobject self, jlong handle) +{ + ChipLogProgress(Controller, "resumeCommissioning() called"); + chip::DeviceLayer::StackLock lock; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + wrapper->Controller()->ResumeCommissioning(); +} + +JNI_METHOD(void, updateCommissioningNetworkCredentials) +(JNIEnv * env, jobject self, jlong handle, jobject networkCredentials) +{ + ChipLogProgress(Controller, "updateCommissioningNetworkCredentials() called"); + chip::DeviceLayer::StackLock lock; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + wrapper->Controller()->ResumeCommissioning(); + + CommissioningParameters commissioningParams = CommissioningParameters(); + wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); + wrapper->UpdateNetworkCredentials(commissioningParams); +} + JNI_METHOD(jbyteArray, convertX509CertToMatterCert) (JNIEnv * env, jobject self, jbyteArray x509Cert) { diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 032f373e424a81..c564b74c397867 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -23,7 +23,9 @@ import chip.devicecontroller.GetConnectedDeviceCallbackJni.GetConnectedDeviceCallback; import chip.devicecontroller.model.ChipAttributePath; import chip.devicecontroller.model.ChipEventPath; +import java.util.ArrayList; import java.util.List; +import java.util.Optional; /** Controller to interact with the CHIP device. */ public class ChipDeviceController { @@ -168,6 +170,19 @@ public void commissionDevice( commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials); } + public void pauseCommissioning() { + pauseCommissioning(deviceControllerPtr); + } + + public void resumeCommissioning() { + resumeCommissioning(deviceControllerPtr); + } + + public void updateCommissioningNetworkCredentials( + NetworkCredentials networkCredentials) { + updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); + } + public void unpairDevice(long deviceId) { unpairDevice(deviceControllerPtr, deviceId); } @@ -220,6 +235,29 @@ public void onCommissioningComplete(long nodeId, int errorCode) { } } + public void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode) { + if (completionListener != null) { + completionListener.onCommissioningStatusUpdate(nodeId, stage, errorCode); + } + } + + public void onScanNetworksFailure(int errorCode) { + if (completionListener != null) { + completionListener.onScanNetworksFailure(errorCode); + } + } + + public void onScanNetworksSuccess(Integer networkingStatus, + Optional debugText, + Optional> + wiFiScanResults, + Optional> + threadScanResults) { + if (completionListener != null) { + completionListener.onScanNetworksSuccess(networkingStatus, debugText, wiFiScanResults, threadScanResults); + } + } + public void onOpCSRGenerationComplete(byte[] csr) { if (completionListener != null) { completionListener.onOpCSRGenerationComplete(csr); @@ -567,6 +605,13 @@ private native boolean openPairingWindowWithPINCallback( private native byte[] getAttestationChallenge(long deviceControllerPtr, long devicePtr); + private native void pauseCommissioning(long deviceControllerPtr); + + private native void resumeCommissioning(long deviceControllerPtr); + + private native void updateCommissioningNetworkCredentials(long deviceControllerPtr, + NetworkCredentials networkCredentials); + private native void shutdownSubscriptions(long deviceControllerPtr, long devicePtr); private native void shutdownCommissioning(long deviceControllerPtr); @@ -603,6 +648,20 @@ public interface CompletionListener { /** Notifies the completion of commissioning. */ void onCommissioningComplete(long nodeId, int errorCode); + /** Notifies the completion of each stage of commissioning. */ + void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode); + + /** Notifies when scan networks call fails. */ + void onScanNetworksFailure(int errorCode); + + void onScanNetworksSuccess( + Integer networkingStatus, + Optional debugText, + Optional> + wiFiScanResults, + Optional> + threadScanResults); + /** Notifies that the Chip connection has been closed. */ void onNotifyChipConnectionClosed(); From cfd3351097c387cb99c754c0eccdc3772d3bef8c Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 11:21:06 -0700 Subject: [PATCH 10/28] Add controller parameters for failsafe timeout, and scans --- src/controller/AutoCommissioner.cpp | 4 +- .../java/AndroidDeviceControllerWrapper.cpp | 8 +++- .../java/AndroidDeviceControllerWrapper.h | 19 ++++++---- .../java/CHIPDeviceController-JNI.cpp | 20 +++++++++- .../devicecontroller/ControllerParams.java | 38 ++++++++++++++++++- 5 files changed, 76 insertions(+), 13 deletions(-) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index bec1a73f2355e8..1fcbf6eb32134a 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -176,8 +176,8 @@ CommissioningStage AutoCommissioner::GetNextCommissioningStageInternal(Commissio { ChipLogProgress(Controller, "Not a BLE connection, skipping ScanNetworks"); } - // fall through if no network scan is called for - FALLTHROUGH; + // skip scan step + return CommissioningStage::kConfigRegulatory; case CommissioningStage::kScanNetworks: return CommissioningStage::kConfigRegulatory; case CommissioningStage::kConfigRegulatory: diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 3a2b8112c9b197..7d38c63e20fa96 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -74,7 +74,8 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( chip::Inet::EndPointManager * tcpEndPointManager, chip::Inet::EndPointManager * udpEndPointManager, AndroidOperationalCredentialsIssuerPtr opCredsIssuerPtr, jobject keypairDelegate, jbyteArray rootCertificate, jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, - jbyteArray ipkEpochKey, uint16_t listenPort, CHIP_ERROR * errInfoOnFailure) + jbyteArray ipkEpochKey, uint16_t listenPort, uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, + bool attemptNetworkScanThread, CHIP_ERROR * errInfoOnFailure) { if (errInfoOnFailure == nullptr) { @@ -150,6 +151,11 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( wrapper->mGroupDataProvider.SetStorageDelegate(wrapperStorage); + CommissioningParameters params = wrapper->mAutoCommissioner.GetCommissioningParameters(); + params.SetFailsafeTimerSeconds(failsafeTimerSeconds); + params.SetAttemptWiFiNetworkScan(attemptNetworkScanWiFi); + params.SetAttemptThreadNetworkScan(attemptNetworkScanThread); + CHIP_ERROR err = wrapper->mGroupDataProvider.Init(); if (err != CHIP_NO_ERROR) { diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 4c3c78f1a440ed..525ed21415502e 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -123,16 +123,19 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel * @param[in] nodeOperationalCertificate an X.509 DER-encoded operational certificate for this node * @param[in] ipkEpochKey the IPK epoch key to use for this node * @param[in] listenPort the UDP port to listen on + * @param[in] failsafeTimerSeconds the failsafe timer in seconds + * @param[in] attemptNetworkScanWiFi whether to attempt a network scan when configuring the network for a WiFi device + * @param[in] attemptNetworkScanThread whether to attempt a network scan when configuring the network for a Thread device * @param[out] errInfoOnFailure a pointer to a CHIP_ERROR that will be populated if this method returns nullptr */ - static AndroidDeviceControllerWrapper * AllocateNew(JavaVM * vm, jobject deviceControllerObj, chip::NodeId nodeId, - const chip::CATValues & cats, chip::System::Layer * systemLayer, - chip::Inet::EndPointManager * tcpEndPointManager, - chip::Inet::EndPointManager * udpEndPointManager, - AndroidOperationalCredentialsIssuerPtr opCredsIssuer, - jobject keypairDelegate, jbyteArray rootCertificate, - jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, - jbyteArray ipkEpochKey, uint16_t listenPort, CHIP_ERROR * errInfoOnFailure); + static AndroidDeviceControllerWrapper * + AllocateNew(JavaVM * vm, jobject deviceControllerObj, chip::NodeId nodeId, const chip::CATValues & cats, + chip::System::Layer * systemLayer, chip::Inet::EndPointManager * tcpEndPointManager, + chip::Inet::EndPointManager * udpEndPointManager, + AndroidOperationalCredentialsIssuerPtr opCredsIssuer, jobject keypairDelegate, jbyteArray rootCertificate, + jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, + uint16_t listenPort, uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, + CHIP_ERROR * errInfoOnFailure); private: using ChipDeviceControllerPtr = std::unique_ptr; diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 90734ed9af2e78..fb8a838f1a6f7c 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -169,6 +169,21 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getUdpListenPort", "()I", &getUdpListenPort); SuccessOrExit(err); + jmethodID getFailsafeTimerSeconds; + err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getFailsafeTimerSeconds", "()I", + &getFailsafeTimerSeconds); + SuccessOrExit(err); + + jmethodID getAttemptNetworkScanWiFi; + err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getAttemptNetworkScanWiFi", "()Z", + &getAttemptNetworkScanWiFi); + SuccessOrExit(err); + + jmethodID getAttemptNetworkScanThread; + err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getAttemptNetworkScanThread", "()Z", + &getAttemptNetworkScanThread); + SuccessOrExit(err); + jmethodID getKeypairDelegate; err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getKeypairDelegate", "()Lchip/devicecontroller/KeypairDelegate;", &getKeypairDelegate); @@ -199,13 +214,16 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr jbyteArray intermediateCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getIntermediateCertificate); jbyteArray operationalCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getOperationalCertificate); jbyteArray ipk = (jbyteArray) env->CallObjectMethod(controllerParams, getIpk); + uint16_t failsafeTimerSeconds = env->CallIntMethod(controllerParams, getFailsafeTimerSeconds); + bool attemptNetworkScanWiFi = env->CallIntMethod(controllerParams, getAttemptNetworkScanWiFi); + bool attemptNetworkScanThread = env->CallIntMethod(controllerParams, getAttemptNetworkScanThread); std::unique_ptr opCredsIssuer( new chip::Controller::AndroidOperationalCredentialsIssuer()); wrapper = AndroidDeviceControllerWrapper::AllocateNew( sJVM, self, kLocalDeviceId, chip::kUndefinedCATs, &DeviceLayer::SystemLayer(), DeviceLayer::TCPEndPointManager(), DeviceLayer::UDPEndPointManager(), std::move(opCredsIssuer), keypairDelegate, rootCertificate, intermediateCertificate, - operationalCertificate, ipk, listenPort, &err); + operationalCertificate, ipk, listenPort, failsafeTimerSeconds, attemptNetworkScanWiFi, attemptNetworkScanThread, &err); SuccessOrExit(err); } diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index ee7f7d09d63faa..e5b0ecb2467b8f 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -11,6 +11,9 @@ public final class ControllerParams { @Nullable private final byte[] intermediateCertificate; @Nullable private final byte[] operationalCertificate; @Nullable private final byte[] ipk; + private final int failsafeTimerSeconds = 30; + private final boolean attemptNetworkScanWiFi = false; + private final boolean attemptNetworkScanThread = true; private static final int LEGACY_GLOBAL_CHIP_PORT = 5540; @@ -49,6 +52,18 @@ public byte[] getIpk() { return ipk; } + public int getFailsafeTimerSeconds() { + return failsafeTimerSeconds; + } + + public boolean getAttemptNetworkScanWiFi() { + return attemptNetworkScanWiFi; + } + + public boolean getAttemptNetworkScanThread() { + return attemptNetworkScanThread; + } + /** Returns parameters with ephemerally generated operational credentials */ public static Builder newBuilder() { return new Builder(); @@ -75,7 +90,10 @@ public static class Builder { @Nullable private byte[] intermediateCertificate = null; @Nullable private byte[] operationalCertificate = null; @Nullable private byte[] ipk = null; - + private int failsafeTimerSeconds = 30; + private boolean attemptNetworkScanWiFi = false; + private boolean attemptNetworkScanThread = true; + private Builder() {} public Builder setUdpListenPort(int udpListenPort) { @@ -86,6 +104,24 @@ public Builder setUdpListenPort(int udpListenPort) { return this; } + public Builder setFailsafeTimerSeconds(int failsafeTimerSeconds) { + if (failsafeTimerSeconds < 1 || failsafeTimerSeconds > 900) { + throw new IllegalArgumentException("failsafeTimerSeconds must be between 0 and 900"); + } + this.failsafeTimerSeconds = failsafeTimerSeconds; + return this; + } + + public Builder setAttemptNetworkScanWiFi(boolean attemptNetworkScanWiFi) { + this.attemptNetworkScanWiFi = attemptNetworkScanWiFi; + return this; + } + + public Builder setAttemptNetworkScanThread(boolean attemptNetworkScanThread) { + this.attemptNetworkScanThread = attemptNetworkScanThread; + return this; + } + public Builder setKeypairDelegate(KeypairDelegate keypairDelegate) { this.keypairDelegate = keypairDelegate; return this; From 4bcd7c42338a877678c0748dec7d781c7d82dd28 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 12:25:03 -0700 Subject: [PATCH 11/28] Add callback for ReadCommissioningInfo --- src/controller/DevicePairingDelegate.h | 6 ++++++ .../java/AndroidDeviceControllerWrapper.cpp | 15 +++++++++++++++ .../java/AndroidDeviceControllerWrapper.h | 1 + .../devicecontroller/ChipDeviceController.java | 9 +++++++++ 4 files changed, 31 insertions(+) diff --git a/src/controller/DevicePairingDelegate.h b/src/controller/DevicePairingDelegate.h index edfefc285079b4..9a726dec39459d 100644 --- a/src/controller/DevicePairingDelegate.h +++ b/src/controller/DevicePairingDelegate.h @@ -76,6 +76,12 @@ class DLL_EXPORT DevicePairingDelegate virtual void OnCommissioningStatusUpdate(PeerId peerId, CommissioningStage stageCompleted, CHIP_ERROR error) {} + /** + * @brief + * Called with the ReadCommissioningInfo returned from the target + */ + virtual void OnReadCommissioningInfo(ReadCommissioningInfo info) {} + /** * @brief * Called with the NetworkScanResponse returned from the target diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 7d38c63e20fa96..ef0c2dac884a6d 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -431,6 +431,21 @@ void AndroidDeviceControllerWrapper::OnCommissioningStatusUpdate(PeerId peerId, jStageCompleted.jniValue(), error.AsInteger()); } +void AndroidDeviceControllerWrapper::OnReadCommissioningInfo(chip::Controller::ReadCommissioningInfo info) +{ + // calls: onReadCommissioningInfo(int vendorId, int productId, int wifiEndpointId, int threadEndpointId) + chip::DeviceLayer::StackUnlock unlock; + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + jmethodID onReadCommissioningInfoMethod; + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onReadCommissioningInfo", "(JI)V", + &onReadCommissioningInfoMethod); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); + + env->CallVoidMethod(mJavaObjectRef, onReadCommissioningInfoMethod, static_cast(info.basic.vendorId), + static_cast(info.basic.productId), static_cast(info.network.wifi.endpoint), + static_cast(info.network.thread.endpoint)); +} + void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) { diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 525ed21415502e..965dcd84b60cec 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -82,6 +82,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR error) override; void OnCommissioningStatusUpdate(chip::PeerId peerId, chip::Controller::CommissioningStage stageCompleted, CHIP_ERROR error) override; + void OnReadCommissioningInfo(chip::Controller::ReadCommissioningInfo info) override; void OnScanNetworksSuccess( const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) override; void OnScanNetworksFailure(CHIP_ERROR error) override; diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index c564b74c397867..c2517d92d27338 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -241,6 +241,12 @@ public void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode } } + public void onReadCommissioningInfo(int vendorId, int productId, int wifiEndpointId, int threadEndpointId) { + if (completionListener != null) { + completionListener.onReadCommissioningInfo(vendorId, productId, wifiEndpointId, threadEndpointId); + } + } + public void onScanNetworksFailure(int errorCode) { if (completionListener != null) { completionListener.onScanNetworksFailure(errorCode); @@ -648,6 +654,9 @@ public interface CompletionListener { /** Notifies the completion of commissioning. */ void onCommissioningComplete(long nodeId, int errorCode); + /** Notifies the completion of each stage of commissioning. */ + void onReadCommissioningInfo(int vendorId, int productId, int wifiEndpointId, int threadEndpointId); + /** Notifies the completion of each stage of commissioning. */ void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode); From 756ac8fcabf0a029bf6be6d2cc8e7fcd23bef6a9 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 12:27:53 -0700 Subject: [PATCH 12/28] straggler file --- src/controller/CHIPDeviceController.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index ed14e3497cc7d8..64a3edf83766b9 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1832,6 +1832,13 @@ void DeviceCommissioner::OnDone(app::ReadClient *) } mAttributeCache = nullptr; mReadClient = nullptr; + + // todo - callback for read commissioning info + if (mPairingDelegate != nullptr) + { + mPairingDelegate->OnReadCommissioningInfo(info); + } + CommissioningDelegate::CommissioningReport report; report.Set(info); CommissioningStageComplete(return_err, report); From ac0327f81dfd9cb6a1033cfc934f525b6985595e Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 13:13:56 -0700 Subject: [PATCH 13/28] address comments --- src/controller/CHIPDeviceController.cpp | 35 ------------------- .../java/CHIPDeviceController-JNI.cpp | 16 ++++++--- .../ChipDeviceController.java | 10 ++++++ 3 files changed, 22 insertions(+), 39 deletions(-) diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 64a3edf83766b9..5f8ceb83383e5d 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1900,41 +1900,6 @@ void DeviceCommissioner::OnScanNetworksResponse(void * context, to_underlying(data.networkingStatus), (data.debugText.HasValue() ? std::string(data.debugText.Value().data(), data.debugText.Value().size()).c_str() : "none provided")); - if (data.networkingStatus == NetworkCommissioning::NetworkCommissioningStatus::kSuccess) - { - if (data.wiFiScanResults.HasValue()) - { - ChipLogProgress(Controller, "ScanNetwork response, has WiFi results"); - - auto iter_WiFiScanResultsInsideOptional_1 = data.wiFiScanResults.Value().begin(); - while (iter_WiFiScanResultsInsideOptional_1.Next()) - { - auto & entry_1 = iter_WiFiScanResultsInsideOptional_1.GetValue(); - ChipLogProgress(Controller, "ScanNetwork response, next WiFi channel=%d", entry_1.channel); - } - } - else - { - ChipLogProgress(Controller, "ScanNetwork response, no WiFi results"); - } - if (data.threadScanResults.HasValue()) - { - ChipLogProgress(Controller, "ScanNetwork response, has Thread results"); - - auto iter_ThreadScanResultsInsideOptional_1 = data.threadScanResults.Value().begin(); - while (iter_ThreadScanResultsInsideOptional_1.Next()) - { - auto & entry_1 = iter_ThreadScanResultsInsideOptional_1.GetValue(); - ChipLogProgress(Controller, "ScanNetwork response, next Thread network name=%s", - std::string(entry_1.networkName.data(), entry_1.networkName.size()).c_str()); - } - } - else - { - ChipLogProgress(Controller, "ScanNetwork response, no Thread results"); - } - } - DeviceCommissioner * commissioner = static_cast(context); if (commissioner->GetPairingDelegate() != nullptr) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index fb8a838f1a6f7c..ed6c8df9aea4b7 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -423,11 +423,19 @@ JNI_METHOD(void, updateCommissioningNetworkCredentials) chip::DeviceLayer::StackLock lock; AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); - wrapper->Controller()->ResumeCommissioning(); - CommissioningParameters commissioningParams = CommissioningParameters(); - wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); - wrapper->UpdateNetworkCredentials(commissioningParams); + CHIP_ERROR err = wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "ApplyNetworkCredentials failed. Err = %" CHIP_ERROR_FORMAT, err.Format()); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } + err = wrapper->UpdateNetworkCredentials(commissioningParams); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "UpdateNetworkCredentials failed. Err = %" CHIP_ERROR_FORMAT, err.Format()); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } } JNI_METHOD(jbyteArray, convertX509CertToMatterCert) diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index c2517d92d27338..49baff89d0be16 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -178,6 +178,16 @@ public void resumeCommissioning() { resumeCommissioning(deviceControllerPtr); } + /** + * Update the network credentials held by the commissioner for the current + * commissioning session. The updated values will be used by the commissioner + * if the network credentials haven't already been sent to the device. + * + * Its expected that this method will be called in response to the NetworkScan + * or the ReadCommissioningInfo callbacks. + * + * @param networkCredentials the credentials (Wi-Fi or Thread) to use in commissioning + */ public void updateCommissioningNetworkCredentials( NetworkCredentials networkCredentials) { updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); From b7b58b3573395abc3cf3c130773f3285b9f7ea1a Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Fri, 15 Jul 2022 13:27:04 -0700 Subject: [PATCH 14/28] fix android build --- .../chiptool/GenericChipDeviceListener.kt | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt b/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt index 1d38c9c5c9c244..f1e41d5fe3e43e 100644 --- a/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt +++ b/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt @@ -23,6 +23,26 @@ open class GenericChipDeviceListener : ChipDeviceController.CompletionListener { // No op } + override fun onReadCommissioningInfo(vendorId: Int,productId: Int, wifiEndpointId: Int, threadEndpointId: Int) { + // No op + } + + override fun onCommissioningStatusUpdate(nodeId: Long, stage: String, errorCode: Int) { + // No op + } + + override fun onScanNetworksFailure(errorCode: Int) { + // No op + } + + override fun onScanNetworksSuccess( + networkingStatus: Int, + debugText: Optional, + wiFiScanResults: Optional>, + threadScanResults: Optional>) { + // No op + } + override fun onNotifyChipConnectionClosed() { // No op } From 4a4b93b4872ed49bca1dfd8f0b993111568a9793 Mon Sep 17 00:00:00 2001 From: "restyled-io[bot]" <32688539+restyled-io[bot]@users.noreply.github.com> Date: Fri, 15 Jul 2022 18:18:50 -0700 Subject: [PATCH 15/28] Restyle DRAFT: add ScanNetworks step to CHIPDeviceController (#20808) * Restyled by whitespace * Restyled by google-java-format Co-authored-by: Restyled.io --- .../ChipDeviceController.java | 54 ++++++++++--------- .../devicecontroller/ControllerParams.java | 2 +- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 49baff89d0be16..77e20669ef58f2 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -179,18 +179,17 @@ public void resumeCommissioning() { } /** - * Update the network credentials held by the commissioner for the current - * commissioning session. The updated values will be used by the commissioner - * if the network credentials haven't already been sent to the device. - * - * Its expected that this method will be called in response to the NetworkScan - * or the ReadCommissioningInfo callbacks. - * + * Update the network credentials held by the commissioner for the current commissioning session. + * The updated values will be used by the commissioner if the network credentials haven't already + * been sent to the device. + * + *

Its expected that this method will be called in response to the NetworkScan or the + * ReadCommissioningInfo callbacks. + * * @param networkCredentials the credentials (Wi-Fi or Thread) to use in commissioning */ - public void updateCommissioningNetworkCredentials( - NetworkCredentials networkCredentials) { - updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); + public void updateCommissioningNetworkCredentials(NetworkCredentials networkCredentials) { + updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); } public void unpairDevice(long deviceId) { @@ -251,9 +250,11 @@ public void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode } } - public void onReadCommissioningInfo(int vendorId, int productId, int wifiEndpointId, int threadEndpointId) { + public void onReadCommissioningInfo( + int vendorId, int productId, int wifiEndpointId, int threadEndpointId) { if (completionListener != null) { - completionListener.onReadCommissioningInfo(vendorId, productId, wifiEndpointId, threadEndpointId); + completionListener.onReadCommissioningInfo( + vendorId, productId, wifiEndpointId, threadEndpointId); } } @@ -263,14 +264,16 @@ public void onScanNetworksFailure(int errorCode) { } } - public void onScanNetworksSuccess(Integer networkingStatus, + public void onScanNetworksSuccess( + Integer networkingStatus, Optional debugText, Optional> - wiFiScanResults, + wiFiScanResults, Optional> - threadScanResults) { + threadScanResults) { if (completionListener != null) { - completionListener.onScanNetworksSuccess(networkingStatus, debugText, wiFiScanResults, threadScanResults); + completionListener.onScanNetworksSuccess( + networkingStatus, debugText, wiFiScanResults, threadScanResults); } } @@ -625,8 +628,8 @@ private native boolean openPairingWindowWithPINCallback( private native void resumeCommissioning(long deviceControllerPtr); - private native void updateCommissioningNetworkCredentials(long deviceControllerPtr, - NetworkCredentials networkCredentials); + private native void updateCommissioningNetworkCredentials( + long deviceControllerPtr, NetworkCredentials networkCredentials); private native void shutdownSubscriptions(long deviceControllerPtr, long devicePtr); @@ -665,7 +668,8 @@ public interface CompletionListener { void onCommissioningComplete(long nodeId, int errorCode); /** Notifies the completion of each stage of commissioning. */ - void onReadCommissioningInfo(int vendorId, int productId, int wifiEndpointId, int threadEndpointId); + void onReadCommissioningInfo( + int vendorId, int productId, int wifiEndpointId, int threadEndpointId); /** Notifies the completion of each stage of commissioning. */ void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode); @@ -674,12 +678,12 @@ public interface CompletionListener { void onScanNetworksFailure(int errorCode); void onScanNetworksSuccess( - Integer networkingStatus, - Optional debugText, - Optional> - wiFiScanResults, - Optional> - threadScanResults); + Integer networkingStatus, + Optional debugText, + Optional> + wiFiScanResults, + Optional> + threadScanResults); /** Notifies that the Chip connection has been closed. */ void onNotifyChipConnectionClosed(); diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index e5b0ecb2467b8f..32ed3005e80ea2 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -93,7 +93,7 @@ public static class Builder { private int failsafeTimerSeconds = 30; private boolean attemptNetworkScanWiFi = false; private boolean attemptNetworkScanThread = true; - + private Builder() {} public Builder setUdpListenPort(int udpListenPort) { From d61ae0dc6310ca7e9c4dcb98f6731bef1b9ff7c9 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Mon, 18 Jul 2022 10:18:24 -0700 Subject: [PATCH 16/28] fix CI --- src/controller/AutoCommissioner.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index 1fcbf6eb32134a..5438ec41baeff2 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -167,10 +167,7 @@ CommissioningStage AutoCommissioner::GetNextCommissioningStageInternal(Commissio { return CommissioningStage::kScanNetworks; } - else - { - ChipLogProgress(Controller, "No NetworkScan enabled or WiFi/Thread endpoint not specified, skipping ScanNetworks"); - } + ChipLogProgress(Controller, "No NetworkScan enabled or WiFi/Thread endpoint not specified, skipping ScanNetworks"); } else { From 2452d0f3f41e36bcfba4bd046e847ad2c34b527c Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Mon, 18 Jul 2022 11:14:19 -0700 Subject: [PATCH 17/28] fix kotlin build issue --- .../chiptool/GenericChipDeviceListener.kt | 12 ------ .../ChipDeviceController.java | 38 +++++++++++-------- 2 files changed, 23 insertions(+), 27 deletions(-) diff --git a/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt b/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt index f1e41d5fe3e43e..4ccf1ba6e6a836 100644 --- a/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt +++ b/src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/GenericChipDeviceListener.kt @@ -31,18 +31,6 @@ open class GenericChipDeviceListener : ChipDeviceController.CompletionListener { // No op } - override fun onScanNetworksFailure(errorCode: Int) { - // No op - } - - override fun onScanNetworksSuccess( - networkingStatus: Int, - debugText: Optional, - wiFiScanResults: Optional>, - threadScanResults: Optional>) { - // No op - } - override fun onNotifyChipConnectionClosed() { // No op } diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 77e20669ef58f2..6b1197ae28cdc5 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -33,6 +33,7 @@ public class ChipDeviceController { private long deviceControllerPtr; private int connectionId; private CompletionListener completionListener; + private ScanNetworksListener scanNetworksListener; /** * To load class and jni, we need to new AndroidChipPlatform after jni load but before new @@ -56,6 +57,10 @@ public void setCompletionListener(CompletionListener listener) { completionListener = listener; } + public void setScanNetworksListener(ScanNetworksListener listener) { + scanNetworksListener = listener; + } + public void pairDevice( BluetoothGatt bleServer, int connId, @@ -259,8 +264,8 @@ public void onReadCommissioningInfo( } public void onScanNetworksFailure(int errorCode) { - if (completionListener != null) { - completionListener.onScanNetworksFailure(errorCode); + if (scanNetworksListener != null) { + scanNetworksListener.onScanNetworksFailure(errorCode); } } @@ -271,8 +276,8 @@ public void onScanNetworksSuccess( wiFiScanResults, Optional> threadScanResults) { - if (completionListener != null) { - completionListener.onScanNetworksSuccess( + if (scanNetworksListener != null) { + scanNetworksListener.onScanNetworksSuccess( networkingStatus, debugText, wiFiScanResults, threadScanResults); } } @@ -649,6 +654,20 @@ protected void finalize() throws Throwable { } } + /** Interface to listen for callbacks from CHIPDeviceController. */ + public interface ScanNetworksListener { + /** Notifies when scan networks call fails. */ + void onScanNetworksFailure(int errorCode); + + void onScanNetworksSuccess( + Integer networkingStatus, + Optional debugText, + Optional> + wiFiScanResults, + Optional> + threadScanResults); + } + /** Interface to listen for callbacks from CHIPDeviceController. */ public interface CompletionListener { @@ -674,17 +693,6 @@ void onReadCommissioningInfo( /** Notifies the completion of each stage of commissioning. */ void onCommissioningStatusUpdate(long nodeId, String stage, int errorCode); - /** Notifies when scan networks call fails. */ - void onScanNetworksFailure(int errorCode); - - void onScanNetworksSuccess( - Integer networkingStatus, - Optional debugText, - Optional> - wiFiScanResults, - Optional> - threadScanResults); - /** Notifies that the Chip connection has been closed. */ void onNotifyChipConnectionClosed(); From 946d0f0454f3a90d32053ed2ad808b97a4840000 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Mon, 18 Jul 2022 14:07:12 -0700 Subject: [PATCH 18/28] fix java method signature lookup --- src/controller/java/AndroidDeviceControllerWrapper.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index ef0c2dac884a6d..9bddb3f14b3e27 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -422,8 +422,8 @@ void AndroidDeviceControllerWrapper::OnCommissioningStatusUpdate(PeerId peerId, chip::DeviceLayer::StackUnlock unlock; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); jmethodID onCommissioningStatusUpdateMethod; - CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onCommissioningStatusUpdate", "(JI)V", - &onCommissioningStatusUpdateMethod); + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onCommissioningStatusUpdate", + "(JLJAVA/LANG/STRING;I)V", &onCommissioningStatusUpdateMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); UtfString jStageCompleted(env, StageToString(stageCompleted)); @@ -437,7 +437,7 @@ void AndroidDeviceControllerWrapper::OnReadCommissioningInfo(chip::Controller::R chip::DeviceLayer::StackUnlock unlock; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); jmethodID onReadCommissioningInfoMethod; - CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onReadCommissioningInfo", "(JI)V", + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onReadCommissioningInfo", "(IIII)V", &onReadCommissioningInfoMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); From f06a4f2610cd21aeff7280d11671e9a59518688c Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Mon, 18 Jul 2022 17:19:03 -0700 Subject: [PATCH 19/28] fix cirq tests, add name for ScanNetworks step --- src/controller/CommissioningDelegate.cpp | 4 ++++ src/controller/CommissioningDelegate.h | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/controller/CommissioningDelegate.cpp b/src/controller/CommissioningDelegate.cpp index 82834ce3854ae8..01d9c6ecd90f88 100644 --- a/src/controller/CommissioningDelegate.cpp +++ b/src/controller/CommissioningDelegate.cpp @@ -41,6 +41,10 @@ const char * StageToString(CommissioningStage stage) return "ArmFailSafe"; break; + case kScanNetworks: + return "ScanNetworks"; + break; + case kConfigRegulatory: return "ConfigRegulatory"; break; diff --git a/src/controller/CommissioningDelegate.h b/src/controller/CommissioningDelegate.h index a29e6b218baac7..4468b624c3c6b9 100644 --- a/src/controller/CommissioningDelegate.h +++ b/src/controller/CommissioningDelegate.h @@ -35,7 +35,6 @@ enum CommissioningStage : uint8_t kSecurePairing, kReadCommissioningInfo, kArmFailsafe, - kScanNetworks, kConfigRegulatory, kSendPAICertificateRequest, kSendDACCertificateRequest, @@ -46,6 +45,8 @@ enum CommissioningStage : uint8_t kGenerateNOCChain, kSendTrustedRootCert, kSendNOC, + // ScanNetworks can happen anytime after kArmFailsafe + kScanNetworks, kWiFiNetworkSetup, kThreadNetworkSetup, kWiFiNetworkEnable, From f1b5c648a1ff8b1f02e597307048c4923d5db15a Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Wed, 20 Jul 2022 08:16:19 -0700 Subject: [PATCH 20/28] attempt to fix cirq tests --- src/controller/CHIPDeviceController.cpp | 4 +++- src/controller/CommissioningDelegate.h | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 5f8ceb83383e5d..33e7867dbfa835 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1573,6 +1573,7 @@ void DeviceCommissioner::ResumeCommissioning() mDeviceBeingCommissioned = nullptr; CommissioningDelegate::CommissioningReport report; + mCommissioningPaused = false; if (mCommissioningDelegate == nullptr) { return; @@ -1766,7 +1767,8 @@ void DeviceCommissioner::OnDone(app::ReadClient *) { if (features.Has(app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kWiFiNetworkInterface)) { - ChipLogError(Controller, "----- NetworkCommissioning Features: has WiFi."); + ChipLogError(Controller, "----- NetworkCommissioning Features: has WiFi. endpointid = %d", + path.mEndpointId); info.network.wifi.endpoint = path.mEndpointId; } else if (features.Has( diff --git a/src/controller/CommissioningDelegate.h b/src/controller/CommissioningDelegate.h index 4468b624c3c6b9..7e2734f5b362dd 100644 --- a/src/controller/CommissioningDelegate.h +++ b/src/controller/CommissioningDelegate.h @@ -45,8 +45,6 @@ enum CommissioningStage : uint8_t kGenerateNOCChain, kSendTrustedRootCert, kSendNOC, - // ScanNetworks can happen anytime after kArmFailsafe - kScanNetworks, kWiFiNetworkSetup, kThreadNetworkSetup, kWiFiNetworkEnable, @@ -54,6 +52,8 @@ enum CommissioningStage : uint8_t kFindOperational, kSendComplete, kCleanup, + // ScanNetworks can happen anytime after kArmFailsafe. Adding to the end to try to fix circ tests + kScanNetworks, }; const char * StageToString(CommissioningStage stage); From 3ae3de4e6566e54c35cc00c756a0d8acb62beaa6 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Tue, 26 Jul 2022 13:48:20 -0700 Subject: [PATCH 21/28] Address comments --- src/controller/AutoCommissioner.cpp | 28 +++++++++- src/controller/AutoCommissioner.h | 16 +++++- src/controller/CHIPDeviceController.cpp | 55 ++----------------- src/controller/CHIPDeviceController.h | 18 +----- src/controller/CommissioningDelegate.h | 15 ++++- src/controller/DevicePairingDelegate.h | 5 +- .../java/AndroidDeviceControllerWrapper.cpp | 2 +- .../java/AndroidDeviceControllerWrapper.h | 9 ++- 8 files changed, 74 insertions(+), 74 deletions(-) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index 5438ec41baeff2..6be757b1a7f312 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -507,6 +507,18 @@ CHIP_ERROR AutoCommissioner::CommissioningStepFinished(CHIP_ERROR err, Commissio { completionStatus.err = err; } + mParams.SetCompletionStatus(completionStatus); + + if (mCommissioningPaused) + { + mPausedStage = nextStage; + return CHIP_NO_ERROR; + } + return PerformStep(nextStage); +} + +CHIP_ERROR AutoCommissioner::PerformStep(CommissioningStage nextStage) +{ DeviceProxy * proxy = mCommissioneeDeviceProxy; if (nextStage == CommissioningStage::kSendComplete || @@ -521,12 +533,26 @@ CHIP_ERROR AutoCommissioner::CommissioningStepFinished(CHIP_ERROR err, Commissio return CHIP_ERROR_INCORRECT_STATE; } - mParams.SetCompletionStatus(completionStatus); mCommissioner->PerformCommissioningStep(proxy, nextStage, mParams, this, GetEndpoint(nextStage), GetCommandTimeout(proxy, nextStage)); return CHIP_NO_ERROR; } +void AutoCommissioner::PauseCommissioning() +{ + mCommissioningPaused = true; +} + +CHIP_ERROR AutoCommissioner::ResumeCommissioning() +{ + VerifyOrReturnError(mPausedStage != CommissioningStage::kError, CHIP_ERROR_INCORRECT_STATE); + CommissioningStage nextStage = mPausedStage; + mPausedStage = CommissioningStage::kError; + mCommissioningPaused = false; + + return PerformStep(nextStage); +} + void AutoCommissioner::ReleaseDAC() { if (mDAC != nullptr) diff --git a/src/controller/AutoCommissioner.h b/src/controller/AutoCommissioner.h index 33bfe350b9fa34..49be8751c43061 100644 --- a/src/controller/AutoCommissioner.h +++ b/src/controller/AutoCommissioner.h @@ -38,11 +38,22 @@ class AutoCommissioner : public CommissioningDelegate CHIP_ERROR CommissioningStepFinished(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report) override; - ReadCommissioningInfo GetReadCommissioningInfo() const { return mDeviceCommissioningInfo; } + /** + * @brief + * This function puts the AutoCommissioner in a paused state to prevent advancing to the next stage. + * It is expected that a DevicePairingDelegate may call this method when processing the + * OnCommissioningStatusUpdate, for example, in order to obtain network credentials from the user based + * upon the results of the NetworkScan. + * Use ResumeCommissioning to continue the commissioning process. + * + */ + void PauseCommissioning(); + CHIP_ERROR ResumeCommissioning(); protected: CommissioningStage GetNextCommissioningStage(CommissioningStage currentStage, CHIP_ERROR & lastErr); DeviceCommissioner * GetCommissioner() { return mCommissioner; } + CHIP_ERROR PerformStep(CommissioningStage nextStage); private: void ReleaseDAC(); @@ -77,6 +88,9 @@ class AutoCommissioner : public CommissioningDelegate bool mNeedsNetworkSetup = false; ReadCommissioningInfo mDeviceCommissioningInfo; + CommissioningStage mPausedStage = CommissioningStage::kError; + bool mCommissioningPaused = false; + // TODO: Why were the nonces statically allocated, but the certs dynamically allocated? uint8_t * mDAC = nullptr; uint16_t mDACLen = 0; diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 33e7867dbfa835..d1d44e8ef4f306 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1557,42 +1557,6 @@ void DeviceCommissioner::SendCommissioningCompleteCallbacks(NodeId nodeId, const } } -void DeviceCommissioner::PauseCommissioning() -{ - VerifyOrReturn(mDeviceBeingCommissioned != nullptr); - mCommissioningPaused = true; -} - -void DeviceCommissioner::ResumeCommissioning() -{ - VerifyOrReturn(mCommissioningPaused); - VerifyOrReturn(mDeviceBeingCommissioned != nullptr); - - NodeId nodeId = mDeviceBeingCommissioned->GetDeviceId(); - DeviceProxy * proxy = mDeviceBeingCommissioned; - mDeviceBeingCommissioned = nullptr; - CommissioningDelegate::CommissioningReport report; - - mCommissioningPaused = false; - if (mCommissioningDelegate == nullptr) - { - return; - } - report.stageCompleted = mCommissioningStage; - CHIP_ERROR status = mCommissioningDelegate->CommissioningStepFinished(mCommissioningPausedErr, report); - if (status != CHIP_NO_ERROR) - { - // Commissioning delegate will only return error if it failed to perform the appropriate commissioning step. - // In this case, we should complete the commissioning for it. - CompletionStatus completionStatus; - completionStatus.err = status; - completionStatus.failedStage = MakeOptional(report.stageCompleted); - mCommissioningStage = CommissioningStage::kCleanup; - mDeviceBeingCommissioned = proxy; - CleanupCommissioning(proxy, nodeId, completionStatus); - } -} - void DeviceCommissioner::CommissioningStageComplete(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report) { // Once this stage is complete, reset mDeviceBeingCommissioned - this will be reset when the delegate calls the next step. @@ -1606,12 +1570,6 @@ void DeviceCommissioner::CommissioningStageComplete(CHIP_ERROR err, Commissionin mPairingDelegate->OnCommissioningStatusUpdate(PeerId(GetCompressedFabricId(), nodeId), mCommissioningStage, err); } - if (mCommissioningPaused) - { - mDeviceBeingCommissioned = proxy; - mCommissioningPausedErr = err; - return; - } if (mCommissioningDelegate == nullptr) { return; @@ -1767,25 +1725,25 @@ void DeviceCommissioner::OnDone(app::ReadClient *) { if (features.Has(app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kWiFiNetworkInterface)) { - ChipLogError(Controller, "----- NetworkCommissioning Features: has WiFi. endpointid = %d", - path.mEndpointId); + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has WiFi. endpointid = %d", + path.mEndpointId); info.network.wifi.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kThreadNetworkInterface)) { - ChipLogError(Controller, "----- NetworkCommissioning Features: has Thread."); + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Thread."); info.network.thread.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kEthernetNetworkInterface)) { - ChipLogError(Controller, "----- NetworkCommissioning Features: has Ethernet."); + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Ethernet."); info.network.eth.endpoint = path.mEndpointId; } else { - ChipLogError(Controller, "----- NetworkCommissioning Features: no features."); + ChipLogProgress(Controller, "----- NetworkCommissioning Features: no features."); // TODO: Gross workaround for the empty feature map on all clusters. Remove. if (info.network.thread.endpoint == kInvalidEndpointId) { @@ -1835,7 +1793,6 @@ void DeviceCommissioner::OnDone(app::ReadClient *) mAttributeCache = nullptr; mReadClient = nullptr; - // todo - callback for read commissioning info if (mPairingDelegate != nullptr) { mPairingDelegate->OnReadCommissioningInfo(info); @@ -1881,7 +1838,7 @@ void DeviceCommissioner::OnSetRegulatoryConfigResponse( void DeviceCommissioner::OnScanNetworksFailure(void * context, CHIP_ERROR error) { - ChipLogProgress(Controller, "Received ScanNetworks failure response %s\n", chip::ErrorStr(error)); + ChipLogProgress(Controller, "Received ScanNetworks failure response %" CHIP_ERROR_FORMAT, error.Format()); DeviceCommissioner * commissioner = static_cast(context); if (commissioner->GetPairingDelegate() != nullptr) diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index bce9ec70e5b02d..ec5c2b6e5c59f3 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -560,18 +560,6 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, */ CHIP_ERROR ValidateAttestationInfo(const Credentials::DeviceAttestationVerifier::AttestationInfo & info); - /** - * @brief - * This function puts the commissioner in a paused state to prevent advancing to the next stage. - * It is expected that a DevicePairingDelegate may call this method when processing the - * OnCommissioningStatusUpdate, for example, in order to obtain network credentials from the user based - * upon the results of the NetworkScan. - * Use ResumeCommissioning to continue the commissioning process. - * - */ - void PauseCommissioning(); - void ResumeCommissioning(); - /** * @brief * Sends CommissioningStepComplete report to the commissioning delegate. Function will fill in current step. @@ -777,11 +765,11 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, const chip::app::Clusters::GeneralCommissioning::Commands::SetRegulatoryConfigResponse::DecodableType & data); static void OnScanNetworksResponse(void * context, - const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data); + const app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data); static void OnScanNetworksFailure(void * context, CHIP_ERROR err); static void OnNetworkConfigResponse(void * context, - const chip::app::Clusters::NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data); + const app::Clusters::NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data); static void OnConnectNetworkResponse( void * context, const chip::app::Clusters::NetworkCommissioning::Commands::ConnectNetworkResponse::DecodableType & data); static void OnCommissioningCompleteResponse( @@ -887,8 +875,6 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, Platform::UniquePtr mReadClient; Credentials::AttestationVerificationResult mAttestationResult; Credentials::DeviceAttestationVerifier * mDeviceAttestationVerifier = nullptr; - bool mCommissioningPaused = false; - CHIP_ERROR mCommissioningPausedErr = CHIP_NO_ERROR; }; } // namespace Controller diff --git a/src/controller/CommissioningDelegate.h b/src/controller/CommissioningDelegate.h index 7e2734f5b362dd..4541aaf5751b21 100644 --- a/src/controller/CommissioningDelegate.h +++ b/src/controller/CommissioningDelegate.h @@ -52,7 +52,8 @@ enum CommissioningStage : uint8_t kFindOperational, kSendComplete, kCleanup, - // ScanNetworks can happen anytime after kArmFailsafe. Adding to the end to try to fix circ tests + // ScanNetworks can happen anytime after kArmFailsafe. + // However, the circ tests fail if it is earlier in the list kScanNetworks, }; @@ -263,10 +264,12 @@ class CommissioningParameters return *this; } + // If a ThreadOperationalDataset is provided, then the ThreadNetworkScan will not be attempted CommissioningParameters & SetThreadOperationalDataset(ByteSpan threadOperationalDataset) { mThreadOperationalDataset.SetValue(threadOperationalDataset); + mAttemptThreadNetworkScan = false; return *this; } // This parameter should be set with the information returned from kSendOpCertSigningRequest. It must be set before calling @@ -354,6 +357,8 @@ class CommissioningParameters Credentials::DeviceAttestationDelegate * GetDeviceAttestationDelegate() const { return mDeviceAttestationDelegate; } + // If an SSID is provided, and AttemptWiFiNetworkScan is true, + // then a directed scan will be performed using the SSID provided in the WiFiCredentials object bool GetAttemptWiFiNetworkScan() const { return mAttemptWiFiNetworkScan; } CommissioningParameters & SetAttemptWiFiNetworkScan(bool attemptWiFiNetworkScan) { @@ -361,10 +366,14 @@ class CommissioningParameters return *this; } + // If a ThreadOperationalDataset is provided, then the ThreadNetworkScan will not be attempted bool GetAttemptThreadNetworkScan() const { return mAttemptThreadNetworkScan; } CommissioningParameters & SetAttemptThreadNetworkScan(bool attemptThreadNetworkScan) { - mAttemptThreadNetworkScan = attemptThreadNetworkScan; + if (!mThreadOperationalDataset.HasValue()) + { + mAttemptThreadNetworkScan = attemptThreadNetworkScan; + } return *this; } @@ -396,7 +405,7 @@ class CommissioningParameters Credentials::DeviceAttestationDelegate * mDeviceAttestationDelegate = nullptr; // Delegate to handle device attestation failures during commissioning bool mAttemptWiFiNetworkScan = false; - bool mAttemptThreadNetworkScan = true; // TODO: consider whether default value should be enabled or disabled + bool mAttemptThreadNetworkScan = true; // This changes to false when a ThreadOperationalDataset is set }; struct RequestedCertificate diff --git a/src/controller/DevicePairingDelegate.h b/src/controller/DevicePairingDelegate.h index 9a726dec39459d..5d27ac5fe1e3f3 100644 --- a/src/controller/DevicePairingDelegate.h +++ b/src/controller/DevicePairingDelegate.h @@ -17,6 +17,7 @@ #pragma once +#include #include #include #include @@ -86,8 +87,8 @@ class DLL_EXPORT DevicePairingDelegate * @brief * Called with the NetworkScanResponse returned from the target */ - virtual void OnScanNetworksSuccess( - const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) + virtual void + OnScanNetworksSuccess(const app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) {} /** diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 9bddb3f14b3e27..56a5521517d637 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -364,7 +364,7 @@ CHIP_ERROR AndroidDeviceControllerWrapper::ApplyNetworkCredentials(chip::Control return err; } -CHIP_ERROR AndroidDeviceControllerWrapper::UpdateNetworkCredentials(chip::Controller::CommissioningParameters & params) +CHIP_ERROR AndroidDeviceControllerWrapper::UpdateNetworkCredentials(const chip::Controller::CommissioningParameters & params) { // this will wipe out any custom attestationNonce and csrNonce that was being used. // however, Android APIs don't allow these to be set to custom values today. diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 965dcd84b60cec..7368ea8077e42b 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -73,7 +73,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel /** * Update the network credentials used by the active device commissioner */ - CHIP_ERROR UpdateNetworkCredentials(chip::Controller::CommissioningParameters & params); + CHIP_ERROR UpdateNetworkCredentials(const chip::Controller::CommissioningParameters & params); // DevicePairingDelegate implementation void OnStatusUpdate(chip::Controller::DevicePairingDelegate::Status status) override; @@ -92,6 +92,13 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override; CHIP_ERROR SyncDeleteKeyValue(const char * key) override; + chip::Controller::AutoCommissioner * GetAutoCommissioner() { return &mAutoCommissioner; } + + const chip::Controller::CommissioningParameters & GetCommissioningParameters() const + { + return mAutoCommissioner.GetCommissioningParameters(); + } + static AndroidDeviceControllerWrapper * FromJNIHandle(jlong handle) { return reinterpret_cast(handle); From 8776a7e818bc729e6a3bc4129cb7509aaa781f67 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Tue, 26 Jul 2022 14:48:31 -0700 Subject: [PATCH 22/28] Address comments --- src/controller/java/CHIPDeviceController-JNI.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index ed6c8df9aea4b7..cc278c9cbce28d 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -403,7 +403,7 @@ JNI_METHOD(void, pauseCommissioning) chip::DeviceLayer::StackLock lock; AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); - wrapper->Controller()->PauseCommissioning(); + wrapper->GetAutoCommissioner()->PauseCommissioning(); } JNI_METHOD(void, resumeCommissioning) @@ -413,7 +413,7 @@ JNI_METHOD(void, resumeCommissioning) chip::DeviceLayer::StackLock lock; AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); - wrapper->Controller()->ResumeCommissioning(); + wrapper->GetAutoCommissioner()->ResumeCommissioning(); } JNI_METHOD(void, updateCommissioningNetworkCredentials) @@ -423,7 +423,7 @@ JNI_METHOD(void, updateCommissioningNetworkCredentials) chip::DeviceLayer::StackLock lock; AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); - CommissioningParameters commissioningParams = CommissioningParameters(); + CommissioningParameters commissioningParams = wrapper->GetCommissioningParameters(); CHIP_ERROR err = wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); if (err != CHIP_NO_ERROR) { From f158c8ec60a1a4f5012bb95c9bfad34dfe56ab61 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Tue, 26 Jul 2022 15:47:08 -0700 Subject: [PATCH 23/28] fix stragglers, restyle --- src/controller/AutoCommissioner.cpp | 11 +++++++++-- .../src/chip/devicecontroller/ControllerParams.java | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index 6be757b1a7f312..89d8c4bfae318e 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -545,10 +545,17 @@ void AutoCommissioner::PauseCommissioning() CHIP_ERROR AutoCommissioner::ResumeCommissioning() { - VerifyOrReturnError(mPausedStage != CommissioningStage::kError, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mCommissioningPaused, CHIP_ERROR_INCORRECT_STATE); + mCommissioningPaused = false; + + // if no new step was attempted + if (mPausedStage == CommissioningStage::kError) + { + return CHIP_NO_ERROR; + } + CommissioningStage nextStage = mPausedStage; mPausedStage = CommissioningStage::kError; - mCommissioningPaused = false; return PerformStep(nextStage); } diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index 1133ae52f80a53..87fb85a375adf1 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -115,7 +115,7 @@ public Builder setControllerVendorId(int controllerVendorId) { this.controllerVendorId = controllerVendorId; return this; } - + public Builder setFailsafeTimerSeconds(int failsafeTimerSeconds) { if (failsafeTimerSeconds < 1 || failsafeTimerSeconds > 900) { throw new IllegalArgumentException("failsafeTimerSeconds must be between 0 and 900"); From 2a5e0a30be83a5e5d1d1165faebd0180bc1730b1 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Wed, 27 Jul 2022 17:10:17 -0700 Subject: [PATCH 24/28] address feedback --- src/controller/AutoCommissioner.cpp | 42 +++- src/controller/AutoCommissioner.h | 8 + src/controller/CHIPDeviceController.cpp | 8 +- src/controller/CommissioningDelegate.h | 14 +- src/controller/DevicePairingDelegate.h | 2 +- .../java/AndroidDeviceControllerWrapper.cpp | 182 ++++++++---------- .../java/AndroidDeviceControllerWrapper.h | 6 +- .../java/CHIPDeviceController-JNI.cpp | 4 +- 8 files changed, 139 insertions(+), 127 deletions(-) diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index 89d8c4bfae318e..0feec835699252 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -45,6 +45,12 @@ void AutoCommissioner::SetOperationalCredentialsDelegate(OperationalCredentialsD CHIP_ERROR AutoCommissioner::SetCommissioningParameters(const CommissioningParameters & params) { mParams = params; + if (params.GetFailsafeTimerSeconds().HasValue()) + { + ChipLogProgress(Controller, "Setting failsafe timer from parameters"); + mParams.SetFailsafeTimerSeconds(params.GetFailsafeTimerSeconds().Value()); + } + if (params.GetThreadOperationalDataset().HasValue()) { ByteSpan dataset = params.GetThreadOperationalDataset().Value(); @@ -57,6 +63,13 @@ CHIP_ERROR AutoCommissioner::SetCommissioningParameters(const CommissioningParam ChipLogProgress(Controller, "Setting thread operational dataset from parameters"); mParams.SetThreadOperationalDataset(ByteSpan(mThreadOperationalDataset, dataset.size())); } + + if (params.GetAttemptThreadNetworkScan().HasValue()) + { + ChipLogProgress(Controller, "Setting attempt thread scan from parameters"); + mParams.SetAttemptThreadNetworkScan(params.GetAttemptThreadNetworkScan().Value()); + } + if (params.GetWiFiCredentials().HasValue()) { WiFiCredentials creds = params.GetWiFiCredentials().Value(); @@ -73,6 +86,12 @@ CHIP_ERROR AutoCommissioner::SetCommissioningParameters(const CommissioningParam WiFiCredentials(ByteSpan(mSsid, creds.ssid.size()), ByteSpan(mCredentials, creds.credentials.size()))); } + if (params.GetAttemptWiFiNetworkScan().HasValue()) + { + ChipLogProgress(Controller, "Setting attempt wifi scan from parameters"); + mParams.SetAttemptWiFiNetworkScan(params.GetAttemptWiFiNetworkScan().Value()); + } + if (params.GetCountryCode().HasValue()) { auto & code = params.GetCountryCode().Value(); @@ -162,8 +181,10 @@ CommissioningStage AutoCommissioner::GetNextCommissioningStageInternal(Commissio if (mNeedsNetworkSetup) { // if there is a WiFi or a Thread endpoint, then perform scan - if ((mParams.GetAttemptWiFiNetworkScan() && mDeviceCommissioningInfo.network.wifi.endpoint != kInvalidEndpointId) || - (mParams.GetAttemptThreadNetworkScan() && mDeviceCommissioningInfo.network.thread.endpoint != kInvalidEndpointId)) + if ((mParams.GetAttemptWiFiNetworkScan().ValueOr(false) && + mDeviceCommissioningInfo.network.wifi.endpoint != kInvalidEndpointId) || + (mParams.GetAttemptThreadNetworkScan().ValueOr(false) && + mDeviceCommissioningInfo.network.thread.endpoint != kInvalidEndpointId)) { return CommissioningStage::kScanNetworks; } @@ -512,21 +533,30 @@ CHIP_ERROR AutoCommissioner::CommissioningStepFinished(CHIP_ERROR err, Commissio if (mCommissioningPaused) { mPausedStage = nextStage; + + if (GetDeviceProxyForStep(nextStage) == nullptr) + { + ChipLogError(Controller, "Invalid device for commissioning"); + return CHIP_ERROR_INCORRECT_STATE; + } return CHIP_NO_ERROR; } return PerformStep(nextStage); } -CHIP_ERROR AutoCommissioner::PerformStep(CommissioningStage nextStage) +DeviceProxy * AutoCommissioner::GetDeviceProxyForStep(CommissioningStage nextStage) { - - DeviceProxy * proxy = mCommissioneeDeviceProxy; if (nextStage == CommissioningStage::kSendComplete || (nextStage == CommissioningStage::kCleanup && mOperationalDeviceProxy != nullptr)) { - proxy = mOperationalDeviceProxy; + return mOperationalDeviceProxy; } + return mCommissioneeDeviceProxy; +} +CHIP_ERROR AutoCommissioner::PerformStep(CommissioningStage nextStage) +{ + DeviceProxy * proxy = GetDeviceProxyForStep(nextStage); if (proxy == nullptr) { ChipLogError(Controller, "Invalid device for commissioning"); diff --git a/src/controller/AutoCommissioner.h b/src/controller/AutoCommissioner.h index 49be8751c43061..422b6ef26911d9 100644 --- a/src/controller/AutoCommissioner.h +++ b/src/controller/AutoCommissioner.h @@ -48,6 +48,13 @@ class AutoCommissioner : public CommissioningDelegate * */ void PauseCommissioning(); + + /** + * @brief + * An error return value means resume failed, for example: + * - AutoCommissioner was not in a paused state. + * - AutoCommissioner was unable to continue (no DeviceProxy) + */ CHIP_ERROR ResumeCommissioning(); protected: @@ -56,6 +63,7 @@ class AutoCommissioner : public CommissioningDelegate CHIP_ERROR PerformStep(CommissioningStage nextStage); private: + DeviceProxy * GetDeviceProxyForStep(CommissioningStage nextStage); void ReleaseDAC(); void ReleasePAI(); diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 3dc9e4a4a80fd1..dcb9eca582e0af 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1712,20 +1712,22 @@ void DeviceCommissioner::OnDone(app::ReadClient *) { if (features.Has(app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kWiFiNetworkInterface)) { - ChipLogProgress(Controller, "----- NetworkCommissioning Features: has WiFi. endpointid = %d", + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has WiFi. endpointid = %" PRIu32, path.mEndpointId); info.network.wifi.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kThreadNetworkInterface)) { - ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Thread."); + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Thread. endpointid = %" PRIu32, + path.mEndpointId); info.network.thread.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kEthernetNetworkInterface)) { - ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Ethernet."); + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Ethernet. endpointid = %" PRIu32, + path.mEndpointId); info.network.eth.endpoint = path.mEndpointId; } else diff --git a/src/controller/CommissioningDelegate.h b/src/controller/CommissioningDelegate.h index 4541aaf5751b21..43ed0a1cd1aad0 100644 --- a/src/controller/CommissioningDelegate.h +++ b/src/controller/CommissioningDelegate.h @@ -269,7 +269,7 @@ class CommissioningParameters { mThreadOperationalDataset.SetValue(threadOperationalDataset); - mAttemptThreadNetworkScan = false; + mAttemptThreadNetworkScan = MakeOptional(false); return *this; } // This parameter should be set with the information returned from kSendOpCertSigningRequest. It must be set before calling @@ -359,20 +359,20 @@ class CommissioningParameters // If an SSID is provided, and AttemptWiFiNetworkScan is true, // then a directed scan will be performed using the SSID provided in the WiFiCredentials object - bool GetAttemptWiFiNetworkScan() const { return mAttemptWiFiNetworkScan; } + Optional GetAttemptWiFiNetworkScan() const { return mAttemptWiFiNetworkScan; } CommissioningParameters & SetAttemptWiFiNetworkScan(bool attemptWiFiNetworkScan) { - mAttemptWiFiNetworkScan = attemptWiFiNetworkScan; + mAttemptWiFiNetworkScan = MakeOptional(attemptWiFiNetworkScan); return *this; } // If a ThreadOperationalDataset is provided, then the ThreadNetworkScan will not be attempted - bool GetAttemptThreadNetworkScan() const { return mAttemptThreadNetworkScan; } + Optional GetAttemptThreadNetworkScan() const { return mAttemptThreadNetworkScan; } CommissioningParameters & SetAttemptThreadNetworkScan(bool attemptThreadNetworkScan) { if (!mThreadOperationalDataset.HasValue()) { - mAttemptThreadNetworkScan = attemptThreadNetworkScan; + mAttemptThreadNetworkScan = MakeOptional(attemptThreadNetworkScan); } return *this; } @@ -404,8 +404,8 @@ class CommissioningParameters CompletionStatus completionStatus; Credentials::DeviceAttestationDelegate * mDeviceAttestationDelegate = nullptr; // Delegate to handle device attestation failures during commissioning - bool mAttemptWiFiNetworkScan = false; - bool mAttemptThreadNetworkScan = true; // This changes to false when a ThreadOperationalDataset is set + Optional mAttemptWiFiNetworkScan; + Optional mAttemptThreadNetworkScan; // This automatically gets set to false when a ThreadOperationalDataset is set }; struct RequestedCertificate diff --git a/src/controller/DevicePairingDelegate.h b/src/controller/DevicePairingDelegate.h index 5d27ac5fe1e3f3..2e9fc0558c2221 100644 --- a/src/controller/DevicePairingDelegate.h +++ b/src/controller/DevicePairingDelegate.h @@ -81,7 +81,7 @@ class DLL_EXPORT DevicePairingDelegate * @brief * Called with the ReadCommissioningInfo returned from the target */ - virtual void OnReadCommissioningInfo(ReadCommissioningInfo info) {} + virtual void OnReadCommissioningInfo(const ReadCommissioningInfo & info) {} /** * @brief diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 650f8e3a64653f..550d617da5c07a 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -156,6 +156,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( params.SetFailsafeTimerSeconds(failsafeTimerSeconds); params.SetAttemptWiFiNetworkScan(attemptNetworkScanWiFi); params.SetAttemptThreadNetworkScan(attemptNetworkScanThread); + wrapper->UpdateCommissioningParameters(params); CHIP_ERROR err = wrapper->mGroupDataProvider.Init(); if (err != CHIP_NO_ERROR) @@ -365,7 +366,7 @@ CHIP_ERROR AndroidDeviceControllerWrapper::ApplyNetworkCredentials(chip::Control return err; } -CHIP_ERROR AndroidDeviceControllerWrapper::UpdateNetworkCredentials(const chip::Controller::CommissioningParameters & params) +CHIP_ERROR AndroidDeviceControllerWrapper::UpdateCommissioningParameters(const chip::Controller::CommissioningParameters & params) { // this will wipe out any custom attestationNonce and csrNonce that was being used. // however, Android APIs don't allow these to be set to custom values today. @@ -432,7 +433,7 @@ void AndroidDeviceControllerWrapper::OnCommissioningStatusUpdate(PeerId peerId, jStageCompleted.jniValue(), error.AsInteger()); } -void AndroidDeviceControllerWrapper::OnReadCommissioningInfo(chip::Controller::ReadCommissioningInfo info) +void AndroidDeviceControllerWrapper::OnReadCommissioningInfo(const chip::Controller::ReadCommissioningInfo & info) { // calls: onReadCommissioningInfo(int vendorId, int productId, int wifiEndpointId, int threadEndpointId) chip::DeviceLayer::StackUnlock unlock; @@ -491,67 +492,58 @@ void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( jobject WiFiScanResultsInsideOptional; chip::JniReferences::GetInstance().CreateArrayList(WiFiScanResultsInsideOptional); - auto iter_WiFiScanResultsInsideOptional_1 = dataResponse.wiFiScanResults.Value().begin(); - while (iter_WiFiScanResultsInsideOptional_1.Next()) + auto iter_WiFiScanResultsInsideOptional = dataResponse.wiFiScanResults.Value().begin(); + while (iter_WiFiScanResultsInsideOptional.Next()) { - auto & entry_1 = iter_WiFiScanResultsInsideOptional_1.GetValue(); - jobject newElement_1; - jobject newElement_1_security; - std::string newElement_1_securityClassName = "java/lang/Integer"; - std::string newElement_1_securityCtorSignature = "(I)V"; - chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_securityClassName.c_str(), - newElement_1_securityCtorSignature.c_str(), - entry_1.security.Raw(), newElement_1_security); - jobject newElement_1_ssid; - jbyteArray newElement_1_ssidByteArray = env->NewByteArray(static_cast(entry_1.ssid.size())); - env->SetByteArrayRegion(newElement_1_ssidByteArray, 0, static_cast(entry_1.ssid.size()), - reinterpret_cast(entry_1.ssid.data())); - newElement_1_ssid = newElement_1_ssidByteArray; - jobject newElement_1_bssid; - jbyteArray newElement_1_bssidByteArray = env->NewByteArray(static_cast(entry_1.bssid.size())); - env->SetByteArrayRegion(newElement_1_bssidByteArray, 0, static_cast(entry_1.bssid.size()), - reinterpret_cast(entry_1.bssid.data())); - newElement_1_bssid = newElement_1_bssidByteArray; - jobject newElement_1_channel; - std::string newElement_1_channelClassName = "java/lang/Integer"; - std::string newElement_1_channelCtorSignature = "(I)V"; - chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_channelClassName.c_str(), - newElement_1_channelCtorSignature.c_str(), - entry_1.channel, newElement_1_channel); - jobject newElement_1_wiFiBand; - std::string newElement_1_wiFiBandClassName = "java/lang/Integer"; - std::string newElement_1_wiFiBandCtorSignature = "(I)V"; + auto & entry = iter_WiFiScanResultsInsideOptional.GetValue(); + jobject newElement; + jobject newElement_security; + std::string newElement_securityClassName = "java/lang/Integer"; + std::string newElement_securityCtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject(newElement_securityClassName.c_str(), + newElement_securityCtorSignature.c_str(), + entry.security.Raw(), newElement_security); + jobject newElement_ssid; + jbyteArray newElement_ssidByteArray = env->NewByteArray(static_cast(entry.ssid.size())); + env->SetByteArrayRegion(newElement_ssidByteArray, 0, static_cast(entry.ssid.size()), + reinterpret_cast(entry.ssid.data())); + newElement_ssid = newElement_ssidByteArray; + jobject newElement_bssid; + jbyteArray newElement_bssidByteArray = env->NewByteArray(static_cast(entry.bssid.size())); + env->SetByteArrayRegion(newElement_bssidByteArray, 0, static_cast(entry.bssid.size()), + reinterpret_cast(entry.bssid.data())); + newElement_bssid = newElement_bssidByteArray; + jobject newElement_channel; + chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Integer", "(I)V", entry.channel, + newElement_channel); + jobject newElement_wiFiBand; chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_1_wiFiBandClassName.c_str(), newElement_1_wiFiBandCtorSignature.c_str(), - static_cast(entry_1.wiFiBand), newElement_1_wiFiBand); - jobject newElement_1_rssi; - std::string newElement_1_rssiClassName = "java/lang/Integer"; - std::string newElement_1_rssiCtorSignature = "(I)V"; - chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_1_rssiClassName.c_str(), newElement_1_rssiCtorSignature.c_str(), entry_1.rssi, newElement_1_rssi); - - jclass wiFiInterfaceScanResultStructClass_2; + "java/lang/Integer", "(I)V", static_cast(entry.wiFiBand), newElement_wiFiBand); + jobject newElement_rssi; + chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Integer", "(I)V", entry.rssi, newElement_rssi); + + jclass wiFiInterfaceScanResultStructClass; err = chip::JniReferences::GetInstance().GetClassRef( env, "chip/devicecontroller/ChipStructs$NetworkCommissioningClusterWiFiInterfaceScanResult", - wiFiInterfaceScanResultStructClass_2); + wiFiInterfaceScanResultStructClass); if (err != CHIP_NO_ERROR) { ChipLogError(Zcl, "Could not find class ChipStructs$NetworkCommissioningClusterWiFiInterfaceScanResult"); return; } - jmethodID wiFiInterfaceScanResultStructCtor_2 = - env->GetMethodID(wiFiInterfaceScanResultStructClass_2, "", + jmethodID wiFiInterfaceScanResultStructCtor = + env->GetMethodID(wiFiInterfaceScanResultStructClass, "", "(Ljava/lang/Integer;[B[BLjava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;)V"); - if (wiFiInterfaceScanResultStructCtor_2 == nullptr) + if (wiFiInterfaceScanResultStructCtor == nullptr) { ChipLogError(Zcl, "Could not find ChipStructs$NetworkCommissioningClusterWiFiInterfaceScanResult constructor"); return; } - newElement_1 = env->NewObject(wiFiInterfaceScanResultStructClass_2, wiFiInterfaceScanResultStructCtor_2, - newElement_1_security, newElement_1_ssid, newElement_1_bssid, newElement_1_channel, - newElement_1_wiFiBand, newElement_1_rssi); - chip::JniReferences::GetInstance().AddToList(WiFiScanResultsInsideOptional, newElement_1); + newElement = + env->NewObject(wiFiInterfaceScanResultStructClass, wiFiInterfaceScanResultStructCtor, newElement_security, + newElement_ssid, newElement_bssid, newElement_channel, newElement_wiFiBand, newElement_rssi); + chip::JniReferences::GetInstance().AddToList(WiFiScanResultsInsideOptional, newElement); } chip::JniReferences::GetInstance().CreateOptional(WiFiScanResultsInsideOptional, WiFiScanResults); } @@ -565,78 +557,58 @@ void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( jobject ThreadScanResultsInsideOptional; chip::JniReferences::GetInstance().CreateArrayList(ThreadScanResultsInsideOptional); - auto iter_ThreadScanResultsInsideOptional_1 = dataResponse.threadScanResults.Value().begin(); - while (iter_ThreadScanResultsInsideOptional_1.Next()) + auto iter_ThreadScanResultsInsideOptional = dataResponse.threadScanResults.Value().begin(); + while (iter_ThreadScanResultsInsideOptional.Next()) { - auto & entry_1 = iter_ThreadScanResultsInsideOptional_1.GetValue(); - jobject newElement_1; - jobject newElement_1_panId; - std::string newElement_1_panIdClassName = "java/lang/Integer"; - std::string newElement_1_panIdCtorSignature = "(I)V"; - chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_1_panIdClassName.c_str(), newElement_1_panIdCtorSignature.c_str(), entry_1.panId, newElement_1_panId); - jobject newElement_1_extendedPanId; - std::string newElement_1_extendedPanIdClassName = "java/lang/Long"; - std::string newElement_1_extendedPanIdCtorSignature = "(J)V"; - chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_extendedPanIdClassName.c_str(), - newElement_1_extendedPanIdCtorSignature.c_str(), - entry_1.extendedPanId, newElement_1_extendedPanId); - jobject newElement_1_networkName; - newElement_1_networkName = - env->NewStringUTF(std::string(entry_1.networkName.data(), entry_1.networkName.size()).c_str()); - jobject newElement_1_channel; - std::string newElement_1_channelClassName = "java/lang/Integer"; - std::string newElement_1_channelCtorSignature = "(I)V"; - chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_channelClassName.c_str(), - newElement_1_channelCtorSignature.c_str(), - entry_1.channel, newElement_1_channel); - jobject newElement_1_version; - std::string newElement_1_versionClassName = "java/lang/Integer"; - std::string newElement_1_versionCtorSignature = "(I)V"; - chip::JniReferences::GetInstance().CreateBoxedObject(newElement_1_versionClassName.c_str(), - newElement_1_versionCtorSignature.c_str(), - entry_1.version, newElement_1_version); - jobject newElement_1_extendedAddress; - jbyteArray newElement_1_extendedAddressByteArray = - env->NewByteArray(static_cast(entry_1.extendedAddress.size())); - env->SetByteArrayRegion(newElement_1_extendedAddressByteArray, 0, static_cast(entry_1.extendedAddress.size()), - reinterpret_cast(entry_1.extendedAddress.data())); - newElement_1_extendedAddress = newElement_1_extendedAddressByteArray; - jobject newElement_1_rssi; - std::string newElement_1_rssiClassName = "java/lang/Integer"; - std::string newElement_1_rssiCtorSignature = "(I)V"; - chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_1_rssiClassName.c_str(), newElement_1_rssiCtorSignature.c_str(), entry_1.rssi, newElement_1_rssi); - jobject newElement_1_lqi; - std::string newElement_1_lqiClassName = "java/lang/Integer"; - std::string newElement_1_lqiCtorSignature = "(I)V"; - chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_1_lqiClassName.c_str(), newElement_1_lqiCtorSignature.c_str(), entry_1.lqi, newElement_1_lqi); - - jclass threadInterfaceScanResultStructClass_2; + auto & entry = iter_ThreadScanResultsInsideOptional.GetValue(); + jobject newElement; + jobject newElement_panId; + chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Integer", "(I)V", entry.panId, + newElement_panId); + jobject newElement_extendedPanId; + chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Long", "(J)V", entry.extendedPanId, + newElement_extendedPanId); + jobject newElement_networkName; + newElement_networkName = env->NewStringUTF(std::string(entry.networkName.data(), entry.networkName.size()).c_str()); + jobject newElement_channel; + chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Integer", "(I)V", entry.channel, + newElement_channel); + jobject newElement_version; + chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Integer", "(I)V", entry.version, + newElement_version); + jobject newElement_extendedAddress; + jbyteArray newElement_extendedAddressByteArray = env->NewByteArray(static_cast(entry.extendedAddress.size())); + env->SetByteArrayRegion(newElement_extendedAddressByteArray, 0, static_cast(entry.extendedAddress.size()), + reinterpret_cast(entry.extendedAddress.data())); + newElement_extendedAddress = newElement_extendedAddressByteArray; + jobject newElement_rssi; + chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Integer", "(I)V", entry.rssi, newElement_rssi); + jobject newElement_lqi; + chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Integer", "(I)V", entry.lqi, newElement_lqi); + + jclass threadInterfaceScanResultStructClass; err = chip::JniReferences::GetInstance().GetClassRef( env, "chip/devicecontroller/ChipStructs$NetworkCommissioningClusterThreadInterfaceScanResult", - threadInterfaceScanResultStructClass_2); + threadInterfaceScanResultStructClass); if (err != CHIP_NO_ERROR) { ChipLogError(Zcl, "Could not find class ChipStructs$NetworkCommissioningClusterThreadInterfaceScanResult"); return; } - jmethodID threadInterfaceScanResultStructCtor_2 = - env->GetMethodID(threadInterfaceScanResultStructClass_2, "", + jmethodID threadInterfaceScanResultStructCtor = + env->GetMethodID(threadInterfaceScanResultStructClass, "", "(Ljava/lang/Integer;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/" "Integer;[BLjava/lang/Integer;Ljava/lang/Integer;)V"); - if (threadInterfaceScanResultStructCtor_2 == nullptr) + if (threadInterfaceScanResultStructCtor == nullptr) { ChipLogError(Zcl, "Could not find ChipStructs$NetworkCommissioningClusterThreadInterfaceScanResult constructor"); return; } - newElement_1 = - env->NewObject(threadInterfaceScanResultStructClass_2, threadInterfaceScanResultStructCtor_2, newElement_1_panId, - newElement_1_extendedPanId, newElement_1_networkName, newElement_1_channel, newElement_1_version, - newElement_1_extendedAddress, newElement_1_rssi, newElement_1_lqi); - chip::JniReferences::GetInstance().AddToList(ThreadScanResultsInsideOptional, newElement_1); + newElement = env->NewObject(threadInterfaceScanResultStructClass, threadInterfaceScanResultStructCtor, newElement_panId, + newElement_extendedPanId, newElement_networkName, newElement_channel, newElement_version, + newElement_extendedAddress, newElement_rssi, newElement_lqi); + chip::JniReferences::GetInstance().AddToList(ThreadScanResultsInsideOptional, newElement); } chip::JniReferences::GetInstance().CreateOptional(ThreadScanResultsInsideOptional, ThreadScanResults); } diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 08abd17a648af2..e5809340fea39c 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -71,9 +71,9 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel CHIP_ERROR ApplyNetworkCredentials(chip::Controller::CommissioningParameters & params, jobject networkCredentials); /** - * Update the network credentials used by the active device commissioner + * Update the CommissioningParameters used by the active device commissioner */ - CHIP_ERROR UpdateNetworkCredentials(const chip::Controller::CommissioningParameters & params); + CHIP_ERROR UpdateCommissioningParameters(const chip::Controller::CommissioningParameters & params); // DevicePairingDelegate implementation void OnStatusUpdate(chip::Controller::DevicePairingDelegate::Status status) override; @@ -82,7 +82,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR error) override; void OnCommissioningStatusUpdate(chip::PeerId peerId, chip::Controller::CommissioningStage stageCompleted, CHIP_ERROR error) override; - void OnReadCommissioningInfo(chip::Controller::ReadCommissioningInfo info) override; + void OnReadCommissioningInfo(const chip::Controller::ReadCommissioningInfo & info) override; void OnScanNetworksSuccess( const chip::app::Clusters::NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & dataResponse) override; void OnScanNetworksFailure(CHIP_ERROR error) override; diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 8cc5ffa67be309..3e8db12d8f0794 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -436,10 +436,10 @@ JNI_METHOD(void, updateCommissioningNetworkCredentials) ChipLogError(Controller, "ApplyNetworkCredentials failed. Err = %" CHIP_ERROR_FORMAT, err.Format()); JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); } - err = wrapper->UpdateNetworkCredentials(commissioningParams); + err = wrapper->UpdateCommissioningParameters(commissioningParams); if (err != CHIP_NO_ERROR) { - ChipLogError(Controller, "UpdateNetworkCredentials failed. Err = %" CHIP_ERROR_FORMAT, err.Format()); + ChipLogError(Controller, "UpdateCommissioningParameters failed. Err = %" CHIP_ERROR_FORMAT, err.Format()); JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); } } From 90cf82099a3320426216176b0194f9770846a5a7 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Wed, 27 Jul 2022 17:29:26 -0700 Subject: [PATCH 25/28] address feedback --- .../java/AndroidDeviceControllerWrapper.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 550d617da5c07a..6ccdb94fc2abfe 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -496,7 +496,6 @@ void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( while (iter_WiFiScanResultsInsideOptional.Next()) { auto & entry = iter_WiFiScanResultsInsideOptional.GetValue(); - jobject newElement; jobject newElement_security; std::string newElement_securityClassName = "java/lang/Integer"; std::string newElement_securityCtorSignature = "(I)V"; @@ -540,7 +539,7 @@ void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( return; } - newElement = + jobject newElement = env->NewObject(wiFiInterfaceScanResultStructClass, wiFiInterfaceScanResultStructCtor, newElement_security, newElement_ssid, newElement_bssid, newElement_channel, newElement_wiFiBand, newElement_rssi); chip::JniReferences::GetInstance().AddToList(WiFiScanResultsInsideOptional, newElement); @@ -561,7 +560,6 @@ void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( while (iter_ThreadScanResultsInsideOptional.Next()) { auto & entry = iter_ThreadScanResultsInsideOptional.GetValue(); - jobject newElement; jobject newElement_panId; chip::JniReferences::GetInstance().CreateBoxedObject("java/lang/Integer", "(I)V", entry.panId, newElement_panId); @@ -605,9 +603,10 @@ void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( return; } - newElement = env->NewObject(threadInterfaceScanResultStructClass, threadInterfaceScanResultStructCtor, newElement_panId, - newElement_extendedPanId, newElement_networkName, newElement_channel, newElement_version, - newElement_extendedAddress, newElement_rssi, newElement_lqi); + jobject newElement = + env->NewObject(threadInterfaceScanResultStructClass, threadInterfaceScanResultStructCtor, newElement_panId, + newElement_extendedPanId, newElement_networkName, newElement_channel, newElement_version, + newElement_extendedAddress, newElement_rssi, newElement_lqi); chip::JniReferences::GetInstance().AddToList(ThreadScanResultsInsideOptional, newElement); } chip::JniReferences::GetInstance().CreateOptional(ThreadScanResultsInsideOptional, ThreadScanResults); From 16a7ecc89fcd3e358a676af621cd5f97fe59bd5b Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Thu, 28 Jul 2022 05:35:45 -0700 Subject: [PATCH 26/28] fix build --- src/controller/CHIPDeviceController.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index dcb9eca582e0af..6ab5c411b58497 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1712,21 +1712,21 @@ void DeviceCommissioner::OnDone(app::ReadClient *) { if (features.Has(app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kWiFiNetworkInterface)) { - ChipLogProgress(Controller, "----- NetworkCommissioning Features: has WiFi. endpointid = %" PRIu32, + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has WiFi. endpointid = %" PRIu16, path.mEndpointId); info.network.wifi.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kThreadNetworkInterface)) { - ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Thread. endpointid = %" PRIu32, + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Thread. endpointid = %" PRIu16, path.mEndpointId); info.network.thread.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kEthernetNetworkInterface)) { - ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Ethernet. endpointid = %" PRIu32, + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Ethernet. endpointid = %" PRIu16, path.mEndpointId); info.network.eth.endpoint = path.mEndpointId; } From 390b792b114dcea4396484721623edf770ce56ea Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Thu, 28 Jul 2022 05:51:21 -0700 Subject: [PATCH 27/28] fix build --- src/controller/CHIPDeviceController.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 6ab5c411b58497..d8217d2833b89b 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -1712,21 +1712,21 @@ void DeviceCommissioner::OnDone(app::ReadClient *) { if (features.Has(app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kWiFiNetworkInterface)) { - ChipLogProgress(Controller, "----- NetworkCommissioning Features: has WiFi. endpointid = %" PRIu16, + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has WiFi. endpointid = %u", path.mEndpointId); info.network.wifi.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kThreadNetworkInterface)) { - ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Thread. endpointid = %" PRIu16, + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Thread. endpointid = %u", path.mEndpointId); info.network.thread.endpoint = path.mEndpointId; } else if (features.Has( app::Clusters::NetworkCommissioning::NetworkCommissioningFeature::kEthernetNetworkInterface)) { - ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Ethernet. endpointid = %" PRIu16, + ChipLogProgress(Controller, "----- NetworkCommissioning Features: has Ethernet. endpointid = %u", path.mEndpointId); info.network.eth.endpoint = path.mEndpointId; } From 50833112a139fb15f1567471b8302256b1c133f3 Mon Sep 17 00:00:00 2001 From: chrisdecenzo Date: Thu, 28 Jul 2022 06:29:12 -0700 Subject: [PATCH 28/28] fix build --- src/controller/CommissioningDelegate.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/controller/CommissioningDelegate.h b/src/controller/CommissioningDelegate.h index 43ed0a1cd1aad0..22d651e2c4be03 100644 --- a/src/controller/CommissioningDelegate.h +++ b/src/controller/CommissioningDelegate.h @@ -269,7 +269,7 @@ class CommissioningParameters { mThreadOperationalDataset.SetValue(threadOperationalDataset); - mAttemptThreadNetworkScan = MakeOptional(false); + mAttemptThreadNetworkScan = MakeOptional(static_cast(false)); return *this; } // This parameter should be set with the information returned from kSendOpCertSigningRequest. It must be set before calling