Advertisement
Guest User

Untitled

a guest
Nov 28th, 2015
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.46 KB | None | 0 0
  1. package com.example.user.waterpumpcontrol;
  2.  
  3. import android.bluetooth.BluetoothAdapter;
  4. import android.bluetooth.BluetoothDevice;
  5. import android.bluetooth.BluetoothSocket;
  6. import android.content.BroadcastReceiver;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.IntentFilter;
  10. import android.os.Handler;
  11. import android.support.v7.app.AppCompatActivity;
  12. import android.os.Bundle;
  13. import android.view.Menu;
  14. import android.view.MenuItem;
  15. import android.view.View;
  16. import android.widget.Button;
  17. import android.widget.TextView;
  18. import android.widget.Toast;
  19.  
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.OutputStream;
  23. import java.util.UUID;
  24.  
  25. public class MainActivity extends AppCompatActivity {
  26.  
  27. private BluetoothAdapter BA;
  28. private int REQUEST_ENABLE_BT = 1;
  29. private static final String APC = "PUMPCTRL"; // HC-05 Bluetooth module device name
  30. private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // HC-05 Bluetooth module unique ID
  31. private BluetoothDevice mmDevice; // BT connected device
  32. private OutputStream mmOutputStream; // BT application output
  33. private InputStream mmInputStream; // BT application input
  34. private int btConnected; // conformation that BT is connected
  35.  
  36. Thread workerThread;
  37. Handler bluetoothIn;
  38. final int handlerState = 0; // used to identify handler message (only using one msg)
  39. private StringBuilder recDataString = new StringBuilder();
  40.  
  41. Button btnSetIdle, btnRtvIdle, btnFlush;
  42. TextView tvTempP, tvTempRadIn, tvTempRadOut, tvFlowPrime, tvFlowSecond, tvPStatus;
  43.  
  44.  
  45. @Override
  46. protected void onCreate(Bundle savedInstanceState) {
  47. super.onCreate(savedInstanceState);
  48.  
  49. // menu items
  50. setContentView(R.layout.activity_main);
  51.  
  52. // buttons
  53. btnSetIdle = (Button) findViewById(R.id.setValBtn);
  54. btnRtvIdle = (Button) findViewById(R.id.rtValBtn);
  55. btnFlush = (Button) findViewById(R.id.flushBtn);
  56.  
  57. // updatable text fields
  58. tvTempP = (TextView) findViewById(R.id.tempReadP);
  59. tvTempRadIn = (TextView) findViewById(R.id.tempReadIn);
  60. tvTempRadOut = (TextView) findViewById(R.id.tempReadOut);
  61. tvFlowPrime = (TextView) findViewById(R.id.flowRead1);
  62. tvFlowSecond = (TextView) findViewById(R.id.flowRead2);
  63. tvPStatus = (TextView) findViewById(R.id.pumpStatus);
  64.  
  65. // Register the BroadcastReceiver
  66. IntentFilter filter = new IntentFilter();
  67.  
  68. filter.addAction(BluetoothDevice.ACTION_FOUND);
  69. filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
  70. filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  71. filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  72.  
  73. registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
  74.  
  75. BA = BluetoothAdapter.getDefaultAdapter();
  76.  
  77. bluetoothIn = new Handler() {
  78. public void handleMessage(android.os.Message msg) {
  79. if (msg.what == handlerState) {//if message is what we want
  80. //Toast.makeText(MainActivity.this, "DATA RECEIVED", Toast.LENGTH_SHORT).show();
  81. byte[] readBuf = (byte[]) msg.obj;
  82. String readMessage = new String(readBuf, 0, msg.arg1); // msg.arg1 = bytes from connect thread; converting to string
  83. recDataString.append(readMessage); //~: always the last character in a string from the Arduino
  84. //Toast.makeText(MainActivity.this, readMessage, Toast.LENGTH_SHORT).show();
  85. int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
  86. if (endOfLineIndex > 0) { // make sure there data before ~
  87. if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
  88. {
  89. String tempPRead = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
  90. String tempRadInRead = recDataString.substring(5, 9); //same again...
  91. String tempRadOutRead = recDataString.substring(9, 13);
  92. String flow1Read = recDataString.substring(13, 17);
  93. String flow2Read = recDataString.substring(17, 21);
  94.  
  95.  
  96. tvTempP.setText(tempPRead); //update the textviews with sensor values
  97. tvTempRadIn.setText(tempRadInRead);
  98. tvTempRadOut.setText(tempRadOutRead);
  99. tvFlowPrime.setText(flow1Read);
  100. tvFlowSecond.setText(flow2Read);
  101. }
  102. else if (recDataString.charAt(0) == '?') //if it starts with ?, conformation of idle values set
  103. {
  104. Toast.makeText(MainActivity.this, "Idle conditions set.", Toast.LENGTH_SHORT).show();
  105. }
  106. else if (recDataString.charAt(0) == '!') //if it starts with !, idle sensor values have been sent
  107. {
  108. int idleFlowStart = recDataString.indexOf("+"); //the separator between both sensor readings sent as a combined string
  109.  
  110. String idleTemp = recDataString.substring(1, idleFlowStart);
  111. String idleFlow = recDataString.substring((idleFlowStart+1), endOfLineIndex);
  112.  
  113. String toast = "Temp C= " + idleTemp + ", Flow L/min= " + idleFlow;
  114.  
  115. Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
  116. }
  117. else if (recDataString.charAt(0) == '$') //if it starts with $, pump will turn on for 10sec
  118. {
  119. Toast.makeText(MainActivity.this, "Pump on for 20 seconds.", Toast.LENGTH_SHORT).show();
  120. }
  121. else if (recDataString.charAt(0) == '*') //if it starts with *, update pump on/off status
  122. {
  123. if (recDataString.charAt(1) == '1'){
  124. tvPStatus.setText("ON");
  125. }
  126. else if (recDataString.charAt(1) == '2'){
  127. tvPStatus.setText("OFF");
  128. }
  129. }
  130. recDataString.delete(0, recDataString.length()); //clear all string data
  131. }
  132. }
  133. }
  134. };
  135.  
  136. // onclick button listeners
  137.  
  138. btnSetIdle.setOnClickListener(new View.OnClickListener() {
  139. public void onClick(View v) { // if button "set idle conditions" is pressed
  140. try {
  141. sendData(1);
  142. } catch (IOException e) {
  143. e.printStackTrace();
  144. }
  145. }
  146. });
  147.  
  148. btnRtvIdle.setOnClickListener(new View.OnClickListener() {
  149. public void onClick(View v) { // if button "retrieve idle conditions" is pressed
  150. try {
  151. sendData(2);
  152. } catch (IOException e) {
  153. e.printStackTrace();
  154. }
  155. }
  156. });
  157.  
  158. btnFlush.setOnClickListener(new View.OnClickListener() {
  159. public void onClick(View v) { // if button "flush coolant system" is pressed
  160. try {
  161. sendData(3);
  162. } catch (IOException e) {
  163. e.printStackTrace();
  164. }
  165. }
  166. });
  167.  
  168. }
  169.  
  170. @Override
  171. public void onDestroy() {
  172. unregisterReceiver(mReceiver);
  173.  
  174. if (BA.isDiscovering()) {
  175. BA.cancelDiscovery();
  176. }
  177.  
  178. super.onDestroy();
  179. }
  180.  
  181. @Override
  182. public boolean onCreateOptionsMenu(Menu menu) {
  183. // Inflate the menu; this adds items to the action bar if it is present.
  184. getMenuInflater().inflate(R.menu.menu_main, menu);
  185. return true;
  186. }
  187.  
  188. @Override
  189. public boolean onOptionsItemSelected(MenuItem item) {
  190. // Handle action bar item clicks here. The action bar will
  191. // automatically handle clicks on the Home/Up button, so long
  192. // as you specify a parent activity in AndroidManifest.xml.
  193. int id = item.getItemId();
  194.  
  195. // if "Connect to Bluetooth" is selected from the menu
  196. if (id == R.id.action_settings) {
  197.  
  198. if (BA != null) {
  199. if (!BA.isEnabled()) {
  200. enableBT(0);
  201. } else {
  202. searchConnect();
  203. }
  204. } else {
  205. Toast.makeText(MainActivity.this, "No Bluetooth adapter found.", Toast.LENGTH_SHORT).show();
  206. }
  207.  
  208. }
  209.  
  210. return super.onOptionsItemSelected(item);
  211. }
  212.  
  213.  
  214. public int enableBT(int msg) {
  215.  
  216. if (msg == 1) {
  217. Toast.makeText(MainActivity.this, "Bluetooth must remain enabled for app use.", Toast.LENGTH_SHORT).show();
  218. }
  219.  
  220. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  221. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  222.  
  223. return 0;
  224. }
  225.  
  226. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  227. if (requestCode == REQUEST_ENABLE_BT) {
  228. if (resultCode == RESULT_OK) {
  229. Toast.makeText(MainActivity.this, "Bluetooth enabled.", Toast.LENGTH_SHORT).show();
  230. searchConnect();
  231. } else {
  232. Toast.makeText(MainActivity.this, "Please enable Bluetooth.", Toast.LENGTH_SHORT).show();
  233. enableBT(0);
  234. }
  235. }
  236. }
  237.  
  238. public void searchConnect() {
  239.  
  240. BA.startDiscovery();
  241.  
  242. }
  243.  
  244. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  245. public void onReceive(Context context, Intent intent) {
  246. String action = intent.getAction();
  247. Bundle extras = intent.getExtras();
  248. final int FAIL = -1;
  249.  
  250. if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
  251. Toast.makeText(MainActivity.this, "BT discovery started.", Toast.LENGTH_SHORT).show(); // search for PUMPCTRL has started
  252. }
  253. else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
  254. Toast.makeText(MainActivity.this, "BT discovery finished.", Toast.LENGTH_SHORT).show(); // search for PUMPCTRL has finished
  255. }
  256. else if (BluetoothDevice.ACTION_FOUND.equals(action)) { // bluetooth device found
  257. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  258.  
  259. if (device.getName().equals(APC)) { // if one of the Bluetooth devices are named "PUMPCTRL", connect to it
  260. mmDevice = device;
  261. try {
  262. openBT();
  263. } catch (IOException e) {
  264. e.printStackTrace();
  265. }
  266. }
  267. }
  268. else if ("android.bluetooth.adapter.action.STATE_CHANGED".equals(action)) {
  269. bluetoothStateChanged(extras.getInt("android.bluetooth.adapter.extra.STATE", FAIL));
  270. }
  271. }
  272. };
  273.  
  274. private void bluetoothStateChanged(int state) {
  275. switch (state) {
  276. case BluetoothAdapter.STATE_OFF: {
  277. break;
  278. }
  279. case BluetoothAdapter.STATE_TURNING_ON: {
  280. break;
  281. }
  282. case BluetoothAdapter.STATE_ON: {
  283. break;
  284. }
  285. case BluetoothAdapter.STATE_TURNING_OFF: { // if BT is turned off while using app, turn it back on
  286. enableBT(1);
  287. break;
  288. }
  289. }
  290. }
  291.  
  292. void openBT() throws IOException {
  293. BluetoothSocket mmSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
  294. mmSocket.connect();
  295. mmOutputStream = mmSocket.getOutputStream();
  296. mmInputStream = mmSocket.getInputStream();
  297. btConnected = 1;
  298. beginListenForData();
  299. }
  300.  
  301. void beginListenForData() {
  302.  
  303. workerThread = new Thread(new Runnable() { // A thread is used to perform intensive tasks in the background
  304. public void run() { // of a main activity in order to prevent visible lag to the user
  305.  
  306. byte[] readBuffer = new byte[512];
  307. int msgLength;
  308.  
  309. while(true) {
  310. try {
  311. int bytesAvailable = mmInputStream.available();
  312. if(bytesAvailable > 0) { // if there is a transmission to receive
  313. msgLength = mmInputStream.read(readBuffer); // store bytes in buffer variable
  314. bluetoothIn.obtainMessage(handlerState, msgLength, -1, readBuffer).sendToTarget(); // send buffer data of length "msgLength" out of work thread to
  315. } // handler for output on main activity window
  316. }
  317. catch (IOException ex) {
  318. break;
  319. }
  320. }
  321. }
  322. });
  323.  
  324. workerThread.start();
  325. }
  326.  
  327. void sendData(int i) throws IOException {
  328. if(btConnected == 1){
  329. mmOutputStream.write(i);
  330. }
  331. else{
  332. Toast.makeText(MainActivity.this, "Bluetooth not connected.", Toast.LENGTH_SHORT).show();
  333. }
  334. }
  335.  
  336. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement