public static BLEInputStream getInstance() { if (bleInputStream == null) { bleInputStream = new BLEInputStream(); } return bleInputStream; }
public void readChangedCharacteristic(BluetoothGattCharacteristic characteristic) { byte[] data; data = characteristic.getValue(); // *** this is going to get overwritten by next call, so make a queue if (data != null && data.length > 0 && (isConnected())) { messageBuffer.append(new String(data, 0, data.length)); if(JsonStreamer.containsJson(messageBuffer.toString())) { int delimiterIndex = messageBuffer.indexOf(DELIMITER); if (delimiterIndex != -1) { byte message[] = messageBuffer.substring(0, delimiterIndex + 1).getBytes(); BLEInputStream.getInstance().putDataInBuffer(message); messageBuffer.delete(0, delimiterIndex + 1); } } else { BLEInputStream.getInstance().putDataInBuffer(data); } } }
private void connectStreams() throws BluetoothException { mConnectionLock.writeLock().lock(); try { if (!connectingToBLE) { try { mOutStream = new BufferedWriter(new OutputStreamWriter( mSocket.getOutputStream())); mInStream = new BufferedInputStream(mSocket.getInputStream()); Log.i(TAG, "Socket stream to vehicle interface " + "opened successfully"); } catch (IOException e) { Log.e(TAG, "Error opening streams ", e); disconnect(); throw new BluetoothException(); } } else { mBLEInputStream = BLEInputStream.getInstance(); mBLEInputStream.clearBuffer(); mInStream = new BufferedInputStream(mBLEInputStream); Log.i(TAG, "Input stream to vehicle interface " + "opened successfully"); } } finally { mConnectionLock.writeLock().unlock(); } }
@Override protected int read(byte[] bytes) throws IOException { mConnectionLock.readLock().lock(); int bytesRead = -1; if (connectingToBLE) { bytesRead = 0; } try { if (isConnected() && !connectingToBLE) { bytesRead = mInStream.read(bytes, 0, bytes.length); } else if (isConnected()) { if (mBLEInputStream != null && mBLEInputStream.doesBufferHasRemaining()) { bytesRead = mInStream.read(bytes, 0, bytes.length); } else if (mDeviceManager.isBLEDisconnected()) { //Disconnect BLE if GattCallBack state changed to disconnected mConnectedAddress = null; bytesRead = -1; } } } finally { mConnectionLock.readLock().unlock(); } return bytesRead; }