Advertisement
Guest User

Untitled

a guest
Feb 27th, 2020
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.50 KB | None | 0 0
  1. package capstone.bluetooth;
  2.  
  3. import android.Manifest;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.content.ClipboardManager;
  6. import android.bluetooth.BluetoothDevice;
  7. import android.bluetooth.BluetoothSocket;
  8. import android.content.BroadcastReceiver;
  9. import android.content.ClipData;
  10. import android.content.Context;
  11. import android.content.Intent;
  12. import android.content.IntentFilter;
  13. import android.content.pm.PackageManager;
  14. import android.graphics.Color;
  15. import android.os.SystemClock;
  16. import android.support.v4.app.ActivityCompat;
  17. import android.support.v4.content.ContextCompat;
  18. import android.support.v7.app.AppCompatActivity;
  19. import android.os.Bundle;
  20. import android.util.Log;
  21. import android.view.View;
  22. import android.widget.ArrayAdapter;
  23. import android.widget.CheckBox;
  24. import android.widget.CompoundButton;
  25. import android.widget.ImageButton;
  26. import android.widget.SeekBar;
  27. import android.widget.TextView;
  28. import android.widget.Toast;
  29. import java.io.IOException;
  30. import java.io.InputStream;
  31. import java.io.OutputStream;
  32. import java.io.UnsupportedEncodingException;
  33. import java.lang.reflect.Method;
  34. import java.text.DecimalFormat;
  35. import java.util.List;
  36. import java.util.Set;
  37. import java.util.UUID;
  38. import android.os.Handler;
  39. import android.widget.ToggleButton;
  40.  
  41. import capstone.bluetooth.R;
  42.  
  43. import java.util.ArrayList;
  44.  
  45. public class MainActivity extends AppCompatActivity {
  46.  
  47. public boolean paused = false;
  48.  
  49. public BluetoothAdapter mBluetoothAdapter;
  50.  
  51. public Handler handler = new Handler();
  52. private IntentFilter filter;
  53.  
  54. public int discovery_restart_time = 3000; //Discovery restrat time
  55.  
  56. Integer counter = 0;
  57.  
  58. private BluetoothAdapter mBTAdapter;
  59. private ArrayAdapter<String> mBTArrayAdapter;
  60.  
  61.  
  62. private final String TAG = MainActivity.class.getSimpleName();
  63. private Handler mHandler; // Our main handler that will receive callback notifications
  64. private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data
  65. private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
  66.  
  67. private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier
  68.  
  69.  
  70. // #defines for identifying shared types between calling functions
  71. private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
  72. private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
  73. private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
  74.  
  75. //nothing
  76. String dBm = "none";
  77. int updateCheck = 0;
  78. int timerUpdate = 0;
  79. int rssi = 0;
  80. TextView distance, signal;
  81. CheckBox check1;
  82. CheckBox check2;
  83. private Boolean GPIO = false;
  84. String distanceFinal = "-86";
  85. Boolean actionVibrate = false;
  86. Boolean vibrateBtn = true;
  87. Boolean lightBtn = true;
  88. ImageButton statusIndicator;
  89. SeekBar distanceSeekBar;
  90. TextView status, appro;
  91. ToggleButton vibrate;
  92. ToggleButton light;
  93. List<Integer> timeDiff = new ArrayList<>();
  94. Integer tempTime = 0;
  95. Boolean timeCheck = false;
  96.  
  97.  
  98.  
  99. public void onCreate(Bundle bundle) {
  100. super.onCreate(bundle);
  101. setContentView(R.layout.activity_main);
  102.  
  103. //ALl about bluetooth
  104. this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  105. if (!this.mBluetoothAdapter.isEnabled()) {
  106. startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
  107. }
  108. this.handler.post(this.discoveryTimer); //Scheduled scanner discovery restart
  109. this.filter = new IntentFilter("android.bluetooth.device.action.FOUND");
  110. registerReceiver(this.mReceiver, this.filter); //Bluetooth signal strength reciever
  111.  
  112. mBTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
  113. mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
  114.  
  115. // Ask for location permission if not already allowed
  116. if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
  117. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
  118.  
  119. mHandler = new Handler(){
  120. public void handleMessage(android.os.Message msg){
  121. if(msg.what == MESSAGE_READ){
  122. String readMessage = null;
  123. try {
  124. readMessage = new String((byte[]) msg.obj, "UTF-8");
  125. } catch (UnsupportedEncodingException e) {
  126. e.printStackTrace();
  127. }
  128. }
  129. }
  130. };
  131.  
  132. if (mBTArrayAdapter == null) {
  133. // Device does not support Bluetooth
  134. Toast.makeText(getApplicationContext(),"Bluetooth device not found!",Toast.LENGTH_SHORT).show();
  135. }
  136. else {
  137. }
  138.  
  139.  
  140. //All about text, nothing about bluetooth
  141. (new Thread(new Runnable()
  142. {
  143.  
  144. @Override
  145. public void run()
  146. {
  147. while (!Thread.interrupted())
  148. try {
  149. Thread.sleep(1000);
  150. runOnUiThread(new Runnable() {
  151.  
  152. @Override
  153. public void run() {
  154. TextView signal = (TextView) findViewById(R.id.signal);
  155. TextView signalStrength = (TextView) findViewById(R.id.signalStrength);
  156. DecimalFormat df = new DecimalFormat("#.##");
  157.  
  158. Boolean testBool = rssi < Double.parseDouble(distanceFinal);
  159.  
  160. signal.setText(rssi + " dBm");
  161.  
  162. Double approValue = Math.pow(10,((-69-Double.valueOf(rssi))/(10*2)));
  163. String approFinal = df.format(approValue);
  164. signalStrength.setText("Signal Strength (β‰ˆ " + approFinal + "m)");
  165.  
  166. if (testBool == true) {
  167. signal.setTextColor(Color.parseColor("#EF2251"));
  168. } else {
  169. signal.setTextColor(Color.parseColor("#FFFFFF"));
  170. }
  171.  
  172. if (timeCheck == true) {
  173. timeDiff.add(tempTime);
  174. timeCheck = false;
  175. tempTime = 0;
  176. Double aveTime = calculateAverage(timeDiff);
  177. Log.i("Timer", "Average " + aveTime + "s in span of " + calculateTotal(timeDiff) + "s " + timeDiff.toString());
  178. }
  179. tempTime++;
  180. }
  181. });
  182. }
  183. catch (InterruptedException e) {
  184. }
  185. }
  186. })).start();
  187.  
  188. //Button to connect to raspberry via bluetooth
  189. statusIndicator = (ImageButton) findViewById(R.id.statusIndicator);
  190. statusIndicator.setOnClickListener(new View.OnClickListener() {
  191. @Override
  192. public void onClick(View w) {
  193. if(mConnectedThread != null) //First check to make sure thread created
  194. mConnectedThread.write("2");
  195. new Thread()
  196. {
  197. public void run() {
  198. boolean fail = false;
  199.  
  200. BluetoothDevice device = mBTAdapter.getRemoteDevice("B8:27:EB:CD:4A:A3");
  201.  
  202.  
  203. try {
  204. mBTSocket = createBluetoothSocket(device);
  205. } catch (IOException e) {
  206. fail = true;
  207. Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
  208. }
  209. // Establish the Bluetooth socket connection.
  210. try {
  211. mBTSocket.connect();
  212. } catch (IOException e) {
  213. try {
  214. fail = true;
  215. mBTSocket.close();
  216. mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
  217. .sendToTarget();
  218. } catch (IOException e2) {
  219. //insert code to deal with this
  220. Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
  221. }
  222. }
  223. if(fail == false) {
  224. mConnectedThread = new ConnectedThread(mBTSocket);
  225. mConnectedThread.start();
  226.  
  227. mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, "F")
  228. .sendToTarget();
  229. }
  230. }
  231. }.start();
  232. }
  233. });
  234.  
  235. //Text Changer nothing about bluetooth
  236. distance = (TextView) findViewById(R.id.distance);
  237. distanceSeekBar = (SeekBar) findViewById(R.id.distanceSeekBar);
  238. appro = (TextView) findViewById(R.id.appro);
  239.  
  240. distanceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
  241. @Override
  242. public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
  243. Double progress = (Double) Double.valueOf(i)/100;
  244. Double progressFinal = (Double) ((0 + (-100+30) *progress) - 30);
  245. DecimalFormat df = new DecimalFormat("#.##");
  246. distanceFinal = df.format(progressFinal);
  247. distance.setText(distanceFinal + " dBm");
  248.  
  249. Double approValue = Math.pow(10,((-69-progressFinal)/(10*2)));
  250. String approFinal = df.format(approValue);
  251. appro.setText("β‰ˆ " + approFinal + "m");
  252. }
  253.  
  254. @Override
  255. public void onStartTrackingTouch(SeekBar seekBar) {
  256.  
  257. }
  258.  
  259. @Override
  260. public void onStopTrackingTouch(SeekBar seekBar) {
  261.  
  262. }
  263. });
  264.  
  265. //Text Changer nothing about bluetooth
  266. vibrate = (ToggleButton) findViewById(R.id.vibrate);
  267. light = (ToggleButton) findViewById(R.id.light);
  268. light.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  269. public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  270. final android.content.ClipboardManager clipboardManager = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
  271. Double aveTime = calculateAverage(timeDiff);
  272. ClipData clipData = ClipData.newPlainText("Test", "Average " + aveTime + "s in span of " + calculateTotal(timeDiff) + "s " + timeDiff.toString());
  273. clipboardManager.setPrimaryClip(clipData);
  274. if (isChecked) {
  275. light.setBackgroundResource(R.drawable.bgbtnguide_yes);
  276. light.setTextColor(Color.parseColor("#FFFFFF"));
  277. } else {
  278. light.setBackgroundResource(R.drawable.bgbtnguide_no);
  279. light.setTextColor(Color.parseColor("#62636B"));
  280. }
  281. }
  282. });
  283.  
  284. vibrate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  285. public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  286. if (isChecked) {
  287. vibrate.setBackgroundResource(R.drawable.bgbtnguide_yes);
  288. vibrate.setTextColor(Color.parseColor("#FFFFFF"));
  289. } else {
  290. vibrate.setBackgroundResource(R.drawable.bgbtnguide_no);
  291. vibrate.setTextColor(Color.parseColor("#62636B"));
  292. }
  293. }
  294. });
  295. }
  296.  
  297. private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
  298. try {
  299. final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
  300. return (BluetoothSocket) m.invoke(device, BTMODULEUUID);
  301. } catch (Exception e) {
  302. Log.e(TAG, "Could not create Insecure RFComm Connection",e);
  303. }
  304. return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
  305. }
  306.  
  307. private class ConnectedThread extends Thread {
  308. private final BluetoothSocket mmSocket;
  309. private final InputStream mmInStream;
  310. private final OutputStream mmOutStream;
  311.  
  312. public ConnectedThread(BluetoothSocket socket) {
  313. mmSocket = socket;
  314. InputStream tmpIn = null;
  315. OutputStream tmpOut = null;
  316.  
  317. // Get the input and output streams, using temp objects because
  318. // member streams are final
  319. try {
  320. tmpIn = socket.getInputStream();
  321. tmpOut = socket.getOutputStream();
  322. } catch (IOException e) {
  323. }
  324.  
  325. mmInStream = tmpIn;
  326. mmOutStream = tmpOut;
  327. }
  328.  
  329. public void run() {
  330. byte[] buffer = new byte[1024]; // buffer store for the stream
  331. int bytes; // bytes returned from read()
  332. // Keep listening to the InputStream until an exception occurs
  333. while (true) {
  334. try {
  335. // Read from the InputStream
  336. bytes = mmInStream.available();
  337. if (bytes != 0) {
  338. buffer = new byte[1024];
  339. SystemClock.sleep(50); //pause and wait for rest of data. Adjust this depending on your sending speed.
  340. bytes = mmInStream.available(); // how many bytes are ready to be read?
  341. bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
  342. mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
  343. .sendToTarget(); // Send the obtained bytes to the UI activity
  344. }
  345. } catch (IOException e) {
  346. e.printStackTrace();
  347.  
  348. break;
  349. }
  350. }
  351. }
  352.  
  353. //Send data to raspberry
  354. public void write(String input) {
  355. byte[] bytes = input.getBytes();
  356. try {
  357. mmOutStream.write(bytes);
  358. } catch (IOException e) {
  359. }
  360. }
  361. }
  362.  
  363. //Scheduled scanner discovery
  364. private Runnable discoveryTimer = new Runnable() {
  365. public void run() {
  366. if (!MainActivity.this.paused) {
  367. MainActivity.this.mBluetoothAdapter.cancelDiscovery();
  368. MainActivity.this.mBluetoothAdapter.startDiscovery();
  369. } else {
  370. MainActivity.this.mBluetoothAdapter.cancelDiscovery();
  371. }
  372. MainActivity.this.handler.postDelayed(this, (long) MainActivity.this.discovery_restart_time);
  373. }
  374. };
  375.  
  376.  
  377. //signal receiver
  378. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  379. public void onReceive(Context context, Intent intent) {
  380. if ("android.bluetooth.device.action.FOUND".equals(intent.getAction())) {
  381. BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
  382.  
  383. //rssi
  384. short shortExtra = intent.getShortExtra("android.bluetooth.device.extra.RSSI", Short.MIN_VALUE);
  385.  
  386. String name = bluetoothDevice.getName();
  387. String address = bluetoothDevice.getAddress();
  388. Log.i("BT", name + " " + address + " " + shortExtra + " " + bluetoothDevice.getType() + " " + counter);
  389.  
  390. //check if it is from raspberry
  391. if (name.equals("raspberrypi")) {
  392. rssi = shortExtra;
  393. counter++;
  394.  
  395. signal = (TextView) findViewById(R.id.signal);
  396. signal.setText(shortExtra + " dBm");
  397. timeCheck = true;
  398.  
  399. if (mConnectedThread != null) {
  400. if (rssi < Double.parseDouble(distanceFinal)) {
  401. mConnectedThread.write("GPIO 18 1");
  402. } else {
  403. mConnectedThread.write("GPIO 18 0");
  404. }
  405. }
  406. }
  407. }
  408. }
  409. };
  410.  
  411. //nothing
  412. private double calculateAverage(List <Integer> marks) {
  413. Integer sum = 0;
  414. if(!marks.isEmpty()) {
  415. for (Integer mark : marks) {
  416. sum += mark;
  417. }
  418. return sum.doubleValue() / marks.size();
  419. }
  420. return sum;
  421. }
  422. //nothing
  423. private double calculateTotal(List <Integer> marks) {
  424. Integer sum = 0;
  425. if(!marks.isEmpty()) {
  426. for (Integer mark : marks) {
  427. sum += mark;
  428. }
  429. return sum.doubleValue() / 1;
  430. }
  431. return sum;
  432. }
  433. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement