From ce5cf7b573a6a10b37e88f592b5cdd6c03d40b77 Mon Sep 17 00:00:00 2001 From: Tomek Zebrowski Date: Thu, 21 Mar 2024 08:23:23 +0100 Subject: [PATCH] fix: Fix integration with obd-metrics --- app/build.gradle | 27 +--- .../BluetoothConnection.java | 120 ++++++------------ .../simpleobdjavatest/MainActivity.java | 11 +- .../OBDBluetoothService.java | 34 +---- build.gradle | 2 +- 5 files changed, 61 insertions(+), 133 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index fa1e8a0..232af9d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -40,11 +40,11 @@ android { composeOptions { kotlinCompilerExtensionVersion '1.4.3' } - packaging { - resources { - excludes += '/META-INF/{AL2.0,LGPL2.1}' - } - } +// packaging { +// resources { +// excludes += '/META-INF/{AL2.0,LGPL2.1}' +// } +// } } dependencies { @@ -68,34 +68,21 @@ dependencies { implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' implementation 'androidx.fragment:fragment-ktx:1.6.2' - implementation 'org.osmdroid:osmdroid-android:6.1.10' - implementation 'org.osmdroid:osmdroid-wms:6.1.10' - implementation 'org.osmdroid:osmdroid-mapsforge:6.1.10' - implementation 'org.osmdroid:osmdroid-geopackage:6.1.10' - implementation 'com.google.zxing:core:3.4.0' - implementation 'com.journeyapps:zxing-android-embedded:4.2.0' - implementation('com.google.android.gms:play-services-location:21.2.0') implementation 'androidx.activity:activity-ktx:1.8.2' implementation 'androidx.activity:activity-compose:1.8.2' implementation 'androidx.core:core-splashscreen:1.0.1' + implementation 'pub.devrel:easypermissions:3.0.0' - // Brings the new BluetoothLeScanner API to older platforms - implementation 'no.nordicsemi.android:log:2.3.0' - implementation 'no.nordicsemi.android.support.v18:scanner:1.6.0' - // Android BLE Library - implementation 'no.nordicsemi.android:ble:2.5.1' //noinspection GradleCompatible implementation 'androidx.appcompat:appcompat:1.6.1' //noinspection GradleCompatible implementation 'com.google.android.material:material:1.11.0' - implementation 'org.tensorflow:tensorflow-lite:2.14.0' - implementation 'org.tensorflow:tensorflow-lite-gpu:2.14.0' annotationProcessor 'androidx.hilt:hilt-compiler:1.2.0' implementation "androidx.car.app:app:1.2.0" - implementation "com.github.pires:obd-java-api:1.0" + annotationProcessor 'androidx.room:room-compiler:2.6.1' //noinspection GradleCompatible diff --git a/app/src/main/java/com/example/simpleobdjavatest/BluetoothConnection.java b/app/src/main/java/com/example/simpleobdjavatest/BluetoothConnection.java index c347e26..64d0350 100644 --- a/app/src/main/java/com/example/simpleobdjavatest/BluetoothConnection.java +++ b/app/src/main/java/com/example/simpleobdjavatest/BluetoothConnection.java @@ -3,7 +3,10 @@ import android.annotation.SuppressLint; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothSocket; +import android.content.Context; +import android.os.ParcelUuid; import android.util.Log; import org.obd.metrics.transport.AdapterConnection; @@ -16,62 +19,68 @@ public class BluetoothConnection implements AdapterConnection { private static final String LOGGER_TAG = "BluetoothConnection"; - private static final UUID RFCOMM_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); - private final String deviceName; + private final String deviceAddress; private BluetoothSocket socket; private InputStream input; private OutputStream output; - public BluetoothConnection(String deviceName) { - this.deviceName = deviceName; - Log.i(LOGGER_TAG, "Created instance of BluetoothConnection with device: " + deviceName); + public BluetoothConnection(String deviceAddress) { + this.deviceAddress = deviceAddress; + Log.i(LOGGER_TAG, "Created instance of BluetoothConnection with device: " + deviceAddress); } @Override public void reconnect() { try { - Log.i(LOGGER_TAG, "Reconnecting to the device: " + deviceName); + Log.i(LOGGER_TAG, "Reconnecting to the device: " + deviceAddress); close(); TimeUnit.MILLISECONDS.sleep(1000); connect(); - Log.i(LOGGER_TAG, "Successfully reconnected to the device: " + deviceName); + Log.i(LOGGER_TAG, "Successfully reconnected to the device: " + deviceAddress); } catch (InterruptedException | IOException e) { - Log.e(LOGGER_TAG, "Error reconnecting to the device: " + deviceName, e); + Log.e(LOGGER_TAG, "Error reconnecting to the device: " + deviceAddress, e); } } - @SuppressLint("MissingPermission") @Override public void connect() throws IOException { - BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - BluetoothDevice device = null; - - if (bluetoothAdapter != null) { - for (BluetoothDevice bondedDevice : bluetoothAdapter.getBondedDevices()) { - if (bondedDevice.getName() != null && bondedDevice.getName().contains("OBD")) { - device = bondedDevice; - Log.i(LOGGER_TAG, "OBD Device found: " + bondedDevice.getName()); - break; + try{ + + BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); + BluetoothDevice adapter = null; + + if (bluetoothAdapter != null) { + + for (BluetoothDevice bondedDevice : bluetoothAdapter.getBondedDevices()) { + if (bondedDevice.getName() != null && bondedDevice.getAddress().equals(deviceAddress)) { + adapter = bondedDevice; + Log.i(LOGGER_TAG, "OBD Device found: " + bondedDevice.getName()); + break; + } } - } - if (device == null) { - throw new IOException("Device not found: " + deviceName); - } + if (null == adapter) { + throw new IOException("Device not found: " + deviceAddress); + } - socket = device.createRfcommSocketToServiceRecord(RFCOMM_UUID); - socket.connect(); + final ParcelUuid[] uuids = adapter.getUuids(); + final UUID uuid = uuids[0].getUuid(); + socket = adapter.createInsecureRfcommSocketToServiceRecord(uuid); + socket.connect(); - if (socket.isConnected()) { - input = socket.getInputStream(); - output = socket.getOutputStream(); - Log.i(LOGGER_TAG, "Successfully connected to the device: " + deviceName); + if (socket.isConnected()) { + input = socket.getInputStream(); + output = socket.getOutputStream(); + Log.e(LOGGER_TAG, "Successfully connected to the adapter: " + deviceAddress); + } else { + throw new IOException("Failed to connect to the adapter: " + deviceAddress); + } } else { - throw new IOException("Failed to connect to the device: " + deviceName); + throw new IOException("BluetoothAdapter not found"); } - } else { - throw new IOException("BluetoothAdapter not found"); + }catch (SecurityException e){ + Log.e(LOGGER_TAG,"Failed to connect to BT due to missing permissions.",e); } } @@ -87,9 +96,9 @@ public void close() { if (socket != null) { socket.close(); } - Log.i(LOGGER_TAG, "Socket for the device: " + deviceName + " is closed."); + Log.i(LOGGER_TAG, "Socket for the device: " + deviceAddress + " is closed."); } catch (IOException e) { - Log.e(LOGGER_TAG, "Error closing the socket: " + deviceName, e); + Log.e(LOGGER_TAG, "Error closing the socket: " + deviceAddress, e); } } @@ -102,49 +111,4 @@ public OutputStream openOutputStream() { public InputStream openInputStream() { return input; } - - @SuppressLint("MissingPermission") - private void connectToDevice() { - BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - if (bluetoothAdapter == null) { - Log.i(LOGGER_TAG, "Bluetooth not supported on this device"); - return; - } - - try { - Log.i(LOGGER_TAG, "Found bounded connections, size: " + bluetoothAdapter.getBondedDevices().size()); - BluetoothDevice adapter = null; - - // find Bluetooth deviceName - for (BluetoothDevice bondedDevice : bluetoothAdapter.getBondedDevices()) { - if (deviceName.equals(bondedDevice.getName())) { - adapter = bondedDevice; - break; - } - } - - if (adapter != null) { - Log.i(LOGGER_TAG, "Opening connection to bounded device: " + adapter.getName()); - socket = adapter.createRfcommSocketToServiceRecord(RFCOMM_UUID); - socket.connect(); - Log.i(LOGGER_TAG, "Doing socket connect for: " + adapter.getName()); - - if (socket.isConnected()) { - Log.i(LOGGER_TAG, "Successfully established connection for: " + adapter.getName()); - input = socket.getInputStream(); - output = socket.getOutputStream(); - Log.i(LOGGER_TAG, "Successfully opened the sockets to device: " + adapter.getName()); - } else { - Log.e(LOGGER_TAG, "Failed to connect to the device: " + adapter.getName()); - } - } else { - Log.e(LOGGER_TAG, "Device not found: " + deviceName); - } - } catch (IOException e) { - Log.e(LOGGER_TAG, "Failed to connect to the device: " + deviceName, e); - } catch (SecurityException e) { - Log.e(LOGGER_TAG, "Security exception: permissions might be missing.", e); - } - } - } \ No newline at end of file diff --git a/app/src/main/java/com/example/simpleobdjavatest/MainActivity.java b/app/src/main/java/com/example/simpleobdjavatest/MainActivity.java index 54443ff..d1ce80f 100644 --- a/app/src/main/java/com/example/simpleobdjavatest/MainActivity.java +++ b/app/src/main/java/com/example/simpleobdjavatest/MainActivity.java @@ -1,6 +1,10 @@ package com.example.simpleobdjavatest; +import android.Manifest; import android.annotation.SuppressLint; +import android.app.Activity; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -12,8 +16,10 @@ import com.example.simpleobdjavatest.databinding.ActivityMainBinding; -public class MainActivity extends AppCompatActivity { +import pub.devrel.easypermissions.EasyPermissions; + +public class MainActivity extends AppCompatActivity { private ActivityMainBinding binding; @SuppressLint("MissingPermission") @@ -46,14 +52,15 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); + EasyPermissions.requestPermissions(this,"I need BT permissions ",1, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_CONNECT); - // initialize BroadcastReceiver IntentFilter filter = new IntentFilter(OBDBluetoothService.ACTION_OBD_STATE); registerReceiver(connectionStateReceiver, filter); Log.i("MainActivity","Start OBD-II BluetoothService"); Intent bsdIntent = new Intent(this, OBDBluetoothService.class); startService(bsdIntent); + } @Override diff --git a/app/src/main/java/com/example/simpleobdjavatest/OBDBluetoothService.java b/app/src/main/java/com/example/simpleobdjavatest/OBDBluetoothService.java index 8f8de36..9c41fb4 100644 --- a/app/src/main/java/com/example/simpleobdjavatest/OBDBluetoothService.java +++ b/app/src/main/java/com/example/simpleobdjavatest/OBDBluetoothService.java @@ -2,14 +2,11 @@ import android.annotation.SuppressLint; import android.app.Service; -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.IBinder; import androidx.annotation.Nullable; -import org.assertj.core.api.Assertions; import org.obd.metrics.api.Workflow; import org.obd.metrics.api.model.AdaptiveTimeoutPolicy; import org.obd.metrics.api.model.Adjustments; @@ -22,11 +19,9 @@ import org.obd.metrics.api.model.ProducerPolicy; import org.obd.metrics.api.model.Query; import org.obd.metrics.command.group.DefaultCommandGroup; -import org.obd.metrics.diagnostic.RateType; import java.io.IOException; import java.util.Objects; -import java.util.Set; import java.util.concurrent.ExecutionException; public class OBDBluetoothService extends Service { @@ -46,7 +41,7 @@ public int onStartCommand(Intent intent, int flags, int startId) { } public void test() throws IOException, InterruptedException, ExecutionException { -// AdapterConnection connection = BluetoothConnection.connect(getDeviceByName("OBD")); + var connection = new BluetoothConnection("AA:BB:CC:11:22:33"); var collector = new DataCollector(); final Pids pids = Pids @@ -79,32 +74,7 @@ public void test() throws IOException, InterruptedException, ExecutionException .protocol(Protocol.CAN_29) .sequence(DefaultCommandGroup.INIT).build(); -// workflow.start(connection, query, init, optional); - - WorkflowFinalizer.finalizeAfter(workflow,25000); - - var registry = workflow.getPidRegistry(); - - var intakePressure = registry.findBy(7005l); - double ratePerSec = workflow.getDiagnostics().rate().findBy(RateType.MEAN, intakePressure).get().getValue(); - - Assertions.assertThat(ratePerSec).isGreaterThanOrEqualTo(commandFrequency); - } - - @SuppressLint("MissingPermission") - private BluetoothDevice getDeviceByName(String name) { - BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - if (bluetoothAdapter != null) { - Set pairedDevices = bluetoothAdapter.getBondedDevices(); - if (pairedDevices != null && !pairedDevices.isEmpty()) { - for (BluetoothDevice device : pairedDevices) { - if (device.getName().equals(name)) { - return device; - } - } - } - } - return null; + workflow.start(connection, query, init, optional); } @Nullable diff --git a/build.gradle b/build.gradle index 068a5d0..355f08f 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,5 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { -id 'com.android.application' version '8.1.2' apply false + id 'com.android.application' version '7.4.2' apply false id 'org.jetbrains.kotlin.android' version '1.8.10' apply false } \ No newline at end of file