Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package capstone.bluetooth;
- import android.Manifest;
- import android.bluetooth.BluetoothAdapter;
- import android.content.ClipboardManager;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothSocket;
- import android.content.BroadcastReceiver;
- import android.content.ClipData;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.content.pm.PackageManager;
- import android.graphics.Color;
- import android.os.SystemClock;
- import android.support.v4.app.ActivityCompat;
- import android.support.v4.content.ContextCompat;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.ArrayAdapter;
- import android.widget.CheckBox;
- import android.widget.CompoundButton;
- import android.widget.ImageButton;
- import android.widget.SeekBar;
- import android.widget.TextView;
- import android.widget.Toast;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.UnsupportedEncodingException;
- import java.lang.reflect.Method;
- import java.text.DecimalFormat;
- import java.util.List;
- import java.util.Set;
- import java.util.UUID;
- import android.os.Handler;
- import android.widget.ToggleButton;
- import capstone.bluetooth.R;
- import java.util.ArrayList;
- public class MainActivity extends AppCompatActivity {
- public boolean paused = false;
- public BluetoothAdapter mBluetoothAdapter;
- public Handler handler = new Handler();
- private IntentFilter filter;
- public int discovery_restart_time = 3000; //Discovery restrat time
- Integer counter = 0;
- private BluetoothAdapter mBTAdapter;
- private ArrayAdapter<String> mBTArrayAdapter;
- private final String TAG = MainActivity.class.getSimpleName();
- private Handler mHandler; // Our main handler that will receive callback notifications
- private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data
- private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
- private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier
- // #defines for identifying shared types between calling functions
- private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
- private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
- private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
- //nothing
- String dBm = "none";
- int updateCheck = 0;
- int timerUpdate = 0;
- int rssi = 0;
- TextView distance, signal;
- CheckBox check1;
- CheckBox check2;
- private Boolean GPIO = false;
- String distanceFinal = "-86";
- Boolean actionVibrate = false;
- Boolean vibrateBtn = true;
- Boolean lightBtn = true;
- ImageButton statusIndicator;
- SeekBar distanceSeekBar;
- TextView status, appro;
- ToggleButton vibrate;
- ToggleButton light;
- List<Integer> timeDiff = new ArrayList<>();
- Integer tempTime = 0;
- Boolean timeCheck = false;
- public void onCreate(Bundle bundle) {
- super.onCreate(bundle);
- setContentView(R.layout.activity_main);
- //ALl about bluetooth
- this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- if (!this.mBluetoothAdapter.isEnabled()) {
- startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
- }
- this.handler.post(this.discoveryTimer); //Scheduled scanner discovery restart
- this.filter = new IntentFilter("android.bluetooth.device.action.FOUND");
- registerReceiver(this.mReceiver, this.filter); //Bluetooth signal strength reciever
- mBTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
- mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
- // Ask for location permission if not already allowed
- if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
- ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
- mHandler = new Handler(){
- public void handleMessage(android.os.Message msg){
- if(msg.what == MESSAGE_READ){
- String readMessage = null;
- try {
- readMessage = new String((byte[]) msg.obj, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
- }
- };
- if (mBTArrayAdapter == null) {
- // Device does not support Bluetooth
- Toast.makeText(getApplicationContext(),"Bluetooth device not found!",Toast.LENGTH_SHORT).show();
- }
- else {
- }
- //All about text, nothing about bluetooth
- (new Thread(new Runnable()
- {
- @Override
- public void run()
- {
- while (!Thread.interrupted())
- try {
- Thread.sleep(1000);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- TextView signal = (TextView) findViewById(R.id.signal);
- TextView signalStrength = (TextView) findViewById(R.id.signalStrength);
- DecimalFormat df = new DecimalFormat("#.##");
- Boolean testBool = rssi < Double.parseDouble(distanceFinal);
- signal.setText(rssi + " dBm");
- Double approValue = Math.pow(10,((-69-Double.valueOf(rssi))/(10*2)));
- String approFinal = df.format(approValue);
- signalStrength.setText("Signal Strength (β " + approFinal + "m)");
- if (testBool == true) {
- signal.setTextColor(Color.parseColor("#EF2251"));
- } else {
- signal.setTextColor(Color.parseColor("#FFFFFF"));
- }
- if (timeCheck == true) {
- timeDiff.add(tempTime);
- timeCheck = false;
- tempTime = 0;
- Double aveTime = calculateAverage(timeDiff);
- Log.i("Timer", "Average " + aveTime + "s in span of " + calculateTotal(timeDiff) + "s " + timeDiff.toString());
- }
- tempTime++;
- }
- });
- }
- catch (InterruptedException e) {
- }
- }
- })).start();
- //Button to connect to raspberry via bluetooth
- statusIndicator = (ImageButton) findViewById(R.id.statusIndicator);
- statusIndicator.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View w) {
- if(mConnectedThread != null) //First check to make sure thread created
- mConnectedThread.write("2");
- new Thread()
- {
- public void run() {
- boolean fail = false;
- BluetoothDevice device = mBTAdapter.getRemoteDevice("B8:27:EB:CD:4A:A3");
- try {
- mBTSocket = createBluetoothSocket(device);
- } catch (IOException e) {
- fail = true;
- Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
- }
- // Establish the Bluetooth socket connection.
- try {
- mBTSocket.connect();
- } catch (IOException e) {
- try {
- fail = true;
- mBTSocket.close();
- mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
- .sendToTarget();
- } catch (IOException e2) {
- //insert code to deal with this
- Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
- }
- }
- if(fail == false) {
- mConnectedThread = new ConnectedThread(mBTSocket);
- mConnectedThread.start();
- mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, "F")
- .sendToTarget();
- }
- }
- }.start();
- }
- });
- //Text Changer nothing about bluetooth
- distance = (TextView) findViewById(R.id.distance);
- distanceSeekBar = (SeekBar) findViewById(R.id.distanceSeekBar);
- appro = (TextView) findViewById(R.id.appro);
- distanceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
- @Override
- public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
- Double progress = (Double) Double.valueOf(i)/100;
- Double progressFinal = (Double) ((0 + (-100+30) *progress) - 30);
- DecimalFormat df = new DecimalFormat("#.##");
- distanceFinal = df.format(progressFinal);
- distance.setText(distanceFinal + " dBm");
- Double approValue = Math.pow(10,((-69-progressFinal)/(10*2)));
- String approFinal = df.format(approValue);
- appro.setText("β " + approFinal + "m");
- }
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- }
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- }
- });
- //Text Changer nothing about bluetooth
- vibrate = (ToggleButton) findViewById(R.id.vibrate);
- light = (ToggleButton) findViewById(R.id.light);
- light.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- final android.content.ClipboardManager clipboardManager = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
- Double aveTime = calculateAverage(timeDiff);
- ClipData clipData = ClipData.newPlainText("Test", "Average " + aveTime + "s in span of " + calculateTotal(timeDiff) + "s " + timeDiff.toString());
- clipboardManager.setPrimaryClip(clipData);
- if (isChecked) {
- light.setBackgroundResource(R.drawable.bgbtnguide_yes);
- light.setTextColor(Color.parseColor("#FFFFFF"));
- } else {
- light.setBackgroundResource(R.drawable.bgbtnguide_no);
- light.setTextColor(Color.parseColor("#62636B"));
- }
- }
- });
- vibrate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- if (isChecked) {
- vibrate.setBackgroundResource(R.drawable.bgbtnguide_yes);
- vibrate.setTextColor(Color.parseColor("#FFFFFF"));
- } else {
- vibrate.setBackgroundResource(R.drawable.bgbtnguide_no);
- vibrate.setTextColor(Color.parseColor("#62636B"));
- }
- }
- });
- }
- private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
- try {
- final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
- return (BluetoothSocket) m.invoke(device, BTMODULEUUID);
- } catch (Exception e) {
- Log.e(TAG, "Could not create Insecure RFComm Connection",e);
- }
- return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
- }
- private class ConnectedThread extends Thread {
- private final BluetoothSocket mmSocket;
- private final InputStream mmInStream;
- private final OutputStream mmOutStream;
- public ConnectedThread(BluetoothSocket socket) {
- mmSocket = socket;
- InputStream tmpIn = null;
- OutputStream tmpOut = null;
- // Get the input and output streams, using temp objects because
- // member streams are final
- try {
- tmpIn = socket.getInputStream();
- tmpOut = socket.getOutputStream();
- } catch (IOException e) {
- }
- mmInStream = tmpIn;
- mmOutStream = tmpOut;
- }
- public void run() {
- byte[] buffer = new byte[1024]; // buffer store for the stream
- int bytes; // bytes returned from read()
- // Keep listening to the InputStream until an exception occurs
- while (true) {
- try {
- // Read from the InputStream
- bytes = mmInStream.available();
- if (bytes != 0) {
- buffer = new byte[1024];
- SystemClock.sleep(50); //pause and wait for rest of data. Adjust this depending on your sending speed.
- bytes = mmInStream.available(); // how many bytes are ready to be read?
- bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
- mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
- .sendToTarget(); // Send the obtained bytes to the UI activity
- }
- } catch (IOException e) {
- e.printStackTrace();
- break;
- }
- }
- }
- //Send data to raspberry
- public void write(String input) {
- byte[] bytes = input.getBytes();
- try {
- mmOutStream.write(bytes);
- } catch (IOException e) {
- }
- }
- }
- //Scheduled scanner discovery
- private Runnable discoveryTimer = new Runnable() {
- public void run() {
- if (!MainActivity.this.paused) {
- MainActivity.this.mBluetoothAdapter.cancelDiscovery();
- MainActivity.this.mBluetoothAdapter.startDiscovery();
- } else {
- MainActivity.this.mBluetoothAdapter.cancelDiscovery();
- }
- MainActivity.this.handler.postDelayed(this, (long) MainActivity.this.discovery_restart_time);
- }
- };
- //signal receiver
- private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
- public void onReceive(Context context, Intent intent) {
- if ("android.bluetooth.device.action.FOUND".equals(intent.getAction())) {
- BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
- //rssi
- short shortExtra = intent.getShortExtra("android.bluetooth.device.extra.RSSI", Short.MIN_VALUE);
- String name = bluetoothDevice.getName();
- String address = bluetoothDevice.getAddress();
- Log.i("BT", name + " " + address + " " + shortExtra + " " + bluetoothDevice.getType() + " " + counter);
- //check if it is from raspberry
- if (name.equals("raspberrypi")) {
- rssi = shortExtra;
- counter++;
- signal = (TextView) findViewById(R.id.signal);
- signal.setText(shortExtra + " dBm");
- timeCheck = true;
- if (mConnectedThread != null) {
- if (rssi < Double.parseDouble(distanceFinal)) {
- mConnectedThread.write("GPIO 18 1");
- } else {
- mConnectedThread.write("GPIO 18 0");
- }
- }
- }
- }
- }
- };
- //nothing
- private double calculateAverage(List <Integer> marks) {
- Integer sum = 0;
- if(!marks.isEmpty()) {
- for (Integer mark : marks) {
- sum += mark;
- }
- return sum.doubleValue() / marks.size();
- }
- return sum;
- }
- //nothing
- private double calculateTotal(List <Integer> marks) {
- Integer sum = 0;
- if(!marks.isEmpty()) {
- for (Integer mark : marks) {
- sum += mark;
- }
- return sum.doubleValue() / 1;
- }
- return sum;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement