Skip to content

Commit

Permalink
[Android] Implement Discover function (#19432)
Browse files Browse the repository at this point in the history
* Implement Android browse

* Restyled by clang-format

Co-authored-by: Restyled.io <commits@restyled.io>
  • Loading branch information
2 people authored and pull[bot] committed Aug 2, 2022
1 parent 34b3bf0 commit e476e4e
Show file tree
Hide file tree
Showing 21 changed files with 458 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import chip.platform.AndroidChipPlatform;
import chip.platform.ChipMdnsCallbackImpl;
import chip.platform.DiagnosticDataProviderImpl;
import chip.platform.NsdManagerServiceBrowser;
import chip.platform.NsdManagerServiceResolver;
import chip.platform.PreferencesConfigurationManager;
import chip.platform.PreferencesKeyValueStoreManager;
Expand Down Expand Up @@ -132,6 +133,7 @@ public void onCommissioningComplete() {
new PreferencesKeyValueStoreManager(applicationContext),
new PreferencesConfigurationManager(applicationContext),
new NsdManagerServiceResolver(applicationContext),
new NsdManagerServiceBrowser(applicationContext),
new ChipMdnsCallbackImpl(),
new DiagnosticDataProviderImpl(applicationContext));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import chip.platform.AndroidChipPlatform;
import chip.platform.ChipMdnsCallbackImpl;
import chip.platform.DiagnosticDataProviderImpl;
import chip.platform.NsdManagerServiceBrowser;
import chip.platform.NsdManagerServiceResolver;
import chip.platform.PreferencesConfigurationManager;
import chip.platform.PreferencesKeyValueStoreManager;
Expand Down Expand Up @@ -67,6 +68,7 @@ private void initJni() {
new PreferencesKeyValueStoreManager(applicationContext),
new PreferencesConfigurationManager(applicationContext),
new NsdManagerServiceResolver(applicationContext),
new NsdManagerServiceBrowser(applicationContext),
new ChipMdnsCallbackImpl(),
new DiagnosticDataProviderImpl(applicationContext));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,6 @@ class MainActivity : AppCompatActivity() {
}.start()
}

AndroidChipPlatform(AndroidBleManager(), PreferencesKeyValueStoreManager(this), PreferencesConfigurationManager(this), NsdManagerServiceResolver(this), ChipMdnsCallbackImpl(), DiagnosticDataProviderImpl(this))
AndroidChipPlatform(AndroidBleManager(), PreferencesKeyValueStoreManager(this), PreferencesConfigurationManager(this), NsdManagerServiceResolver(this), NsdManagerServiceBrowser(this), ChipMdnsCallbackImpl(), DiagnosticDataProviderImpl(this))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import chip.platform.AndroidBleManager
import chip.platform.AndroidChipPlatform
import chip.platform.ChipMdnsCallbackImpl
import chip.platform.DiagnosticDataProviderImpl
import chip.platform.NsdManagerServiceBrowser
import chip.platform.NsdManagerServiceResolver
import chip.platform.PreferencesConfigurationManager
import chip.platform.PreferencesKeyValueStoreManager
Expand All @@ -51,7 +52,7 @@ object ChipClient {
if (!this::androidPlatform.isInitialized && context != null) {
//force ChipDeviceController load jni
ChipDeviceController.loadJni()
androidPlatform = AndroidChipPlatform(AndroidBleManager(), PreferencesKeyValueStoreManager(context), PreferencesConfigurationManager(context), NsdManagerServiceResolver(context), ChipMdnsCallbackImpl(), DiagnosticDataProviderImpl(context))
androidPlatform = AndroidChipPlatform(AndroidBleManager(), PreferencesKeyValueStoreManager(context), PreferencesConfigurationManager(context), NsdManagerServiceResolver(context), NsdManagerServiceBrowser(context), ChipMdnsCallbackImpl(), DiagnosticDataProviderImpl(context))
}
return androidPlatform
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,30 @@ import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.fragment.app.Fragment
import com.google.chip.chiptool.ChipClient
import com.google.chip.chiptool.R
import com.google.chip.chiptool.setuppayloadscanner.BarcodeFragment
import com.google.chip.chiptool.setuppayloadscanner.CHIPDeviceInfo
import com.google.chip.chiptool.util.FragmentUtil
import kotlinx.android.synthetic.main.address_commissioning_fragment.addressEditText
import kotlinx.android.synthetic.main.address_commissioning_fragment.commissionBtn
import kotlinx.android.synthetic.main.address_commissioning_fragment.discoverBtn
import kotlinx.android.synthetic.main.address_commissioning_fragment.discoverListSpinner
import kotlinx.android.synthetic.main.address_commissioning_fragment.discriminatorEditText
import kotlinx.android.synthetic.main.address_commissioning_fragment.pincodeEditText
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class AddressCommissioningFragment : Fragment() {
private val ipAddressList = ArrayList<String>()
private val scope = CoroutineScope(Dispatchers.Main + Job())

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
Expand Down Expand Up @@ -45,6 +58,39 @@ class AddressCommissioningFragment : Fragment() {
)
)
}

discoverBtn.setOnClickListener { _ ->
discoverBtn.isEnabled = false
val deviceController = ChipClient.getDeviceController(requireContext())
deviceController.discoverCommissionableNodes()
scope.launch {
delay(7000)
updateSpinner()
discoverBtn.isEnabled = true
}
}
}

private fun updateSpinner() {
val deviceController = ChipClient.getDeviceController(requireContext())
for(i in 0..10) {
val device = deviceController.getDiscoveredDevice(i) ?: break
ipAddressList.add("${device.ipAddress}, ${device.discriminator}")
}
requireActivity().runOnUiThread {
discoverListSpinner.adapter =
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, ipAddressList)
discoverListSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val address = ipAddressList[position].split(",")[0].trim()
val discriminator = ipAddressList[position].split(",")[1].trim()
addressEditText.setText(address)
discriminatorEditText.setText(discriminator)
}

override fun onNothingSelected(parent: AdapterView<*>) {}
}
}
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
app:layout_constraintTop_toTopOf="parent" />

<androidx.constraintlayout.helper.widget.Flow
android:id="@+id/address_commissioning_fragment_flow"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:constraint_referenced_ids="addressLabel,addressEditText,discriminatorLabel,discriminatorEditText,pincodeLabel,pincodeEditText"
Expand Down Expand Up @@ -74,6 +75,28 @@
android:inputType="number"
android:text="@string/default_pincode" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/address_commissioning_fragment_flow">

<Button
android:id="@+id/discoverBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dns_discover_btn_text"/>

<Spinner
android:id="@+id/discoverListSpinner"
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>
<Button
android:id="@+id/commissionBtn"
android:layout_width="wrap_content"
Expand Down
1 change: 1 addition & 0 deletions src/android/CHIPTool/app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
<string name="enter_discriminator_label_text">Discriminator</string>
<string name="enter_pincode_label_text">Pincode</string>
<string name="commission_btn_text">Commission</string>
<string name="dns_discover_btn_text">Discover</string>

<string name="send_command_on_btn_text">On</string>
<string name="send_command_off_btn_text">Off</string>
Expand Down
1 change: 1 addition & 0 deletions src/controller/java/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ android_library("java") {
"src/chip/devicecontroller/ChipCommandType.java",
"src/chip/devicecontroller/ChipDeviceController.java",
"src/chip/devicecontroller/ChipDeviceControllerException.java",
"src/chip/devicecontroller/DiscoveredDevice.java",
"src/chip/devicecontroller/GetConnectedDeviceCallbackJni.java",
"src/chip/devicecontroller/NetworkCredentials.java",
"src/chip/devicecontroller/NetworkLocation.java",
Expand Down
49 changes: 49 additions & 0 deletions src/controller/java/CHIPDeviceController-JNI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,55 @@ JNI_METHOD(void, updateDevice)(JNIEnv * env, jobject self, jlong handle, jlong f
}
}

JNI_METHOD(void, discoverCommissionableNodes)(JNIEnv * env, jobject self, jlong handle)
{
chip::DeviceLayer::StackLock lock;

AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle);
chip::Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kNone, (uint64_t) 0);

CHIP_ERROR err = wrapper->Controller()->DiscoverCommissionableNodes(filter);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Controller, "Failed to discoverCommissionableNodes");
JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err);
}
}

JNI_METHOD(jobject, getDiscoveredDevice)(JNIEnv * env, jobject self, jlong handle, jint idx)
{
chip::DeviceLayer::StackLock lock;

AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle);
const Dnssd::DiscoveredNodeData * data = wrapper->Controller()->GetDiscoveredDevice(idx);

if (data == nullptr)
{
return nullptr;
}

jclass discoveredDeviceCls = env->FindClass("chip/devicecontroller/DiscoveredDevice");
jmethodID constructor = env->GetMethodID(discoveredDeviceCls, "<init>", "()V");

jfieldID discrminatorID = env->GetFieldID(discoveredDeviceCls, "discriminator", "J");
jfieldID ipAddressID = env->GetFieldID(discoveredDeviceCls, "ipAddress", "Ljava/lang/String;");

jobject discoveredObj = env->NewObject(discoveredDeviceCls, constructor);

env->SetLongField(discoveredObj, discrminatorID, data->commissionData.longDiscriminator);

