Java Code Examples for android.bluetooth.BluetoothProfile#STATE_CONNECTING

The following examples show how to use android.bluetooth.BluetoothProfile#STATE_CONNECTING . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NukiCallback.java    From trigger with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    //Log.i(TAG, "status: " + getGattStatus(status) + ", newState: " + newState);

    if (status == GATT_SUCCESS) {
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTED:
                gatt.discoverServices();
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                closeConnection(gatt);
                break;
            case BluetoothProfile.STATE_CONNECTING:
            case BluetoothProfile.STATE_DISCONNECTING:
                break;
        }
    } else {
        closeConnection(gatt);
        this.listener.onTaskResult(
            setup_id, ReplyCode.REMOTE_ERROR, "Connection error: " + NukiRequestHandler.getGattStatus(status)
        );
    }
}
 
Example 2
Source File: BaseBleService.java    From bleYan with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
	BleLog.i(TAG, "onConnectionStateChange: State = " + BleUtils.getBleConnectStatus(status)
			+ " newState = " + BleUtils.getBleConnectStatus(newState));

	if (newState == BluetoothProfile.STATE_CONNECTED) {
		updateState(BleConnectState.CONNECTED);
		//start discoverServices
		BleLog.i(TAG, "gatt.discoverServices()");
		gatt.discoverServices();
	} else if (newState == BluetoothProfile.STATE_CONNECTING) {
		updateState(BleConnectState.CONNECTING);
	} else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
		updateState(BleConnectState.DISCONNECTING);
	} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
		//disconnect
		sIsWriting = false;
		sWriteQueue.clear();
		updateState(BleConnectState.DISCONNECTED);
          }
}
 
Example 3
Source File: BleUtils.java    From bleYan with GNU General Public License v2.0 6 votes vote down vote up
public static String getBleConnectStatus(int status) {
    switch (status) {
        case BluetoothProfile.STATE_DISCONNECTED:
            return "STATE_DISCONNECTED";

        case BluetoothProfile.STATE_CONNECTING:
            return "STATE_CONNECTING";

        case BluetoothProfile.STATE_CONNECTED:
            return "STATE_CONNECTED";

        case BluetoothProfile.STATE_DISCONNECTING:
            return "STATE_DISCONNECTING";

        default:
            return "STATE_UNKNOWN: " + status;
    }
}
 
Example 4
Source File: BtPairStateMachine.java    From apollo-DuerOS with Apache License 2.0 6 votes vote down vote up
@Override
public boolean processMessage(Message msg) {
    switch(msg.what) {
        case EVENT_MD_READY:
            int connState = getHfpConnectionState();
            if (connState == BluetoothProfile.STATE_DISCONNECTED) {
                transitionTo(mPairDisconnectedState);
            } else if (connState == BluetoothProfile.STATE_CONNECTED) {
                deferMessage(obtainMessage(EVENT_CHECK_HFP_CONNECTION));
                transitionTo(mPairConnectedState);
            } else if (connState == BluetoothProfile.STATE_DISCONNECTING) {
                sendMessageDelayed(EVENT_MD_READY, 2000);
            } else if (connState == BluetoothProfile.STATE_CONNECTING) {
                sendMessageDelayed(EVENT_MD_READY, 2000);
            } else {
                deferMessage(obtainMessage(EVENT_ON_ERROR, ERROR_CHECK_CONNECTION, 0));
                transitionTo(mPairErrorState);
            }
            return HANDLED;
        default:
            return NOT_HANDLED;
    }
}
 
Example 5
Source File: PBluetoothLEClientBak.java    From PHONK with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

    if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionStatus = DISCONNECTED;
    } else if (newState == BluetoothProfile.STATE_CONNECTING) {
        mConnectionStatus = CONNECTING;
    } else if (newState == BluetoothProfile.STATE_CONNECTED) {
        mConnectionStatus = CONNECTED;
    } else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
        mConnectionStatus = DISCONNECTING;
    }

    MLog.d(TAG, "connected " + mConnectionStatus);

    if (mCallbackGattConnection != null) {
        ReturnObject o = new ReturnObject();
        o.put("status", mConnectionStatus);
        o.put("gatt", gatt);
        mCallbackGattConnection.event(o);
    }
}
 
Example 6
Source File: ParserUtils.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Converts the connection state to String value.
 *
 * @param state the connection state
 * @return state as String
 */
@NonNull
public static String stateToString(@ConnectionState final int state) {
	switch (state) {
		case BluetoothProfile.STATE_CONNECTED:
			return "CONNECTED";
		case BluetoothProfile.STATE_CONNECTING:
			return "CONNECTING";
		case BluetoothProfile.STATE_DISCONNECTING:
			return "DISCONNECTING";
		case BluetoothProfile.STATE_DISCONNECTED:
			return "DISCONNECTED";
		default:
			return "UNKNOWN (" + state + ")";
	}
}
 
Example 7
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 6 votes vote down vote up
/**
 * Disconnect the bluetooth peripheral.
 *
 * <p>When the disconnection has been completed {@link BluetoothCentralCallback#onDisconnectedPeripheral(BluetoothPeripheral, int)} will be called.
 */
private void disconnect() {
    if (state == BluetoothProfile.STATE_CONNECTED || state == BluetoothProfile.STATE_CONNECTING) {
        this.state = BluetoothProfile.STATE_DISCONNECTING;
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (bluetoothGatt != null) {
                    Timber.i("force disconnect '%s' (%s)", getName(), getAddress());
                    bluetoothGatt.disconnect();
                }
            }
        });
    } else {
        if (listener != null) {
            listener.disconnected(BluetoothPeripheral.this, GATT_CONN_TERMINATE_LOCAL_HOST);
        }
    }
}
 
Example 8
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 6 votes vote down vote up
private void successfullyDisconnected(int previousState) {
    if (previousState == BluetoothProfile.STATE_CONNECTED || previousState == BluetoothProfile.STATE_DISCONNECTING) {
        Timber.i("disconnected '%s' on request", getName());
    } else if (previousState == BluetoothProfile.STATE_CONNECTING) {
        Timber.i("cancelling connect attempt");
    }

    if (bondLost) {
        completeDisconnect(false, GATT_SUCCESS);
        if (listener != null) {
            // Consider the loss of the bond a connection failure so that a connection retry will take place
            callbackHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    listener.connectFailed(BluetoothPeripheral.this, GATT_SUCCESS);
                }
            }, DELAY_AFTER_BOND_LOST); // Give the stack some time to register the bond loss internally. This is needed on most phones...
        }
    } else {
        completeDisconnect(true, GATT_SUCCESS);
    }
}
 
Example 9
Source File: BaseMyo.java    From myolib with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTING) {
        mConnectionState = ConnectionState.CONNECTING;
    } else if (newState == BluetoothProfile.STATE_CONNECTED) {
        mConnectionState = ConnectionState.CONNECTED;
        Logy.d(TAG, "Device connected, discovering services...");
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
        mConnectionState = ConnectionState.DISCONNECTING;
        mWaitToken.drainPermits();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionState = ConnectionState.DISCONNECTED;
    } else {
        throw new RuntimeException("Unknown connection state");
    }
    Logy.d(TAG, "status:" + status + ", newState:" + mConnectionState.name());
    for (ConnectionListener listener : mConnectionListeners)
        listener.onConnectionStateChanged(this, mConnectionState);
    super.onConnectionStateChange(gatt, status, newState);
}
 
Example 10
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 5 votes vote down vote up
/**
 * Cancel an active or pending connection.
 * <p>
 * This operation is asynchronous and you will receive a callback on onDisconnectedPeripheral.
 */
public void cancelConnection() {
    // Check if we have a Gatt object
    if (bluetoothGatt == null) {
        return;
    }

    // Check if we are not already disconnected or disconnecting
    if (state == BluetoothProfile.STATE_DISCONNECTED || state == BluetoothProfile.STATE_DISCONNECTING) {
        return;
    }

    // Cancel the connection timer
    cancelConnectionTimer();

    // Check if we are in the process of connecting
    if (state == BluetoothProfile.STATE_CONNECTING) {
        // Cancel the connection by calling disconnect
        disconnect();

        // Since we will not get a callback on onConnectionStateChange for this, we complete the disconnect ourselves
        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                completeDisconnect(true, GATT_SUCCESS);
            }
        }, 50);
    } else {
        // Cancel active connection
        disconnect();
    }
}
 
Example 11
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 5 votes vote down vote up
private String stateToString(final int state) {
    switch (state) {
        case BluetoothProfile.STATE_CONNECTED:
            return "CONNECTED";
        case BluetoothProfile.STATE_CONNECTING:
            return "CONNECTING";
        case BluetoothProfile.STATE_DISCONNECTING:
            return "DISCONNECTING";
        default:
            return "DISCONNECTED";
    }
}
 
Example 12
Source File: BleGattCallback.java    From attach with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (debug) {
        Log.v(TAG, "BLE gatt changed from status: " + status + " to status:" + newState);
    }
    switch (newState) {
        case BluetoothProfile.STATE_CONNECTED:
            if (debug) {
                Log.v(TAG, "STATE_CONNECTED");
            }
            setState(bluetoothDevice.getName(), "STATE_CONNECTED");
            gatt.discoverServices();
            break;
        case BluetoothProfile.STATE_DISCONNECTED:
            if (debug) {
                Log.v(TAG, "STATE_DISCONNECTED");
            }
            setState(bluetoothDevice.getName(), "STATE_DISCONNECTED");
            break;
        case BluetoothProfile.STATE_CONNECTING:
            if (debug) {
                Log.v(TAG, "STATE_CONNECTING");
            }
            setState(bluetoothDevice.getName(), "STATE_CONNECTING");
            break;
        case BluetoothProfile.STATE_DISCONNECTING:
            if (debug) {
                Log.v(TAG, "STATE_DISCONNECTING");
            }
            setState(bluetoothDevice.getName(), "STATE_DISCONNECTING");
            break;
        default:
            if (debug) {
                Log.v(TAG, "STATE_OTHER");
            }
            setState(bluetoothDevice.getName(), "STATE_OTHER");
    }
}
 
Example 13
Source File: ConnectionStateChangeLog.java    From EFRConnect-android with Apache License 2.0 5 votes vote down vote up
private String parseNewState(int newState) {
    switch (newState) {
        case BluetoothProfile.STATE_DISCONNECTED:
            return "State Disconnected";
        case BluetoothProfile.STATE_CONNECTING:
            return "State Connecting";
        case BluetoothProfile.STATE_CONNECTED:
            return "Successful connect to device";
        case BluetoothProfile.STATE_DISCONNECTING:
            return "State Disconnecting";
        default:
            return String.valueOf(newState);
    }
}
 
Example 14
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 5 votes vote down vote up
private void connectionStateChangeUnsuccessful(int status, int previousState, int newState, long timePassed) {
    // Check if service discovery completed
    if (discoverServicesRunnable != null) {
        // Service discovery is still pending so cancel it
        mainHandler.removeCallbacks(discoverServicesRunnable);
        discoverServicesRunnable = null;
    }
    boolean servicesDiscovered = !getServices().isEmpty();

    // See if the initial connection failed
    if (previousState == BluetoothProfile.STATE_CONNECTING) {
        boolean isTimeout = timePassed > getTimoutThreshold();
        Timber.i("connection failed with status '%s' (%s)", statusToString(status), isTimeout ? "TIMEOUT" : "ERROR");
        final int adjustedStatus = (status == GATT_ERROR && isTimeout) ? GATT_CONN_TIMEOUT : status;
        completeDisconnect(false, adjustedStatus);
        if (listener != null) {
            listener.connectFailed(BluetoothPeripheral.this, adjustedStatus);
        }
    } else if (previousState == BluetoothProfile.STATE_CONNECTED && newState == BluetoothProfile.STATE_DISCONNECTED && !servicesDiscovered) {
        // We got a disconnection before the services were even discovered
        Timber.i("peripheral '%s' disconnected with status '%s' before completing service discovery", getName(), statusToString(status));
        completeDisconnect(false, status);
        if (listener != null) {
            listener.connectFailed(BluetoothPeripheral.this, status);
        }
    } else {
        // See if we got connection drop
        if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            Timber.i("peripheral '%s' disconnected with status '%s'", getName(), statusToString(status));
        } else {
            Timber.i("unexpected connection state change for '%s' status '%s'", getName(), statusToString(status));
        }
        completeDisconnect(true, status);
    }
}
 
Example 15
Source File: SerialInterface_BLE.java    From PodEmu with GNU General Public License v3.0 5 votes vote down vote up
@Override
@TargetApi(21)
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
    PodEmuLog.debug("SIBLE: GATT onConnectionStateChange");
    switch (newState)
    {
        case BluetoothProfile.STATE_CONNECTED:
            setState(STATE_CONNECTED);
            gatt.discoverServices();
            synchronized (SerialInterface_BLE.this)
            {
                SerialInterface_BLE.this.notifyAll();
            }
            break;
        case BluetoothProfile.STATE_CONNECTING:
            setState(STATE_CONNECTING);
            break;
        case BluetoothProfile.STATE_DISCONNECTING:
            setState(STATE_LOST);
            break;
        case BluetoothProfile.STATE_DISCONNECTED:
            setState(STATE_NONE);
            break;
    }
    //PodEmuService.communicateSerialStatusChange();
}
 
Example 16
Source File: StatusPresenter.java    From thunderboard-android with Apache License 2.0 5 votes vote down vote up
private Subscriber<StatusEvent> onStatusEvent() {
    return new Subscriber<StatusEvent>() {
        @Override
        public void onCompleted() {
            Timber.d("completed");
        }

        @Override
        public void onError(Throwable e) {
            Timber.d("error: %s", e.getMessage());
        }

        @Override
        public void onNext(StatusEvent event) {

            device = event.device;
            int deviceState = device.getState();
            Timber.d("device: %s, state: %d", device.getName(), deviceState);

            if (BluetoothProfile.STATE_DISCONNECTED == deviceState) {
                // we are done, notify the UI
                connectivityHeartbeatTimer.cancel();
                if(isConnectivityLost) {
                    isConnectivityLost = false;
                    viewListener.onData(device);
                }
            } else if (BluetoothProfile.STATE_CONNECTED == deviceState && Boolean.TRUE.equals(device.isServicesDiscovered)) {
                // good stuff, we have a status event and the services
                isConnectivityLost = false;
                viewListener.onData(device);
            } else if (BluetoothProfile.STATE_CONNECTING == deviceState) {
                viewListener.onData(device);
            }
        }
    };
}
 
Example 17
Source File: BleManager.java    From Bluefruit_LE_Connect_Android with MIT License 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

    // Log.d(TAG, "onConnectionStateChange status: "+status+ " newState: "+newState);

    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mConnectionState = STATE_CONNECTED;

        if (mBleListener != null) {
            mBleListener.onConnected();
        }

        // Attempts to discover services after successful connection.
        gatt.discoverServices();

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionState = STATE_DISCONNECTED;

        if (mBleListener != null) {
            mBleListener.onDisconnected();
        }
    } else if (newState == BluetoothProfile.STATE_CONNECTING) {
        mConnectionState = STATE_CONNECTING;

        if (mBleListener != null) {
            mBleListener.onConnecting();
        }
    }
}
 
Example 18
Source File: DeviceActivity.java    From BLERW with Apache License 2.0 4 votes vote down vote up
private void init() {
	// BLE check
	if (!BleUtil.isBLESupported(this)) {
		Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT)
				.show();
		finish();
		return;
	}

	// BT check
	BluetoothManager manager = BleUtil.getManager(this);
	if (manager != null) {
		mBTAdapter = manager.getAdapter();
	}
	if (mBTAdapter == null) {
		Toast.makeText(this, R.string.bt_unavailable, Toast.LENGTH_SHORT)
				.show();
		finish();
		return;
	}

	// check BluetoothDevice
	if (mDevice == null) {
		mDevice = getBTDeviceExtra();
		if (mDevice == null) {
			finish();
			return;
		}
	}

	// button disable
	mReadManufacturerNameButton.setEnabled(false);
	mReadSerialNumberButton.setEnabled(false);
	mWriteAlertLevelButton.setEnabled(false);

	// connect to Gatt
	if ((mConnGatt == null)
			&& (mStatus == BluetoothProfile.STATE_DISCONNECTED)) {
		// try to connect
		mConnGatt = mDevice.connectGatt(this, false, mGattcallback);
		mStatus = BluetoothProfile.STATE_CONNECTING;
	} else {
		if (mConnGatt != null) {
			// re-connect and re-discover Services
			mConnGatt.connect();
			mConnGatt.discoverServices();
		} else {
			Log.e(TAG, "state error");
			finish();
			return;
		}
	}
	setProgressBarIndeterminateVisibility(true);
}
 
Example 19
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 4 votes vote down vote up
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
    long timePassed = SystemClock.elapsedRealtime() - connectTimestamp;
    cancelConnectionTimer();
    final int previousState = state;
    state = newState;

    if (status == GATT_SUCCESS) {
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTED:
                successfullyConnected(device.getBondState(), timePassed);
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                successfullyDisconnected(previousState);
                break;
            case BluetoothProfile.STATE_DISCONNECTING:
                Timber.i("peripheral is disconnecting");
                break;
            case BluetoothProfile.STATE_CONNECTING:
                Timber.i("peripheral is connecting");
            default:
                Timber.e("unknown state received");
                break;
        }
    } else {
        connectionStateChangeUnsuccessful(status, previousState, newState, timePassed);
    }
}
 
Example 20
Source File: BleService.java    From BleLib with Apache License 2.0 4 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (mOnConnectionStateChangeListener != null) {
        mOnConnectionStateChangeListener.onConnectionStateChange(gatt, status, newState);
    }
    String intentAction;
    String address = gatt.getDevice().getAddress();
    if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        Log.i(TAG, "onConnectionStateChange: DISCONNECTED: " + getConnectDevices().size());
        intentAction = ACTION_GATT_DISCONNECTED;
        isConnect = false;
        mConnState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction, address);
        close();
    } else if (newState == BluetoothProfile.STATE_CONNECTING) {
        Log.i(TAG, "onConnectionStateChange: CONNECTING: " + getConnectDevices().size());
        isConnect = false;
        intentAction = ACTION_GATT_CONNECTING;
        mConnState = STATE_CONNECTING;
        Log.i(TAG, "Connecting to GATT server.");
        broadcastUpdate(intentAction, address);
    } else if (newState == BluetoothProfile.STATE_CONNECTED) {
        Log.i(TAG, "onConnectionStateChange: CONNECTED: " + getConnectDevices().size());
        intentAction = ACTION_GATT_CONNECTED;
        isConnect = true;
        mConnState = STATE_CONNECTED;
        broadcastUpdate(intentAction, address);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());
    } else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
        Log.i(TAG, "onConnectionStateChange: DISCONNECTING: " + getConnectDevices().size());
        isConnect = false;
        intentAction = ACTION_GATT_DISCONNECTING;
        mConnState = STATE_DISCONNECTING;
        Log.i(TAG, "Disconnecting from GATT server.");
        broadcastUpdate(intentAction, address);
    }
}