Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.user.waterpumpcontrol;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothSocket;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Handler;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.UUID;
- public class MainActivity extends AppCompatActivity {
- private BluetoothAdapter BA;
- private int REQUEST_ENABLE_BT = 1;
- private static final String APC = "PUMPCTRL"; // HC-05 Bluetooth module device name
- private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // HC-05 Bluetooth module unique ID
- private BluetoothDevice mmDevice; // BT connected device
- private OutputStream mmOutputStream; // BT application output
- private InputStream mmInputStream; // BT application input
- private int btConnected; // conformation that BT is connected
- Thread workerThread;
- Handler bluetoothIn;
- final int handlerState = 0; // used to identify handler message (only using one msg)
- private StringBuilder recDataString = new StringBuilder();
- Button btnSetIdle, btnRtvIdle, btnFlush;
- TextView tvTempP, tvTempRadIn, tvTempRadOut, tvFlowPrime, tvFlowSecond, tvPStatus;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // menu items
- setContentView(R.layout.activity_main);
- // buttons
- btnSetIdle = (Button) findViewById(R.id.setValBtn);
- btnRtvIdle = (Button) findViewById(R.id.rtValBtn);
- btnFlush = (Button) findViewById(R.id.flushBtn);
- // updatable text fields
- tvTempP = (TextView) findViewById(R.id.tempReadP);
- tvTempRadIn = (TextView) findViewById(R.id.tempReadIn);
- tvTempRadOut = (TextView) findViewById(R.id.tempReadOut);
- tvFlowPrime = (TextView) findViewById(R.id.flowRead1);
- tvFlowSecond = (TextView) findViewById(R.id.flowRead2);
- tvPStatus = (TextView) findViewById(R.id.pumpStatus);
- // Register the BroadcastReceiver
- IntentFilter filter = new IntentFilter();
- filter.addAction(BluetoothDevice.ACTION_FOUND);
- filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
- filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
- filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
- registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
- BA = BluetoothAdapter.getDefaultAdapter();
- bluetoothIn = new Handler() {
- public void handleMessage(android.os.Message msg) {
- if (msg.what == handlerState) {//if message is what we want
- //Toast.makeText(MainActivity.this, "DATA RECEIVED", Toast.LENGTH_SHORT).show();
- byte[] readBuf = (byte[]) msg.obj;
- String readMessage = new String(readBuf, 0, msg.arg1); // msg.arg1 = bytes from connect thread; converting to string
- recDataString.append(readMessage); //~: always the last character in a string from the Arduino
- //Toast.makeText(MainActivity.this, readMessage, Toast.LENGTH_SHORT).show();
- int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
- if (endOfLineIndex > 0) { // make sure there data before ~
- if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
- {
- String tempPRead = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
- String tempRadInRead = recDataString.substring(5, 9); //same again...
- String tempRadOutRead = recDataString.substring(9, 13);
- String flow1Read = recDataString.substring(13, 17);
- String flow2Read = recDataString.substring(17, 21);
- tvTempP.setText(tempPRead); //update the textviews with sensor values
- tvTempRadIn.setText(tempRadInRead);
- tvTempRadOut.setText(tempRadOutRead);
- tvFlowPrime.setText(flow1Read);
- tvFlowSecond.setText(flow2Read);
- }
- else if (recDataString.charAt(0) == '?') //if it starts with ?, conformation of idle values set
- {
- Toast.makeText(MainActivity.this, "Idle conditions set.", Toast.LENGTH_SHORT).show();
- }
- else if (recDataString.charAt(0) == '!') //if it starts with !, idle sensor values have been sent
- {
- int idleFlowStart = recDataString.indexOf("+"); //the separator between both sensor readings sent as a combined string
- String idleTemp = recDataString.substring(1, idleFlowStart);
- String idleFlow = recDataString.substring((idleFlowStart+1), endOfLineIndex);
- String toast = "Temp C= " + idleTemp + ", Flow L/min= " + idleFlow;
- Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
- }
- else if (recDataString.charAt(0) == '$') //if it starts with $, pump will turn on for 10sec
- {
- Toast.makeText(MainActivity.this, "Pump on for 20 seconds.", Toast.LENGTH_SHORT).show();
- }
- else if (recDataString.charAt(0) == '*') //if it starts with *, update pump on/off status
- {
- if (recDataString.charAt(1) == '1'){
- tvPStatus.setText("ON");
- }
- else if (recDataString.charAt(1) == '2'){
- tvPStatus.setText("OFF");
- }
- }
- recDataString.delete(0, recDataString.length()); //clear all string data
- }
- }
- }
- };
- // onclick button listeners
- btnSetIdle.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) { // if button "set idle conditions" is pressed
- try {
- sendData(1);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- btnRtvIdle.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) { // if button "retrieve idle conditions" is pressed
- try {
- sendData(2);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- btnFlush.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) { // if button "flush coolant system" is pressed
- try {
- sendData(3);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- }
- @Override
- public void onDestroy() {
- unregisterReceiver(mReceiver);
- if (BA.isDiscovering()) {
- BA.cancelDiscovery();
- }
- super.onDestroy();
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- // if "Connect to Bluetooth" is selected from the menu
- if (id == R.id.action_settings) {
- if (BA != null) {
- if (!BA.isEnabled()) {
- enableBT(0);
- } else {
- searchConnect();
- }
- } else {
- Toast.makeText(MainActivity.this, "No Bluetooth adapter found.", Toast.LENGTH_SHORT).show();
- }
- }
- return super.onOptionsItemSelected(item);
- }
- public int enableBT(int msg) {
- if (msg == 1) {
- Toast.makeText(MainActivity.this, "Bluetooth must remain enabled for app use.", Toast.LENGTH_SHORT).show();
- }
- Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
- return 0;
- }
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == REQUEST_ENABLE_BT) {
- if (resultCode == RESULT_OK) {
- Toast.makeText(MainActivity.this, "Bluetooth enabled.", Toast.LENGTH_SHORT).show();
- searchConnect();
- } else {
- Toast.makeText(MainActivity.this, "Please enable Bluetooth.", Toast.LENGTH_SHORT).show();
- enableBT(0);
- }
- }
- }
- public void searchConnect() {
- BA.startDiscovery();
- }
- private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- Bundle extras = intent.getExtras();
- final int FAIL = -1;
- if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
- Toast.makeText(MainActivity.this, "BT discovery started.", Toast.LENGTH_SHORT).show(); // search for PUMPCTRL has started
- }
- else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
- Toast.makeText(MainActivity.this, "BT discovery finished.", Toast.LENGTH_SHORT).show(); // search for PUMPCTRL has finished
- }
- else if (BluetoothDevice.ACTION_FOUND.equals(action)) { // bluetooth device found
- BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- if (device.getName().equals(APC)) { // if one of the Bluetooth devices are named "PUMPCTRL", connect to it
- mmDevice = device;
- try {
- openBT();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- else if ("android.bluetooth.adapter.action.STATE_CHANGED".equals(action)) {
- bluetoothStateChanged(extras.getInt("android.bluetooth.adapter.extra.STATE", FAIL));
- }
- }
- };
- private void bluetoothStateChanged(int state) {
- switch (state) {
- case BluetoothAdapter.STATE_OFF: {
- break;
- }
- case BluetoothAdapter.STATE_TURNING_ON: {
- break;
- }
- case BluetoothAdapter.STATE_ON: {
- break;
- }
- case BluetoothAdapter.STATE_TURNING_OFF: { // if BT is turned off while using app, turn it back on
- enableBT(1);
- break;
- }
- }
- }
- void openBT() throws IOException {
- BluetoothSocket mmSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
- mmSocket.connect();
- mmOutputStream = mmSocket.getOutputStream();
- mmInputStream = mmSocket.getInputStream();
- btConnected = 1;
- beginListenForData();
- }
- void beginListenForData() {
- workerThread = new Thread(new Runnable() { // A thread is used to perform intensive tasks in the background
- public void run() { // of a main activity in order to prevent visible lag to the user
- byte[] readBuffer = new byte[512];
- int msgLength;
- while(true) {
- try {
- int bytesAvailable = mmInputStream.available();
- if(bytesAvailable > 0) { // if there is a transmission to receive
- msgLength = mmInputStream.read(readBuffer); // store bytes in buffer variable
- bluetoothIn.obtainMessage(handlerState, msgLength, -1, readBuffer).sendToTarget(); // send buffer data of length "msgLength" out of work thread to
- } // handler for output on main activity window
- }
- catch (IOException ex) {
- break;
- }
- }
- }
- });
- workerThread.start();
- }
- void sendData(int i) throws IOException {
- if(btConnected == 1){
- mmOutputStream.write(i);
- }
- else{
- Toast.makeText(MainActivity.this, "Bluetooth not connected.", Toast.LENGTH_SHORT).show();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement