Giter Site home page Giter Site logo

java-obd-api's Introduction

Java OBD API

An OBD-II API written in Java. Based on obd-java-api.

Quickstart

Android

Just include it into the build.gradle file:

   dependencies {
     ...

     // Java OBD API
     implementation 'com.github.eltonvs:java-obd-api:0.0.1'
   }

Maven

You only need to include it into your pom.xml file:

   <dependency>
     <groupId>com.github.eltonvs</groupId>
     <artifactId>java-obd-api</artifactId>
     <version>0.0.1</version>
   </dependency>

Sample Usage

After pairing and establishing a Bluetooth connection with your OBD device.

// retrieve Bluetooth socket
socket = ...; // specific to the VM you're using (Java, Android, etc.)

// Group many obd commands into a single command ()
ObdCommandGroup obdCommands = new ObdCommandGroup();
obdCommands.add(new EchoOffCommand());
obdCommands.add(new LineFeedOffCommand());
obdCommands.add(new TimeoutCommand(timeout));
obdCommands.add(new SelectProtocolCommand(protocol));

// Run all commands at once
obdCommands.run(socket.getInputStream(), socket.getOutputStream());

Contributing

We're open for contributions!

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the Apache 2.0 - see the LICENSE file for details

Acknowledgments

java-obd-api's People

Contributors

dependabot-preview[bot] avatar eltonvs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-obd-api's Issues

Only can pair to ELM327, but can't establish the connection to transfer data

Hello, Elton. I wonder if you're still active, but I need help. So here is the problem. I'm able to pair with my ELM327, but somehow can't keep the connection established after I enter the code (1234). Here's my code:

public class MainActivity extends AppCompatActivity {

public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ACCESS_FINE_LOCATION = 2;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;

private ListView listview;
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> listAdapter;
private List<String> device_name = new ArrayList<>();
private List<String> device_address = new ArrayList<>();
private BluetoothSocket cnt_socket;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // we get bluetooth adapter
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    listview = findViewById(R.id.listview);

    // we create a simple array adapter to display devices detected
    listAdapter = new ArrayAdapter<>(this, R.layout.list_style);
    listview.setAdapter(listAdapter);

    // pairing
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            bluetoothAdapter.cancelDiscovery();
            startThread(position);
        }
    });

    // we check bluetooth state
    checkBluetoothState();

    // we start scanning
    scan();

    //we check permission a start of the app
    checkCoarseLocationPermission();
    checkFineLocationPermission();
}

public void scan() {
    if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
        // we check if coarse location must be asked
        if (checkCoarseLocationPermission()) {
            listAdapter.clear();
            device_name.clear();
            device_address.clear();
            bluetoothAdapter.startDiscovery();
        }
    } else {
        checkBluetoothState();
    }
}

public void startThread(int position) {
    BluetoothConnect btConnect = new BluetoothConnect(position);
    btConnect.start();
    Toast.makeText(this, "Connecting ...", Toast.LENGTH_SHORT).show();
}

class BluetoothConnect extends Thread {
    int position;

    BluetoothConnect(int position) {
        this.position = position;
    }

    @Override
    public void run() {
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

        BluetoothDevice device = btAdapter.getRemoteDevice(device_address.get(position));

        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

        BluetoothSocket socket = null;
        try {
            socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            socket.connect();
            cnt_socket = socket;
        } catch (IOException e) {
            e.printStackTrace();
        }

        device.createBond();
    }
}

@Override
protected void onResume() {
    super.onResume();
    // we register a dedicated receiver for some Bluetooth actions
    registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
    registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED));
    registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
    registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}

protected void onPause() {
    super.onPause();
    unregisterReceiver(devicesFoundReceiver);
}

private boolean checkCoarseLocationPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                REQUEST_ACCESS_COARSE_LOCATION);
        return false;
    } else {
        return true;
    }
}

private boolean checkFineLocationPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_ACCESS_FINE_LOCATION);
        return false;
    } else {
        return true;
    }
}

private void checkBluetoothState() {
    if (bluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not supported on your device!", Toast.LENGTH_SHORT).show();
    } else {
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, "You need to enable Bluetooth", Toast.LENGTH_SHORT).show();
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
        checkBluetoothState();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case REQUEST_ACCESS_COARSE_LOCATION:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Access coarse location allowed. You can scan Bluetooth devices", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Access coarse location forbidden. You can't scan Bluetooth devices", Toast.LENGTH_SHORT).show();
            }
            break;
    }
}

@Override
public void onBackPressed() {
    super.onBackPressed();

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

// we need to implement our receiver to get devices detected
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getName() != null && !device_address.contains(device.getAddress())) {
                listAdapter.add(device.getName() + "\n" + device.getAddress());
                listAdapter.notifyDataSetChanged();
                device_name.add(device.getName());
                device_address.add(device.getAddress());
            }
        } else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            try {
                new EchoOffCommand().run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
                new LineFeedOffCommand().run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
                new TimeoutCommand(125).run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
                new SelectProtocolCommand(ObdProtocols.AUTO).run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
                new AmbientAirTemperatureCommand().run(cnt_socket.getInputStream(), cnt_socket.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

        } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            Toast.makeText(context, "Showing device(s), please wait ...", Toast.LENGTH_LONG).show();
        }
    }
};

}

Would you mind to help? :(

static values when retrieving data

Hi elton,
when i retrieve data from the elm237 device with your library, i always get a static values. for example, vehicle speed is always either 52 km\h or 65 km\h. i have tried different protocols. do you know what could be the problem?
thanks, doron.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.