Advertisement
sandipmjadhav

Bluetooth Connection class

Oct 26th, 2012
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 30.40 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.lang.reflect.Method;
  6.  
  7. import android.bluetooth.BluetoothAdapter;
  8. import android.bluetooth.BluetoothDevice;
  9. import android.bluetooth.BluetoothSocket;
  10. import android.content.Context;
  11. import android.os.Bundle;
  12. import android.os.Message;
  13. import android.util.Log;
  14.  
  15. import com.example.models.CaliberationResponseModel;
  16. import com.example.settings.Measurement;
  17. import com.spSoft.handheldDeviceAndroidApp.communication.model.MeasurementData;
  18. import com.spSoft.handheldDeviceAndroidApp.communication.parser.HHDCommandResponseParser;
  19. import com.spSoft.handheldDeviceAndroidApp.logger.BaseLoggerException;
  20. import com.spSoft.handheldDeviceAndroidApp.logger.CsvWriter;
  21. import com.spSoft.handheldDeviceAndroidApp.logger.Logger;
  22. import com.spSoft.utils.AppPreferences;
  23. import com.spSoft.utils.GlobalValues;
  24.  
  25. /**
  26. * This class does all the work for setting up and managing Bluetooth
  27. * connections with other devices. It has a thread that listens for incoming
  28. * connections, a thread for connecting with a device, and a thread for
  29. * performing data transmissions when connected.
  30. */
  31. public class HHDBTService {
  32. // Debugging
  33. private static final String TAG = "HHDBTService";
  34. private static final boolean D = true;
  35.  
  36. // Member fields
  37. private final BluetoothAdapter mAdapter;
  38. private static BapiHandler mHandler;
  39. AppPreferences bapiPreferences;
  40. private CsvWriter csvLogWriter;
  41. /*
  42. * private AcceptThread mSecureAcceptThread; private AcceptThread
  43. * mInsecureAcceptThread;
  44. */
  45. private ConnectThread mConnectThread;
  46. private MeasurementReadThread mConnectedThread;
  47. private SetAliasReadThread mSetAliasReadThread;
  48. private StartCaliberationThread mStartCaliberationThread;
  49. private StartCaliberationReadingThread mStartCaliberationReadingThread;
  50. private static int mState;
  51.  
  52. // Constants that indicate the current connection state
  53. public static final int STATE_NONE = 0; // we're doing nothing
  54. public static final int STATE_LISTEN = 1; // now listening for incoming
  55. // connections
  56. public static final int STATE_CONNECTING = 2; // now initiating an outgoing
  57. // connection
  58. public static final int STATE_CONNECTED = 3; // now connected to a remote
  59. // device
  60.  
  61. /**
  62. * Constructor. Prepares a new BluetoothChat session.
  63. *
  64. * @param context
  65. * The UI Activity Context
  66. * @param handler
  67. * A Handler to send messages back to the UI Activity
  68. */
  69. public HHDBTService(Context context, BapiHandler handler) {
  70. mAdapter = BluetoothAdapter.getDefaultAdapter();
  71. mState = STATE_NONE;
  72. mHandler = handler;
  73. bapiPreferences = new AppPreferences(context);
  74. setState(STATE_LISTEN);
  75. }
  76.  
  77. /**
  78. * Set the current state of the chat connection
  79. *
  80. * @param state
  81. * An integer defining the current connection state
  82. */
  83. public synchronized static void setState(int state) {
  84. if (D)
  85. Log.d(TAG, "setState() " + mState + " -> " + state);
  86. mState = state;
  87.  
  88. // Give the new state to the Handler so the UI Activity can update
  89. mHandler.obtainMessage(GlobalValues.MESSAGE_STATE_CHANGE, state, -1)
  90. .sendToTarget();
  91. }
  92.  
  93. /**
  94. * Return the current connection state.
  95. */
  96. public synchronized int getState() {
  97. return mState;
  98. }
  99.  
  100. /**
  101. * Start the chat service. Specifically start AcceptThread to begin a
  102. * session in listening (server) mode. Called by the Activity onResume()
  103. */
  104. /*
  105. * public synchronized void start() { if (D) Log.d(TAG, "start");
  106. *
  107. * // Cancel any thread attempting to make a connection if (mConnectThread
  108. * != null) { mConnectThread.cancel(); mConnectThread = null; }
  109. *
  110. * // Cancel any thread currently running a connection if (mConnectedThread
  111. * != null) { mConnectedThread.cancel(); mConnectedThread = null; }
  112. *
  113. * setState(STATE_LISTEN); }
  114. */
  115.  
  116. /**
  117. * Start the ConnectThread to initiate a connection to a remote device.
  118. *
  119. * @param device
  120. * The BluetoothDevice to connect
  121. * @param secure
  122. * Socket Security type - Secure (true) , Insecure (false)
  123. */
  124. public synchronized void connect(BluetoothDevice device, boolean secure,
  125. int commandIndex) {
  126. /*
  127. * if (D) Log.d(TAG, "connect to: " + device);
  128. *
  129. * // Cancel any thread attempting to make a connection if (mState ==
  130. * STATE_CONNECTING) { if (mConnectThread != null) {
  131. * mConnectThread.cancel(); mConnectThread = null; } }
  132. *
  133. * // Cancel any thread currently running a connection if
  134. * (mConnectedThread != null) { mConnectedThread.cancel();
  135. * mConnectedThread = null; }
  136. */
  137.  
  138. // Start the thread to connect with the given device
  139. mConnectThread = new ConnectThread(device, secure, commandIndex);
  140. mConnectThread.start();
  141. setState(STATE_CONNECTING);
  142. }
  143.  
  144. /**
  145. * Start the MeasurementReadThread to begin managing a Bluetooth connection
  146. *
  147. * @param socket
  148. * The BluetoothSocket on which the connection was made
  149. * @param device
  150. * The BluetoothDevice that has been connected
  151. */
  152. public synchronized void connected(BluetoothSocket socket,
  153. BluetoothDevice device, final String socketType, int commandIndex) {
  154. if (D)
  155. Log.d(TAG, "connected, Socket Type:" + socketType);
  156.  
  157. // Cancel the thread that completed the connection
  158. if (mConnectThread != null) {
  159. mConnectThread.cancel();
  160. mConnectThread = null;
  161. }
  162.  
  163. /*
  164. * // Cancel any thread currently running a connection if
  165. * (mConnectedThread != null) { mConnectedThread.cancel();
  166. * mConnectedThread = null; }
  167. */
  168.  
  169. // Start the thread to manage the connection and perform transmissions
  170. /*
  171. * mConnectedThread = new MeasurementReadThread(socket, socketType);
  172. * mConnectedThread.start();
  173. */
  174.  
  175. // TODO start/write other threads here condition will come from Global
  176. // Class
  177.  
  178. switch (commandIndex) {
  179. case GlobalValues.command_setMeasurement:
  180. mConnectedThread = new MeasurementReadThread(socket, socketType);
  181. mConnectedThread.start();
  182. break;
  183.  
  184. case GlobalValues.command_setAlise:
  185. mConnectedThread = new MeasurementReadThread(socket, socketType);
  186. mConnectedThread.start();
  187. mSetAliasReadThread = new SetAliasReadThread(socket, socketType);
  188. mSetAliasReadThread.start();
  189. break;
  190. case GlobalValues.command_startCalibration:
  191. mStartCaliberationThread = new StartCaliberationThread(socket,
  192. socketType);
  193. mStartCaliberationThread.start();
  194. break;
  195. case GlobalValues.command_Calibration_reading:
  196. mStartCaliberationReadingThread = new StartCaliberationReadingThread(
  197. socket, socketType);
  198. mStartCaliberationReadingThread.start();
  199. break;
  200. }
  201.  
  202. // Send the name of the connected device back to the UI Activity
  203. Message msg = mHandler.obtainMessage(GlobalValues.MESSAGE_DEVICE_NAME);
  204. Bundle bundle = new Bundle();
  205. bundle.putString(GlobalValues.KEY_CURRENT_CONNECTED_DEVICE_NAME,
  206. device.getName());
  207. msg.setData(bundle);
  208. mHandler.sendMessage(msg);
  209.  
  210. setState(STATE_CONNECTED);
  211. }
  212.  
  213. /**
  214. * Stop all threads
  215. */
  216. public synchronized void stop() {
  217. if (D)
  218. Log.d(TAG, "stop");
  219.  
  220. if (mConnectThread != null) {
  221. mConnectThread.cancel();
  222. mConnectThread = null;
  223. }
  224.  
  225. if (mConnectedThread != null) {
  226. mConnectedThread.cancel();
  227. mConnectedThread = null;
  228. }
  229.  
  230. setState(STATE_NONE);
  231. }
  232.  
  233. /**
  234. * Write to the MeasurementReadThread in an unsynchronized manner
  235. *
  236. * @param out
  237. * The bytes to write
  238. * @see MeasurementReadThread#write(byte[])
  239. */
  240. public void write(byte[] out) {
  241. // Create temporary object
  242. MeasurementReadThread r;
  243. // Synchronize a copy of the MeasurementReadThread
  244. synchronized (this) {
  245. if (mState != STATE_CONNECTED)
  246. return;
  247. r = mConnectedThread;
  248. }
  249. // Perform the write unsynchronized
  250. r.write(out);
  251. }
  252.  
  253. /**
  254. * Indicate that the connection attempt failed and notify the UI Activity.
  255. */
  256. private void connectionFailed() {
  257. // Send a failure message back to the Activity
  258. if (Measurement.FLAG_DEVICE_LOST_FOUND) {
  259. Message msg = mHandler.obtainMessage(GlobalValues.MESSAGE_SHOW_TOAST);
  260. Bundle bundle = new Bundle();
  261. bundle.putString(GlobalValues.TOAST, "Unable to connect device");
  262. msg.setData(bundle);
  263. mHandler.sendMessage(msg);
  264. }
  265.  
  266. // Start the service over to restart listening mode
  267. /* HHDBTService.this.start(); */
  268. }
  269.  
  270. /**
  271. * Indicate that the connection was lost and notify the UI Activity.
  272. */
  273. private void connectionLost() {
  274. // Send a failure message back to the Activity
  275. /*
  276. * Message msg =
  277. * mHandler.obtainMessage(GlobalValues.MESSAGE_DEVICE_CONNECTION_LOST);
  278. * Bundle bundle = new Bundle(); bundle.putString(GlobalValues.TOAST,
  279. * "Device connection was lost"); msg.setData(bundle);
  280. * mHandler.sendMessage(msg);
  281. *
  282. * // Start the service over to restart listening mode
  283. * HHDBTService.this.start();
  284. */
  285. /**
  286. * @author Sandip Removing all threads and stating state to none
  287. */
  288. if (D)
  289. Log.d(TAG, "start");
  290.  
  291. // Cancel any thread attempting to make a connection
  292. if (mConnectThread != null) {
  293. mConnectThread.cancel();
  294. mConnectThread = null;
  295. }
  296.  
  297. // Cancel any thread currently running a connection
  298. if (mConnectedThread != null) {
  299. mConnectedThread.cancel();
  300. mConnectedThread = null;
  301. }
  302. setState(STATE_NONE);
  303. }
  304.  
  305. /**
  306. * This thread runs while attempting to make an outgoing connection with a
  307. * device. It runs straight through; the connection either succeeds or
  308. * fails.
  309. */
  310. private class ConnectThread extends Thread {
  311. private BluetoothSocket mmSocket;
  312. private final BluetoothDevice mmDevice;
  313. private String mSocketType;
  314. private int mCommandIndex;
  315.  
  316. public ConnectThread(BluetoothDevice device, boolean secure,
  317. int commandIndex) {
  318. mmDevice = device;
  319. mSocketType = secure ? "Secure" : "Insecure";
  320. mCommandIndex = commandIndex;
  321. }
  322.  
  323. protected boolean simpleComm(Integer port) {
  324. // byte [] inputBytes = null;
  325.  
  326. // The documents tell us to cancel the discovery process.
  327. mAdapter.cancelDiscovery();
  328.  
  329. Log.d(this.toString(), "Port = " + port);
  330. try {
  331. // This is a hack to access "createRfcommSocket which is does
  332. // not
  333. // have public access in the current api.
  334. // Note: BlueToothDevice.createRfcommSocketToServiceRecord (UUID
  335. // uuid) does not work in this type of application. .
  336. Method m = mmDevice.getClass().getMethod("createRfcommSocket",
  337. new Class[] { int.class });
  338. mmSocket = (BluetoothSocket) m.invoke(mmDevice, port);
  339.  
  340. // debug check to ensure socket was set.
  341. assert (mmSocket != null) : "Socket is Null";
  342.  
  343. mAdapter.cancelDiscovery();
  344. // attempt to connect to device
  345. mmSocket.connect();
  346. /*try {
  347. Log.d(this.toString(),
  348. "************ CONNECTION SUCCEES! *************");
  349.  
  350. connected(mmSocket, mmDevice, mSocketType, mCommandIndex);
  351. return true;
  352. } finally {
  353. // close the socket and we are done.
  354. // //mmSocket.close();
  355. }*/
  356. // IOExcecption is thrown if connect fails.
  357. } catch (IOException ex) {
  358. Log.e(this.toString(), "IOException " + ex.getMessage());
  359. if (port == 3) {
  360. connectionFailed();
  361. try {
  362. mmSocket.close();
  363. mmSocket = null;
  364. } catch (IOException e) {
  365. // TODO Auto-generated catch block
  366. e.printStackTrace();
  367. }
  368.  
  369. }
  370. // NoSuchMethodException IllegalAccessException
  371. // InvocationTargetException
  372. // are reflection exceptions.
  373. } catch (NoSuchMethodException ex) {
  374. Log.e(this.toString(),
  375. "NoSuchMethodException " + ex.getMessage());
  376. } catch (IllegalAccessException ex) {
  377. Log.e(this.toString(),
  378. "IllegalAccessException " + ex.getMessage());
  379. } catch (InvocationTargetException ex) {
  380. Log.e(this.toString(),
  381. "InvocationTargetException " + ex.getMessage());
  382. }
  383.  
  384. return false;
  385. }
  386.  
  387. public void run() {
  388.  
  389. for (Integer port = 1; port <= 3; port++) {
  390. if (simpleComm(Integer.valueOf(port)))
  391. break;
  392.  
  393. }
  394.  
  395. // Reset the ConnectThread because we're done
  396. synchronized (HHDBTService.this) {
  397. mConnectThread = null;
  398. }
  399.  
  400. connected(mmSocket, mmDevice, mSocketType, mCommandIndex);
  401. }
  402.  
  403. public void cancel() {
  404. /*
  405. * try { mmSocket.close(); } catch (IOException e) { Log.e(TAG,
  406. * "close() of connect " + mSocketType + " socket failed", e); }
  407. */
  408. }
  409. }
  410.  
  411. /**
  412. * This thread runs during a connection with a remote device. It handles all
  413. * incoming and outgoing transmissions.
  414. */
  415. private class MeasurementReadThread extends Thread {
  416. private BluetoothSocket mmSocket;
  417. private InputStream mmInStream;
  418. private OutputStream mmOutStream;
  419. private Logger logger;
  420.  
  421. private boolean isFirst = true;
  422.  
  423. boolean isCancelled = false;
  424.  
  425. public MeasurementReadThread(BluetoothSocket socket, String socketType) {
  426. Log.d(TAG, "create MeasurementReadThread: " + socketType);
  427. mmSocket = socket;
  428. InputStream tmpIn = null;
  429. OutputStream tmpOut = null;
  430.  
  431. // Get the BluetoothSocket input and output streams
  432. try {
  433. tmpIn = socket.getInputStream();
  434. tmpOut = socket.getOutputStream();
  435. } catch (IOException e) {
  436. Log.e(TAG, "temp sockets not created", e);
  437. }
  438. logger = Logger.getInstance();
  439.  
  440. mmInStream = tmpIn;
  441. mmOutStream = tmpOut;
  442. }
  443.  
  444. public void run() {
  445. Log.i(TAG, "BEGIN mConnectedThread");
  446. byte[] buffer = new byte[1024];
  447. int bytes;
  448.  
  449. // Keep listening to the InputStream while connected
  450. while (!isCancelled && mState == STATE_CONNECTED) {
  451. try {
  452. byte[] command = new byte[] { (byte) 0xAA, (byte) 0x02,
  453. (byte) 0x00, (byte) 0x00, (byte) 0x9F, (byte) 0xFD,
  454. (byte) 0x55 };
  455.  
  456. mmOutStream.write(command);
  457.  
  458. if (mmInStream.available() > 0) {
  459. // Read from the InputStream
  460. bytes = mmInStream.read(buffer);
  461.  
  462. // Send the obtained bytes to the UI Activity
  463. mHandler.obtainMessage(GlobalValues.MESSAGE_MEASUREMENT_READING,
  464. bytes, -1, buffer).sendToTarget();
  465.  
  466. // if logging enabled then record data in database here
  467. if (!bapiPreferences.getPreferences(
  468. GlobalValues.KEY_LOG_STATUS,
  469. GlobalValues.LOG_DISABLED).equals(
  470. GlobalValues.LOG_DISABLED)) {
  471. try {
  472. HHDCommandResponseParser parser = new HHDCommandResponseParser();
  473. MeasurementData measurementData = parser
  474. .parseMeasurementData(buffer);
  475. logger.recordLog(measurementData
  476. .getTemperature(),
  477. String.valueOf(measurementData
  478. .getTempUnit()),
  479. measurementData.getHumidity(), String
  480. .valueOf(measurementData
  481. .getHumidityUnit()),
  482. measurementData.getDate(),
  483. measurementData.getTime());
  484.  
  485. if (!bapiPreferences
  486. .getPreferences(
  487. GlobalValues.KEY_CSV_FILE_LOG_STATUS,
  488. GlobalValues.CSV_FILE_LOG_DISABLED)
  489. .equals(GlobalValues.CSV_FILE_LOG_DISABLED)) {
  490. // add to csv file code here
  491. csvLogWriter = new CsvWriter(
  492. GlobalValues.CSV_FILE_DIRECTORY_PATH,
  493. bapiPreferences
  494. .getPreferences(
  495. GlobalValues.KEY_CSV_FILE_NAME,
  496. "Bapi.csv"));
  497. String record = new String(
  498. String.valueOf(measurementData
  499. .getTemperature())
  500. + ","
  501. + measurementData
  502. .getTempUnit()
  503. + ","
  504. + String.valueOf(measurementData
  505. .getHumidity())
  506. + ","
  507. + measurementData
  508. .getHumidityUnit()
  509. + ","
  510. + measurementData.getDate()
  511. + ","
  512. + measurementData.getTime());
  513. csvLogWriter.writeRecordToFile(record);
  514.  
  515. }
  516. } catch (BaseLoggerException e) {
  517.  
  518. Log.d(HHDBTService.class.toString(),
  519. "EXCEPTION WHILE LOGGING:"
  520. + e.getMessage());
  521. }
  522. }
  523. }
  524. } catch (IOException e) {
  525. Log.e(TAG, "disconnected", e);
  526. connectionLost();
  527. break;
  528. }
  529.  
  530. try {
  531. if (!isFirst) {
  532. if (!bapiPreferences.getPreferences(
  533. GlobalValues.KEY_AUTO_MANUAL,
  534. GlobalValues.MANUAL)
  535. .equals(GlobalValues.MANUAL))
  536. Thread.sleep(5000);
  537. else
  538. cancel();
  539. } else {
  540. Thread.sleep(1000);
  541. isFirst = false;
  542. }
  543. } catch (InterruptedException e) {
  544. e.printStackTrace();
  545. }
  546.  
  547. }
  548. }
  549.  
  550. /**
  551. * Write to the connected OutStream.
  552. *
  553. * @param buffer
  554. * The bytes to write
  555. */
  556. public void write(byte[] buffer) {
  557. try {
  558. mmOutStream.write(buffer);
  559.  
  560. // Share the sent message back to the UI Activity
  561. mHandler.obtainMessage(GlobalValues.MESSAGE_WRITE, -1, -1,
  562. buffer).sendToTarget();
  563. } catch (IOException e) {
  564. Log.e(TAG, "Exception during write", e);
  565. }
  566. }
  567.  
  568. public void cancel() {
  569. try {
  570. mmOutStream.close();
  571. mmInStream.close();
  572. isCancelled = true;
  573. mmSocket.close();
  574. } catch (IOException e) {
  575. Log.e(TAG, "close() of connect socket failed", e);
  576. }
  577. }
  578. }
  579.  
  580. /**
  581. * This thread runs during a connection with a remote device. It handles all
  582. * incoming and outgoing transmissions.
  583. */
  584. private class SetAliasReadThread extends Thread {
  585. private BluetoothSocket mmSocket;
  586. private InputStream mmInStream;
  587. private OutputStream mmOutStream;
  588.  
  589. boolean isCancelled = false;
  590.  
  591. public SetAliasReadThread(BluetoothSocket socket, String socketType) {
  592. Log.d(TAG, "create MeasurementReadThread: " + socketType);
  593. mmSocket = socket;
  594. InputStream tmpIn = null;
  595. OutputStream tmpOut = null;
  596.  
  597. // Get the BluetoothSocket input and output streams
  598. try {
  599. tmpIn = socket.getInputStream();
  600. tmpOut = socket.getOutputStream();
  601. } catch (IOException e) {
  602. Log.e(TAG, "temp sockets not created", e);
  603. }
  604.  
  605. mmInStream = tmpIn;
  606. mmOutStream = tmpOut;
  607. }
  608.  
  609. public void run() {
  610. Log.i(TAG, "BEGIN mConnectedThread");
  611. byte[] buffer = new byte[1024];
  612. int bytes;
  613.  
  614. // Keep listening to the InputStream while connected
  615. byte[] command = new byte[] { (byte) 0xAA, (byte) 0x05,
  616. (byte) 0x00, (byte) 0x1E, (byte) 0x40, (byte) 0x40,
  617. (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
  618. (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
  619. (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
  620. (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
  621. (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
  622. (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
  623. (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
  624. (byte) 0xAE, (byte) 0x25, (byte) 0x55 };
  625.  
  626. try {
  627. mmOutStream.write(command);
  628. } catch (IOException e) {
  629. Log.e(TAG, "disconnected", e);
  630. connectionLost();
  631. cancel();
  632. }
  633.  
  634. while (!isCancelled && mState == STATE_CONNECTED) {
  635. try {
  636.  
  637. if (mmInStream.available() > 0) {
  638. // Read from the InputStream
  639. bytes = mmInStream.read(buffer);
  640.  
  641. // Send the obtained bytes to the UI Activity
  642. mHandler.obtainMessage(
  643. GlobalValues.MESSAGE_SET_ALIAS_READ, bytes, -1,
  644. buffer).sendToTarget();
  645.  
  646. // HHDCommandResponseParser parser = new HHDCommandResponseParser();
  647. // MeasurementData measurementData = parser
  648. // .parseMeasurementData(buffer);
  649. // SetAliasResponseModel
  650. // setAliasResponseData=parser.parseSetAlialRessponseData(buffer);
  651. // Log.d(TAG,
  652. // "Response from set alias command:::"+setAliasResponseData.getResult());
  653. cancel();
  654. }
  655.  
  656. } catch (IOException e) {
  657. Log.e(TAG, "disconnected", e);
  658. connectionLost();
  659. cancel();
  660. break;
  661. }
  662.  
  663. try {
  664. Thread.sleep(1000);
  665. } catch (InterruptedException e) {
  666. e.printStackTrace();
  667. }
  668.  
  669. }
  670. }
  671.  
  672. /**
  673. * Write to the connected OutStream.
  674. *
  675. * @param buffer
  676. * The bytes to write
  677. */
  678. @SuppressWarnings("unused")
  679. public void write(byte[] buffer) {
  680. try {
  681. mmOutStream.write(buffer);
  682.  
  683. // Share the sent message back to the UI Activity
  684. mHandler.obtainMessage(GlobalValues.MESSAGE_WRITE, -1, -1,
  685. buffer).sendToTarget();
  686. } catch (IOException e) {
  687. Log.e(TAG, "Exception during write", e);
  688. }
  689. }
  690.  
  691. public void cancel() {
  692. try {
  693. mmOutStream.close();
  694. mmInStream.close();
  695. isCancelled = true;
  696. mmSocket.close();
  697. } catch (IOException e) {
  698. Log.e(TAG, "close() of connect socket failed", e);
  699. }
  700. }
  701. }
  702.  
  703. /**
  704. * @author Pratik. This thread runs during a connection with a remote
  705. * device. It handles all incoming and outgoing transmissions.
  706. */
  707. @SuppressWarnings("unused")
  708. private class StartCaliberationThread extends Thread {
  709. private BluetoothSocket mmSocket;
  710. private InputStream mmInStream;
  711. private OutputStream mmOutStream;
  712.  
  713. boolean isCancelled = false;
  714.  
  715. public StartCaliberationThread(BluetoothSocket socket, String socketType) {
  716. Log.d(TAG, "create MeasurementReadThread: " + socketType);
  717. mmSocket = socket;
  718. InputStream tmpIn = null;
  719. OutputStream tmpOut = null;
  720.  
  721. // Get the BluetoothSocket input and output streams
  722. try {
  723. tmpIn = socket.getInputStream();
  724. tmpOut = socket.getOutputStream();
  725. } catch (IOException e) {
  726. Log.e(TAG, "temp sockets not created", e);
  727. }
  728.  
  729. mmInStream = tmpIn;
  730. mmOutStream = tmpOut;
  731. }
  732.  
  733. public void run() {
  734. Log.i(TAG, "BEGIN mConnectedThread");
  735. byte[] buffer = new byte[1024];
  736. int bytes;
  737.  
  738. // Keep listening to the InputStream while connected
  739. byte[] command = new byte[] { (byte) 0xAA, (byte) 0x06,
  740. (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x8E,
  741. (byte) 0x00, (byte) 0x55 };
  742.  
  743. try {
  744. mmOutStream.write(command);
  745. } catch (IOException e) {
  746. Log.e(TAG, "disconnected", e);
  747. connectionLost();
  748. cancel();
  749. }
  750.  
  751. while (!isCancelled && mState == STATE_CONNECTED) {
  752. try {
  753.  
  754. if (mmInStream.available() > 0) {
  755. // Read from the InputStream
  756. bytes = mmInStream.read(buffer);
  757.  
  758. // Send the obtained bytes to the UI Activity
  759. mHandler.obtainMessage(
  760. GlobalValues.MESSAGE_START_CALIBERATION_MODE,
  761. bytes, -1, buffer).sendToTarget();
  762.  
  763. HHDCommandResponseParser parser = new HHDCommandResponseParser();
  764. // MeasurementData measurementData = parser
  765. // .parseMeasurementData(buffer);
  766. CaliberationResponseModel startCaliberationResponseData = parser
  767. .parseStartCaliberationRessponseData(buffer);
  768. Log.d(TAG, "Response from start calibration command:::"
  769. + startCaliberationResponseData.getResult());
  770. cancel();
  771. }
  772.  
  773. } catch (IOException e) {
  774. Log.e(TAG, "disconnected", e);
  775. connectionLost();
  776. cancel();
  777. break;
  778. }
  779.  
  780. try {
  781. Thread.sleep(1000);
  782. } catch (InterruptedException e) {
  783. e.printStackTrace();
  784. }
  785.  
  786. }
  787. }
  788.  
  789. /**
  790. * Write to the connected OutStream.
  791. *
  792. * @param buffer
  793. * The bytes to write
  794. */
  795. public void write(byte[] buffer) {
  796. try {
  797. mmOutStream.write(buffer);
  798.  
  799. // Share the sent message back to the UI Activity
  800. mHandler.obtainMessage(GlobalValues.MESSAGE_WRITE, -1, -1,
  801. buffer).sendToTarget();
  802. } catch (IOException e) {
  803. Log.e(TAG, "Exception during write", e);
  804. }
  805. }
  806.  
  807. public void cancel() {
  808. try {
  809. mmOutStream.close();
  810. mmInStream.close();
  811. isCancelled = true;
  812. mmSocket.close();
  813. } catch (IOException e) {
  814. Log.e(TAG, "close() of connect socket failed", e);
  815. }
  816. }
  817. }
  818.  
  819. /**
  820. * @author Pratik. This thread runs during a connection with a remote
  821. * device. It handles all incoming and outgoing transmissions.
  822. */
  823. @SuppressWarnings("unused")
  824. private class StartCaliberationReadingThread extends Thread {
  825. private BluetoothSocket mmSocket;
  826. private InputStream mmInStream;
  827. private OutputStream mmOutStream;
  828.  
  829. boolean isCancelled = false;
  830.  
  831. public StartCaliberationReadingThread(BluetoothSocket socket,
  832. String socketType) {
  833. Log.d(TAG, "create MeasurementReadThread: " + socketType);
  834. mmSocket = socket;
  835. InputStream tmpIn = null;
  836. OutputStream tmpOut = null;
  837.  
  838. // Get the BluetoothSocket input and output streams
  839. try {
  840. tmpIn = socket.getInputStream();
  841. tmpOut = socket.getOutputStream();
  842. } catch (IOException e) {
  843. Log.e(TAG, "temp sockets not created", e);
  844. }
  845.  
  846. mmInStream = tmpIn;
  847. mmOutStream = tmpOut;
  848. }
  849.  
  850. public void run() {
  851. Log.i(TAG, "BEGIN mConnectedThread");
  852. byte[] buffer = new byte[1024];
  853. int bytes;
  854.  
  855. // Keep listening to the InputStream while connected
  856. byte[] command = new byte[] { (byte) 0xAA, (byte) 0x02,
  857. (byte) 0x00, (byte) 0x00, (byte) 0x9F, (byte) 0xFD,
  858. (byte) 0x55 };
  859.  
  860. try {
  861. mmOutStream.write(command);
  862. } catch (IOException e) {
  863. Log.e(TAG, "disconnected", e);
  864. connectionLost();
  865. cancel();
  866. }
  867.  
  868. while (!isCancelled && mState == STATE_CONNECTED) {
  869. try {
  870.  
  871. if (mmInStream.available() > 0) {
  872. // Read from the InputStream
  873. bytes = mmInStream.read(buffer);
  874.  
  875. // Send the obtained bytes to the UI Activity
  876. mHandler.obtainMessage(
  877. GlobalValues.MESSAGE_CALIBERATION_READING,
  878. bytes, -1, buffer).sendToTarget();
  879.  
  880. // HHDCommandResponseParser parser = new
  881. // HHDCommandResponseParser();
  882. // MeasurementData measurementData = parser
  883. // .parseMeasurementData(buffer);
  884. // CaliberationResponseModel
  885. // startCaliberationResponseData = parser
  886. // .parseStartCaliberationRessponseData(buffer);
  887. // Log.d(TAG, "Response from set alias command:::"
  888. // + startCaliberationResponseData.getResult());
  889. cancel();
  890. }
  891.  
  892. } catch (IOException e) {
  893. Log.e(TAG, "disconnected", e);
  894. connectionLost();
  895. cancel();
  896. break;
  897. }
  898.  
  899. try {
  900. Thread.sleep(1000);
  901. } catch (InterruptedException e) {
  902. e.printStackTrace();
  903. }
  904.  
  905. }
  906. }
  907.  
  908. /**
  909. * Write to the connected OutStream.
  910. *
  911. * @param buffer
  912. * The bytes to write
  913. */
  914. public void write(byte[] buffer) {
  915. try {
  916. mmOutStream.write(buffer);
  917.  
  918. // Share the sent message back to the UI Activity
  919. mHandler.obtainMessage(GlobalValues.MESSAGE_WRITE, -1, -1,
  920. buffer).sendToTarget();
  921. } catch (IOException e) {
  922. Log.e(TAG, "Exception during write", e);
  923. }
  924. }
  925.  
  926. public void cancel() {
  927. try {
  928. mmOutStream.close();
  929. mmInStream.close();
  930. isCancelled = true;
  931. mmSocket.close();
  932. } catch (IOException e) {
  933. Log.e(TAG, "close() of connect socket failed", e);
  934. }
  935. }
  936.  
  937. }
  938.  
  939. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement