Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothSocket;
- import android.content.Context;
- import android.os.Bundle;
- import android.os.Message;
- import android.util.Log;
- import com.example.models.CaliberationResponseModel;
- import com.example.settings.Measurement;
- import com.spSoft.handheldDeviceAndroidApp.communication.model.MeasurementData;
- import com.spSoft.handheldDeviceAndroidApp.communication.parser.HHDCommandResponseParser;
- import com.spSoft.handheldDeviceAndroidApp.logger.BaseLoggerException;
- import com.spSoft.handheldDeviceAndroidApp.logger.CsvWriter;
- import com.spSoft.handheldDeviceAndroidApp.logger.Logger;
- import com.spSoft.utils.AppPreferences;
- import com.spSoft.utils.GlobalValues;
- /**
- * This class does all the work for setting up and managing Bluetooth
- * connections with other devices. It has a thread that listens for incoming
- * connections, a thread for connecting with a device, and a thread for
- * performing data transmissions when connected.
- */
- public class HHDBTService {
- // Debugging
- private static final String TAG = "HHDBTService";
- private static final boolean D = true;
- // Member fields
- private final BluetoothAdapter mAdapter;
- private static BapiHandler mHandler;
- AppPreferences bapiPreferences;
- private CsvWriter csvLogWriter;
- /*
- * private AcceptThread mSecureAcceptThread; private AcceptThread
- * mInsecureAcceptThread;
- */
- private ConnectThread mConnectThread;
- private MeasurementReadThread mConnectedThread;
- private SetAliasReadThread mSetAliasReadThread;
- private StartCaliberationThread mStartCaliberationThread;
- private StartCaliberationReadingThread mStartCaliberationReadingThread;
- private static int mState;
- // Constants that indicate the current connection state
- public static final int STATE_NONE = 0; // we're doing nothing
- public static final int STATE_LISTEN = 1; // now listening for incoming
- // connections
- public static final int STATE_CONNECTING = 2; // now initiating an outgoing
- // connection
- public static final int STATE_CONNECTED = 3; // now connected to a remote
- // device
- /**
- * Constructor. Prepares a new BluetoothChat session.
- *
- * @param context
- * The UI Activity Context
- * @param handler
- * A Handler to send messages back to the UI Activity
- */
- public HHDBTService(Context context, BapiHandler handler) {
- mAdapter = BluetoothAdapter.getDefaultAdapter();
- mState = STATE_NONE;
- mHandler = handler;
- bapiPreferences = new AppPreferences(context);
- setState(STATE_LISTEN);
- }
- /**
- * Set the current state of the chat connection
- *
- * @param state
- * An integer defining the current connection state
- */
- public synchronized static void setState(int state) {
- if (D)
- Log.d(TAG, "setState() " + mState + " -> " + state);
- mState = state;
- // Give the new state to the Handler so the UI Activity can update
- mHandler.obtainMessage(GlobalValues.MESSAGE_STATE_CHANGE, state, -1)
- .sendToTarget();
- }
- /**
- * Return the current connection state.
- */
- public synchronized int getState() {
- return mState;
- }
- /**
- * Start the chat service. Specifically start AcceptThread to begin a
- * session in listening (server) mode. Called by the Activity onResume()
- */
- /*
- * public synchronized void start() { if (D) Log.d(TAG, "start");
- *
- * // Cancel any thread attempting to make a connection if (mConnectThread
- * != null) { mConnectThread.cancel(); mConnectThread = null; }
- *
- * // Cancel any thread currently running a connection if (mConnectedThread
- * != null) { mConnectedThread.cancel(); mConnectedThread = null; }
- *
- * setState(STATE_LISTEN); }
- */
- /**
- * Start the ConnectThread to initiate a connection to a remote device.
- *
- * @param device
- * The BluetoothDevice to connect
- * @param secure
- * Socket Security type - Secure (true) , Insecure (false)
- */
- public synchronized void connect(BluetoothDevice device, boolean secure,
- int commandIndex) {
- /*
- * if (D) Log.d(TAG, "connect to: " + device);
- *
- * // Cancel any thread attempting to make a connection if (mState ==
- * STATE_CONNECTING) { if (mConnectThread != null) {
- * mConnectThread.cancel(); mConnectThread = null; } }
- *
- * // Cancel any thread currently running a connection if
- * (mConnectedThread != null) { mConnectedThread.cancel();
- * mConnectedThread = null; }
- */
- // Start the thread to connect with the given device
- mConnectThread = new ConnectThread(device, secure, commandIndex);
- mConnectThread.start();
- setState(STATE_CONNECTING);
- }
- /**
- * Start the MeasurementReadThread to begin managing a Bluetooth connection
- *
- * @param socket
- * The BluetoothSocket on which the connection was made
- * @param device
- * The BluetoothDevice that has been connected
- */
- public synchronized void connected(BluetoothSocket socket,
- BluetoothDevice device, final String socketType, int commandIndex) {
- if (D)
- Log.d(TAG, "connected, Socket Type:" + socketType);
- // Cancel the thread that completed the connection
- if (mConnectThread != null) {
- mConnectThread.cancel();
- mConnectThread = null;
- }
- /*
- * // Cancel any thread currently running a connection if
- * (mConnectedThread != null) { mConnectedThread.cancel();
- * mConnectedThread = null; }
- */
- // Start the thread to manage the connection and perform transmissions
- /*
- * mConnectedThread = new MeasurementReadThread(socket, socketType);
- * mConnectedThread.start();
- */
- // TODO start/write other threads here condition will come from Global
- // Class
- switch (commandIndex) {
- case GlobalValues.command_setMeasurement:
- mConnectedThread = new MeasurementReadThread(socket, socketType);
- mConnectedThread.start();
- break;
- case GlobalValues.command_setAlise:
- mConnectedThread = new MeasurementReadThread(socket, socketType);
- mConnectedThread.start();
- mSetAliasReadThread = new SetAliasReadThread(socket, socketType);
- mSetAliasReadThread.start();
- break;
- case GlobalValues.command_startCalibration:
- mStartCaliberationThread = new StartCaliberationThread(socket,
- socketType);
- mStartCaliberationThread.start();
- break;
- case GlobalValues.command_Calibration_reading:
- mStartCaliberationReadingThread = new StartCaliberationReadingThread(
- socket, socketType);
- mStartCaliberationReadingThread.start();
- break;
- }
- // Send the name of the connected device back to the UI Activity
- Message msg = mHandler.obtainMessage(GlobalValues.MESSAGE_DEVICE_NAME);
- Bundle bundle = new Bundle();
- bundle.putString(GlobalValues.KEY_CURRENT_CONNECTED_DEVICE_NAME,
- device.getName());
- msg.setData(bundle);
- mHandler.sendMessage(msg);
- setState(STATE_CONNECTED);
- }
- /**
- * Stop all threads
- */
- public synchronized void stop() {
- if (D)
- Log.d(TAG, "stop");
- if (mConnectThread != null) {
- mConnectThread.cancel();
- mConnectThread = null;
- }
- if (mConnectedThread != null) {
- mConnectedThread.cancel();
- mConnectedThread = null;
- }
- setState(STATE_NONE);
- }
- /**
- * Write to the MeasurementReadThread in an unsynchronized manner
- *
- * @param out
- * The bytes to write
- * @see MeasurementReadThread#write(byte[])
- */
- public void write(byte[] out) {
- // Create temporary object
- MeasurementReadThread r;
- // Synchronize a copy of the MeasurementReadThread
- synchronized (this) {
- if (mState != STATE_CONNECTED)
- return;
- r = mConnectedThread;
- }
- // Perform the write unsynchronized
- r.write(out);
- }
- /**
- * Indicate that the connection attempt failed and notify the UI Activity.
- */
- private void connectionFailed() {
- // Send a failure message back to the Activity
- if (Measurement.FLAG_DEVICE_LOST_FOUND) {
- Message msg = mHandler.obtainMessage(GlobalValues.MESSAGE_SHOW_TOAST);
- Bundle bundle = new Bundle();
- bundle.putString(GlobalValues.TOAST, "Unable to connect device");
- msg.setData(bundle);
- mHandler.sendMessage(msg);
- }
- // Start the service over to restart listening mode
- /* HHDBTService.this.start(); */
- }
- /**
- * Indicate that the connection was lost and notify the UI Activity.
- */
- private void connectionLost() {
- // Send a failure message back to the Activity
- /*
- * Message msg =
- * mHandler.obtainMessage(GlobalValues.MESSAGE_DEVICE_CONNECTION_LOST);
- * Bundle bundle = new Bundle(); bundle.putString(GlobalValues.TOAST,
- * "Device connection was lost"); msg.setData(bundle);
- * mHandler.sendMessage(msg);
- *
- * // Start the service over to restart listening mode
- * HHDBTService.this.start();
- */
- /**
- * @author Sandip Removing all threads and stating state to none
- */
- if (D)
- Log.d(TAG, "start");
- // Cancel any thread attempting to make a connection
- if (mConnectThread != null) {
- mConnectThread.cancel();
- mConnectThread = null;
- }
- // Cancel any thread currently running a connection
- if (mConnectedThread != null) {
- mConnectedThread.cancel();
- mConnectedThread = null;
- }
- setState(STATE_NONE);
- }
- /**
- * This thread runs while attempting to make an outgoing connection with a
- * device. It runs straight through; the connection either succeeds or
- * fails.
- */
- private class ConnectThread extends Thread {
- private BluetoothSocket mmSocket;
- private final BluetoothDevice mmDevice;
- private String mSocketType;
- private int mCommandIndex;
- public ConnectThread(BluetoothDevice device, boolean secure,
- int commandIndex) {
- mmDevice = device;
- mSocketType = secure ? "Secure" : "Insecure";
- mCommandIndex = commandIndex;
- }
- protected boolean simpleComm(Integer port) {
- // byte [] inputBytes = null;
- // The documents tell us to cancel the discovery process.
- mAdapter.cancelDiscovery();
- Log.d(this.toString(), "Port = " + port);
- try {
- // This is a hack to access "createRfcommSocket which is does
- // not
- // have public access in the current api.
- // Note: BlueToothDevice.createRfcommSocketToServiceRecord (UUID
- // uuid) does not work in this type of application. .
- Method m = mmDevice.getClass().getMethod("createRfcommSocket",
- new Class[] { int.class });
- mmSocket = (BluetoothSocket) m.invoke(mmDevice, port);
- // debug check to ensure socket was set.
- assert (mmSocket != null) : "Socket is Null";
- mAdapter.cancelDiscovery();
- // attempt to connect to device
- mmSocket.connect();
- /*try {
- Log.d(this.toString(),
- "************ CONNECTION SUCCEES! *************");
- connected(mmSocket, mmDevice, mSocketType, mCommandIndex);
- return true;
- } finally {
- // close the socket and we are done.
- // //mmSocket.close();
- }*/
- // IOExcecption is thrown if connect fails.
- } catch (IOException ex) {
- Log.e(this.toString(), "IOException " + ex.getMessage());
- if (port == 3) {
- connectionFailed();
- try {
- mmSocket.close();
- mmSocket = null;
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- // NoSuchMethodException IllegalAccessException
- // InvocationTargetException
- // are reflection exceptions.
- } catch (NoSuchMethodException ex) {
- Log.e(this.toString(),
- "NoSuchMethodException " + ex.getMessage());
- } catch (IllegalAccessException ex) {
- Log.e(this.toString(),
- "IllegalAccessException " + ex.getMessage());
- } catch (InvocationTargetException ex) {
- Log.e(this.toString(),
- "InvocationTargetException " + ex.getMessage());
- }
- return false;
- }
- public void run() {
- for (Integer port = 1; port <= 3; port++) {
- if (simpleComm(Integer.valueOf(port)))
- break;
- }
- // Reset the ConnectThread because we're done
- synchronized (HHDBTService.this) {
- mConnectThread = null;
- }
- connected(mmSocket, mmDevice, mSocketType, mCommandIndex);
- }
- public void cancel() {
- /*
- * try { mmSocket.close(); } catch (IOException e) { Log.e(TAG,
- * "close() of connect " + mSocketType + " socket failed", e); }
- */
- }
- }
- /**
- * This thread runs during a connection with a remote device. It handles all
- * incoming and outgoing transmissions.
- */
- private class MeasurementReadThread extends Thread {
- private BluetoothSocket mmSocket;
- private InputStream mmInStream;
- private OutputStream mmOutStream;
- private Logger logger;
- private boolean isFirst = true;
- boolean isCancelled = false;
- public MeasurementReadThread(BluetoothSocket socket, String socketType) {
- Log.d(TAG, "create MeasurementReadThread: " + socketType);
- mmSocket = socket;
- InputStream tmpIn = null;
- OutputStream tmpOut = null;
- // Get the BluetoothSocket input and output streams
- try {
- tmpIn = socket.getInputStream();
- tmpOut = socket.getOutputStream();
- } catch (IOException e) {
- Log.e(TAG, "temp sockets not created", e);
- }
- logger = Logger.getInstance();
- mmInStream = tmpIn;
- mmOutStream = tmpOut;
- }
- public void run() {
- Log.i(TAG, "BEGIN mConnectedThread");
- byte[] buffer = new byte[1024];
- int bytes;
- // Keep listening to the InputStream while connected
- while (!isCancelled && mState == STATE_CONNECTED) {
- try {
- byte[] command = new byte[] { (byte) 0xAA, (byte) 0x02,
- (byte) 0x00, (byte) 0x00, (byte) 0x9F, (byte) 0xFD,
- (byte) 0x55 };
- mmOutStream.write(command);
- if (mmInStream.available() > 0) {
- // Read from the InputStream
- bytes = mmInStream.read(buffer);
- // Send the obtained bytes to the UI Activity
- mHandler.obtainMessage(GlobalValues.MESSAGE_MEASUREMENT_READING,
- bytes, -1, buffer).sendToTarget();
- // if logging enabled then record data in database here
- if (!bapiPreferences.getPreferences(
- GlobalValues.KEY_LOG_STATUS,
- GlobalValues.LOG_DISABLED).equals(
- GlobalValues.LOG_DISABLED)) {
- try {
- HHDCommandResponseParser parser = new HHDCommandResponseParser();
- MeasurementData measurementData = parser
- .parseMeasurementData(buffer);
- logger.recordLog(measurementData
- .getTemperature(),
- String.valueOf(measurementData
- .getTempUnit()),
- measurementData.getHumidity(), String
- .valueOf(measurementData
- .getHumidityUnit()),
- measurementData.getDate(),
- measurementData.getTime());
- if (!bapiPreferences
- .getPreferences(
- GlobalValues.KEY_CSV_FILE_LOG_STATUS,
- GlobalValues.CSV_FILE_LOG_DISABLED)
- .equals(GlobalValues.CSV_FILE_LOG_DISABLED)) {
- // add to csv file code here
- csvLogWriter = new CsvWriter(
- GlobalValues.CSV_FILE_DIRECTORY_PATH,
- bapiPreferences
- .getPreferences(
- GlobalValues.KEY_CSV_FILE_NAME,
- "Bapi.csv"));
- String record = new String(
- String.valueOf(measurementData
- .getTemperature())
- + ","
- + measurementData
- .getTempUnit()
- + ","
- + String.valueOf(measurementData
- .getHumidity())
- + ","
- + measurementData
- .getHumidityUnit()
- + ","
- + measurementData.getDate()
- + ","
- + measurementData.getTime());
- csvLogWriter.writeRecordToFile(record);
- }
- } catch (BaseLoggerException e) {
- Log.d(HHDBTService.class.toString(),
- "EXCEPTION WHILE LOGGING:"
- + e.getMessage());
- }
- }
- }
- } catch (IOException e) {
- Log.e(TAG, "disconnected", e);
- connectionLost();
- break;
- }
- try {
- if (!isFirst) {
- if (!bapiPreferences.getPreferences(
- GlobalValues.KEY_AUTO_MANUAL,
- GlobalValues.MANUAL)
- .equals(GlobalValues.MANUAL))
- Thread.sleep(5000);
- else
- cancel();
- } else {
- Thread.sleep(1000);
- isFirst = false;
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Write to the connected OutStream.
- *
- * @param buffer
- * The bytes to write
- */
- public void write(byte[] buffer) {
- try {
- mmOutStream.write(buffer);
- // Share the sent message back to the UI Activity
- mHandler.obtainMessage(GlobalValues.MESSAGE_WRITE, -1, -1,
- buffer).sendToTarget();
- } catch (IOException e) {
- Log.e(TAG, "Exception during write", e);
- }
- }
- public void cancel() {
- try {
- mmOutStream.close();
- mmInStream.close();
- isCancelled = true;
- mmSocket.close();
- } catch (IOException e) {
- Log.e(TAG, "close() of connect socket failed", e);
- }
- }
- }
- /**
- * This thread runs during a connection with a remote device. It handles all
- * incoming and outgoing transmissions.
- */
- private class SetAliasReadThread extends Thread {
- private BluetoothSocket mmSocket;
- private InputStream mmInStream;
- private OutputStream mmOutStream;
- boolean isCancelled = false;
- public SetAliasReadThread(BluetoothSocket socket, String socketType) {
- Log.d(TAG, "create MeasurementReadThread: " + socketType);
- mmSocket = socket;
- InputStream tmpIn = null;
- OutputStream tmpOut = null;
- // Get the BluetoothSocket input and output streams
- try {
- tmpIn = socket.getInputStream();
- tmpOut = socket.getOutputStream();
- } catch (IOException e) {
- Log.e(TAG, "temp sockets not created", e);
- }
- mmInStream = tmpIn;
- mmOutStream = tmpOut;
- }
- public void run() {
- Log.i(TAG, "BEGIN mConnectedThread");
- byte[] buffer = new byte[1024];
- int bytes;
- // Keep listening to the InputStream while connected
- byte[] command = new byte[] { (byte) 0xAA, (byte) 0x05,
- (byte) 0x00, (byte) 0x1E, (byte) 0x40, (byte) 0x40,
- (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
- (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
- (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
- (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
- (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
- (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
- (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40,
- (byte) 0xAE, (byte) 0x25, (byte) 0x55 };
- try {
- mmOutStream.write(command);
- } catch (IOException e) {
- Log.e(TAG, "disconnected", e);
- connectionLost();
- cancel();
- }
- while (!isCancelled && mState == STATE_CONNECTED) {
- try {
- if (mmInStream.available() > 0) {
- // Read from the InputStream
- bytes = mmInStream.read(buffer);
- // Send the obtained bytes to the UI Activity
- mHandler.obtainMessage(
- GlobalValues.MESSAGE_SET_ALIAS_READ, bytes, -1,
- buffer).sendToTarget();
- // HHDCommandResponseParser parser = new HHDCommandResponseParser();
- // MeasurementData measurementData = parser
- // .parseMeasurementData(buffer);
- // SetAliasResponseModel
- // setAliasResponseData=parser.parseSetAlialRessponseData(buffer);
- // Log.d(TAG,
- // "Response from set alias command:::"+setAliasResponseData.getResult());
- cancel();
- }
- } catch (IOException e) {
- Log.e(TAG, "disconnected", e);
- connectionLost();
- cancel();
- break;
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Write to the connected OutStream.
- *
- * @param buffer
- * The bytes to write
- */
- @SuppressWarnings("unused")
- public void write(byte[] buffer) {
- try {
- mmOutStream.write(buffer);
- // Share the sent message back to the UI Activity
- mHandler.obtainMessage(GlobalValues.MESSAGE_WRITE, -1, -1,
- buffer).sendToTarget();
- } catch (IOException e) {
- Log.e(TAG, "Exception during write", e);
- }
- }
- public void cancel() {
- try {
- mmOutStream.close();
- mmInStream.close();
- isCancelled = true;
- mmSocket.close();
- } catch (IOException e) {
- Log.e(TAG, "close() of connect socket failed", e);
- }
- }
- }
- /**
- * @author Pratik. This thread runs during a connection with a remote
- * device. It handles all incoming and outgoing transmissions.
- */
- @SuppressWarnings("unused")
- private class StartCaliberationThread extends Thread {
- private BluetoothSocket mmSocket;
- private InputStream mmInStream;
- private OutputStream mmOutStream;
- boolean isCancelled = false;
- public StartCaliberationThread(BluetoothSocket socket, String socketType) {
- Log.d(TAG, "create MeasurementReadThread: " + socketType);
- mmSocket = socket;
- InputStream tmpIn = null;
- OutputStream tmpOut = null;
- // Get the BluetoothSocket input and output streams
- try {
- tmpIn = socket.getInputStream();
- tmpOut = socket.getOutputStream();
- } catch (IOException e) {
- Log.e(TAG, "temp sockets not created", e);
- }
- mmInStream = tmpIn;
- mmOutStream = tmpOut;
- }
- public void run() {
- Log.i(TAG, "BEGIN mConnectedThread");
- byte[] buffer = new byte[1024];
- int bytes;
- // Keep listening to the InputStream while connected
- byte[] command = new byte[] { (byte) 0xAA, (byte) 0x06,
- (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x8E,
- (byte) 0x00, (byte) 0x55 };
- try {
- mmOutStream.write(command);
- } catch (IOException e) {
- Log.e(TAG, "disconnected", e);
- connectionLost();
- cancel();
- }
- while (!isCancelled && mState == STATE_CONNECTED) {
- try {
- if (mmInStream.available() > 0) {
- // Read from the InputStream
- bytes = mmInStream.read(buffer);
- // Send the obtained bytes to the UI Activity
- mHandler.obtainMessage(
- GlobalValues.MESSAGE_START_CALIBERATION_MODE,
- bytes, -1, buffer).sendToTarget();
- HHDCommandResponseParser parser = new HHDCommandResponseParser();
- // MeasurementData measurementData = parser
- // .parseMeasurementData(buffer);
- CaliberationResponseModel startCaliberationResponseData = parser
- .parseStartCaliberationRessponseData(buffer);
- Log.d(TAG, "Response from start calibration command:::"
- + startCaliberationResponseData.getResult());
- cancel();
- }
- } catch (IOException e) {
- Log.e(TAG, "disconnected", e);
- connectionLost();
- cancel();
- break;
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Write to the connected OutStream.
- *
- * @param buffer
- * The bytes to write
- */
- public void write(byte[] buffer) {
- try {
- mmOutStream.write(buffer);
- // Share the sent message back to the UI Activity
- mHandler.obtainMessage(GlobalValues.MESSAGE_WRITE, -1, -1,
- buffer).sendToTarget();
- } catch (IOException e) {
- Log.e(TAG, "Exception during write", e);
- }
- }
- public void cancel() {
- try {
- mmOutStream.close();
- mmInStream.close();
- isCancelled = true;
- mmSocket.close();
- } catch (IOException e) {
- Log.e(TAG, "close() of connect socket failed", e);
- }
- }
- }
- /**
- * @author Pratik. This thread runs during a connection with a remote
- * device. It handles all incoming and outgoing transmissions.
- */
- @SuppressWarnings("unused")
- private class StartCaliberationReadingThread extends Thread {
- private BluetoothSocket mmSocket;
- private InputStream mmInStream;
- private OutputStream mmOutStream;
- boolean isCancelled = false;
- public StartCaliberationReadingThread(BluetoothSocket socket,
- String socketType) {
- Log.d(TAG, "create MeasurementReadThread: " + socketType);
- mmSocket = socket;
- InputStream tmpIn = null;
- OutputStream tmpOut = null;
- // Get the BluetoothSocket input and output streams
- try {
- tmpIn = socket.getInputStream();
- tmpOut = socket.getOutputStream();
- } catch (IOException e) {
- Log.e(TAG, "temp sockets not created", e);
- }
- mmInStream = tmpIn;
- mmOutStream = tmpOut;
- }
- public void run() {
- Log.i(TAG, "BEGIN mConnectedThread");
- byte[] buffer = new byte[1024];
- int bytes;
- // Keep listening to the InputStream while connected
- byte[] command = new byte[] { (byte) 0xAA, (byte) 0x02,
- (byte) 0x00, (byte) 0x00, (byte) 0x9F, (byte) 0xFD,
- (byte) 0x55 };
- try {
- mmOutStream.write(command);
- } catch (IOException e) {
- Log.e(TAG, "disconnected", e);
- connectionLost();
- cancel();
- }
- while (!isCancelled && mState == STATE_CONNECTED) {
- try {
- if (mmInStream.available() > 0) {
- // Read from the InputStream
- bytes = mmInStream.read(buffer);
- // Send the obtained bytes to the UI Activity
- mHandler.obtainMessage(
- GlobalValues.MESSAGE_CALIBERATION_READING,
- bytes, -1, buffer).sendToTarget();
- // HHDCommandResponseParser parser = new
- // HHDCommandResponseParser();
- // MeasurementData measurementData = parser
- // .parseMeasurementData(buffer);
- // CaliberationResponseModel
- // startCaliberationResponseData = parser
- // .parseStartCaliberationRessponseData(buffer);
- // Log.d(TAG, "Response from set alias command:::"
- // + startCaliberationResponseData.getResult());
- cancel();
- }
- } catch (IOException e) {
- Log.e(TAG, "disconnected", e);
- connectionLost();
- cancel();
- break;
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Write to the connected OutStream.
- *
- * @param buffer
- * The bytes to write
- */
- public void write(byte[] buffer) {
- try {
- mmOutStream.write(buffer);
- // Share the sent message back to the UI Activity
- mHandler.obtainMessage(GlobalValues.MESSAGE_WRITE, -1, -1,
- buffer).sendToTarget();
- } catch (IOException e) {
- Log.e(TAG, "Exception during write", e);
- }
- }
- public void cancel() {
- try {
- mmOutStream.close();
- mmInStream.close();
- isCancelled = true;
- mmSocket.close();
- } catch (IOException e) {
- Log.e(TAG, "close() of connect socket failed", e);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement