Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bluetooth scanning #686

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BODY_SENSORS" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.CAMERA" />
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/java/com/termux/api/TermuxApiReceiver.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import com.termux.api.apis.AudioAPI;
import com.termux.api.apis.BatteryStatusAPI;
import com.termux.api.apis.BluetoothScanAPI;
import com.termux.api.apis.BrightnessAPI;
import com.termux.api.apis.CallLogAPI;
import com.termux.api.apis.CameraInfoAPI;
Expand Down Expand Up @@ -90,6 +91,11 @@ private void doWork(Context context, Intent intent) {
case "BatteryStatus":
BatteryStatusAPI.onReceive(this, context, intent);
break;
case "BluetoothScan":
if (TermuxApiPermissionActivity.checkAndRequestPermissions(context, intent, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH, Manifest.permission.ACCESS_FINE_LOCATION)) {
BluetoothScanAPI.onReceive(context, intent);
}
break;
case "Brightness":
if (!Settings.System.canWrite(context)) {
TermuxApiPermissionActivity.checkAndRequestPermissions(context, intent, Manifest.permission.WRITE_SETTINGS);
Expand Down
122 changes: 122 additions & 0 deletions app/src/main/java/com/termux/api/apis/BluetoothScanAPI.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package com.termux.api.apis;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.JsonWriter;

import com.termux.api.util.ResultReturner;
import com.termux.shared.logger.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;

public class BluetoothScanAPI {

private static final ArrayList<BluetoothDevice> devices = new ArrayList<>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's strictly necessary to track and return last-seen timestamps. It also looks like the scan API will trigger multiple times for the same devices as it's repeatedly discovered, and a longer scan with the code would result in multiple copies of the same device in this array and the returned output.

This seems like it should be HashMap<BluetoothDevice, long>.

private static final String LOG_TAG = "BluetoothScanAPI";
private static BluetoothAdapter adapter;
private static boolean scanning = false;

private static final BroadcastReceiver receiver = new BroadcastReceiver() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please give this a better name, even though it's the only BroadcastReceiver in sight. device_found_receiver?

@Override
public void onReceive(Context context, Intent intent) {
if (Objects.equals(intent.getAction(), BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device != null) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason we'd expect an ACTION_FOUND with device == null? Add a comment if so, log an error saying "that shouldn't happen it but" did if not.

devices.add(device);
}
}
}
};

public static void onReceive(final Context context, final Intent intent) {
Logger.logDebug(LOG_TAG, "onReceive");

ResultReturner.returnData(context, intent, new ResultReturner.ResultJsonWriter() {
@Override
public void writeJson(JsonWriter out) throws Exception {
String mode = intent.getStringExtra("mode");
if (mode == null) return;
out.beginObject();
switch (mode.toLowerCase()) {
case "start":
if (start(context)) {
out.name("error").value(false);
} else {
out.name("error").value(true);
out.name("reason").value("Already running!");
Comment on lines +50 to +53
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of having two keys, how about error only being present if it has an error message and returning an empty object on success? There's approximate precedent for that in the NFC API.

}
break;
case "stop":
if (stop(context)) {
out.name("error").value(false);
printList(out, true);
} else {
out.name("error").value(true);
out.name("reason").value("Already stopped!");
}
break;
case "info":
if (scanning) {
out.name("error").value(false);
printList(out, false);
} else {
out.name("error").value(true);
out.name("reason").value("Scan is not running!");
}
break;
default:
out.name("error").value(true);
out.name("reason").value("Invalid option! Choose one from [start, stop, info]");
break;
}
out.endObject();
}
});


}

private static void printList(JsonWriter out, boolean clear) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: This method doesn't actually print. writeDiscoveredDevices, something like that?

(If you accept my suggested API change, you should remove boolean clear and clear unconditionally after calling this in the dump/poll handler.)

try {
out.name("devices");
out.beginArray();
for (BluetoothDevice device : devices) {
out.beginObject();
out.name("name").value(device.getName());
out.name("address").value(device.getAddress());
out.endObject();
}
out.endArray();
if (clear) {
devices.clear();
}
} catch (IOException ex) {
Logger.logError(Arrays.toString(ex.getStackTrace()));
}
}

private static boolean start(Context context) {
if (scanning) return false;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mega nit: { return false; }, and same in stop(), please. :)

context.getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
adapter = BluetoothAdapter.getDefaultAdapter();
adapter.startDiscovery();
scanning = true;
return true;
}

private static boolean stop(Context context) {
if (!scanning) return false;
adapter.cancelDiscovery();
context.getApplicationContext().unregisterReceiver(receiver);
scanning = false;
return true;
}

}