char ipAddress[100];
data->resolutionData.ipAddress[0].ToString(ipAddress, 100);
jstring jniipAdress = env->NewStringUTF(ipAddress);
env->SetObjectField(discoveredObj, ipAddressID, jniipAdress);

if (data == nullptr)
{
ChipLogError(Controller, "GetDiscoveredDevice - not found");
}
return discoveredObj;
}

JNI_METHOD(jboolean, openPairingWindow)(JNIEnv * env, jobject self, jlong handle, jlong devicePtr, jint duration)
{
chip::DeviceLayer::StackLock lock;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,18 @@ public void updateDevice(long fabricId, long deviceId) {
updateDevice(deviceControllerPtr, fabricId, deviceId);
}

/**
* Get commmissionible Node. Commmissionible Node results are able to get using {@link
* ChipDeviceController.getDiscoveredDevice}.
*/
public void discoverCommissionableNodes() {
discoverCommissionableNodes(deviceControllerPtr);
}

public DiscoveredDevice getDiscoveredDevice(int idx) {
return getDiscoveredDevice(deviceControllerPtr, idx);
}

public boolean openPairingWindow(long devicePtr, int duration) {
return openPairingWindow(deviceControllerPtr, devicePtr, duration);
}
Expand Down Expand Up @@ -436,6 +448,10 @@ private native void getConnectedDevicePointer(

private native void updateDevice(long deviceControllerPtr, long fabricId, long deviceId);

private native void discoverCommissionableNodes(long deviceControllerPtr);

private native DiscoveredDevice getDiscoveredDevice(long deviceControllerPtr, int idx);

private native boolean openPairingWindow(long deviceControllerPtr, long devicePtr, int duration);

private native boolean openPairingWindowWithPIN(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright (c) 2020-2021 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package chip.devicecontroller;

public class DiscoveredDevice {
public long discriminator;
public String ipAddress;
}
19 changes: 13 additions & 6 deletions src/platform/android/AndroidChipPlatform-JNI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -230,19 +230,26 @@ JNI_METHOD(void, setDiagnosticDataProviderManager)(JNIEnv * env, jclass self, jo
chip::DeviceLayer::DiagnosticDataProviderImpl::GetDefaultInstance().InitializeWithObject(manager);
}

// for ServiceResolver
JNI_METHOD(void, nativeSetServiceResolver)(JNIEnv * env, jclass self, jobject resolver, jobject chipMdnsCallback)
// for ServiceResolver and ServiceBrowser
JNI_METHOD(void, nativeSetDnssdDelegates)(JNIEnv * env, jclass self, jobject resolver, jobject browser, jobject chipMdnsCallback)
{
chip::DeviceLayer::StackLock lock;
chip::Dnssd::InitializeWithObjects(resolver, chipMdnsCallback);
chip::Dnssd::InitializeWithObjects(resolver, browser, chipMdnsCallback);
}

JNI_MDNSCALLBACK_METHOD(void, handleServiceResolve)
(JNIEnv * env, jclass self, jstring instanceName, jstring serviceType, jstring address, jint port, jobject attributes,
jlong callbackHandle, jlong contextHandle)
(JNIEnv * env, jclass self, jstring instanceName, jstring serviceType, jstring hostName, jstring address, jint port,
jobject attributes, jlong callbackHandle, jlong contextHandle)
{
using ::chip::Dnssd::HandleResolve;
HandleResolve(instanceName, serviceType, address, port, attributes, callbackHandle, contextHandle);
HandleResolve(instanceName, serviceType, hostName, address, port, attributes, callbackHandle, contextHandle);
}

JNI_MDNSCALLBACK_METHOD(void, handleServiceBrowse)
(JNIEnv * env, jclass self, jobjectArray instanceName, jstring serviceType, jlong callbackHandle, jlong contextHandle)
{
using ::chip::Dnssd::HandleBrowse;
HandleBrowse(instanceName, serviceType, callbackHandle, contextHandle);
}

#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
Expand Down
2 changes: 2 additions & 0 deletions src/platform/android/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,11 @@ android_library("java") {
"java/chip/platform/DiagnosticDataProviderImpl.java",
"java/chip/platform/KeyValueStoreManager.java",
"java/chip/platform/NetworkInterface.java",
"java/chip/platform/NsdManagerServiceBrowser.java",
"java/chip/platform/NsdManagerServiceResolver.java",
"java/chip/platform/PreferencesConfigurationManager.java",
"java/chip/platform/PreferencesKeyValueStoreManager.java",
"java/chip/platform/ServiceBrowser.java",
"java/chip/platform/ServiceResolver.java",
]

Expand Down
Loading

0 comments on commit e476e4e

Please sign in to comment.