Skip to content

Commit

Permalink
Android add discover (#10682)
Browse files Browse the repository at this point in the history
* Add Android Discover

* Fix Build error

* Modify coding rule, string xml

* Modify coding style

* Restyled by google-java-format

* Restyled by gn

* Change browse using android platform layer

* Restyled by whitespace

* Restyled by google-java-format

* Restyled by clang-format

* Restyled by clang-format

* Modify after review

* Remove unused code

* Restyled by google-java-format

* Restyled by gn

* Modify some issue

* Fix some issue after reviewing

* restore file

* Restyled by clang-format

Co-authored-by: Restyled.io <[email protected]>
  • Loading branch information
2 people authored and pull[bot] committed Nov 5, 2021
1 parent 80775bb commit 1645940
Show file tree
Hide file tree
Showing 19 changed files with 589 additions and 30 deletions.
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())
AndroidChipPlatform.defaultInstance(this)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,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())
androidPlatform = AndroidChipPlatform.defaultInstance(context)
}
return androidPlatform
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ 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
Expand All @@ -13,10 +15,21 @@ 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 @@ -46,6 +59,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 @@ -37,6 +37,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 @@ -69,6 +69,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/PaseVerifierParams.java",
"zap-generated/chip/devicecontroller/ChipClusters.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 @@ -352,6 +352,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 = chip::Dnssd::DiscoveryFilter();

CHIP_ERROR err = wrapper->Controller()->DiscoverCommissionableNodes(filter);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Controller, "Failed to discoverCommissionableNodes");
ThrowError(env, 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->longDiscriminator);

char ipAddress[100];
data->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 @@ -196,6 +196,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 @@ -259,6 +271,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 @@ -210,19 +210,26 @@ JNI_METHOD(void, setConfigurationManager)(JNIEnv * env, jclass self, jobject man
chip::DeviceLayer::ConfigurationMgrImpl().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, 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, 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 @@ -75,9 +75,11 @@ android_library("java") {
"java/chip/platform/ChipMdnsCallbackImpl.java",
"java/chip/platform/ConfigurationManager.java",
"java/chip/platform/KeyValueStoreManager.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 1645940

Please sign in to comment.