Skip to content

Commit

Permalink
fix: Fix integration with obd-metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
tzebrowski committed Mar 21, 2024
1 parent 0724511 commit ce5cf7b
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 133 deletions.
27 changes: 7 additions & 20 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
}
}

Expand All @@ -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);
}
}

Expand All @@ -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);
}
}

}
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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")
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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<BluetoothDevice> 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
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit ce5cf7b

Please sign in to comment.