com.welie.blessed.BluetoothPeripheral Java Examples

The following examples show how to use com.welie.blessed.BluetoothPeripheral. 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: BluetoothSenssun.java    From openScale with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onBluetoothDiscovery(BluetoothPeripheral peripheral) {

        if (peripheral.getService(MODEL_A_MEASUREMENT_SERVICE) != null) {
            writeService = MODEL_A_MEASUREMENT_SERVICE;
            writeCharacteristic = MODEL_A_WRITE_CHARACTERISTIC;
            setNotificationOn(MODEL_A_MEASUREMENT_SERVICE, MODEL_A_NOTIFICATION_CHARACTERISTIC);
            Timber.d("Found a Model A");
        }

        if (peripheral.getService(MODEL_B_MEASUREMENT_SERVICE) != null) {
            writeService = MODEL_B_MEASUREMENT_SERVICE;
            writeCharacteristic = MODEL_B_WRITE_CHARACTERISTIC;
            setNotificationOn(MODEL_B_MEASUREMENT_SERVICE, MODEL_B_NOTIFICATION_CHARACTERISTIC);
            Timber.d("Found a Model B");
        }
}
 
Example #2
Source File: BluetoothCommunication.java    From openScale with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Connect to a Bluetooth device.
 *
 * On successfully connection Bluetooth machine state is automatically triggered.
 * If the device is not found the process is automatically stopped.
 *
 * @param macAddress the Bluetooth address to connect to
 */
public void connect(String macAddress) {
    // Running an LE scan during connect improves connectivity on some phones
    // (e.g. Sony Xperia Z5 compact, Android 7.1.1). For some scales (e.g. Medisana BS444)
    // it seems to be a requirement that the scale is discovered before connecting to it.
    // Otherwise the connection almost never succeeds.
    LocationManager locationManager = (LocationManager)context.getSystemService(LOCATION_SERVICE);

    if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED && (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
    ) {
        Timber.d("Do LE scan before connecting to device");
        central.scanForPeripheralsWithAddresses(new String[]{macAddress});
        stopMachineState();
    }
    else {
        Timber.d("No location permission, connecting without LE scan");
        BluetoothPeripheral peripheral = central.getPeripheral(macAddress);
        connectToDevice(peripheral);
    }
}
 
Example #3
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 6 votes vote down vote up
public PBluetoothLEClient readFromCharacteristic(String macAddress, String serviceUUID, String charUUID) {
    BluetoothPeripheral peripheral = central.getPeripheral(macAddress);
    BluetoothGattCharacteristic btChar = peripheral.getCharacteristic(UUID.fromString(serviceUUID), UUID.fromString(charUUID));
    peripheral.readCharacteristic(btChar);
    peripheral.setNotify(btChar, true);
    return this;
}
 
Example #4
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothPeripheral peripheral) {
    MLog.i(TAG, "discovered service " + peripheral.getServices());

    /*
    peripheral.getServices().forEach(bluetoothGattService -> {
        MLog.d(TAG, "service: " + bluetoothGattService.getUuid());
        bluetoothGattService.getCharacteristics().forEach(bluetoothGattCharacteristic -> {
            MLog.d(TAG, "\t c: " + bluetoothGattCharacteristic.getUuid());
        });
    });

    // Request a new connection priority
    peripheral.requestConnectionPriority(CONNECTION_PRIORITY_HIGH);

    // Read manufacturer and model number from the Device Information Service
    if (peripheral.getService(T1_SERVICE_UUID) != null) {
        MLog.d(TAG, "reading...");
        BluetoothGattCharacteristic characteristic = peripheral.getCharacteristic(T1_SERVICE_UUID, T1_CHARACTERISTIC_UUID);
        peripheral.readCharacteristic(characteristic);
        peripheral.setNotify(characteristic, true);
        // peripheral.readCharacteristic(peripheral.getCharacteristic(DIS_SERVICE_UUID, MODEL_NUMBER_CHARACTERISTIC_UUID));
    }
     */
}
 
Example #5
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, int status) {
    if (status == GATT_SUCCESS) {
        if(peripheral.isNotifying(characteristic)) {
            MLog.d(TAG, "SUCCESS: Notify set to 'on' for %s " + characteristic.getUuid());
        } else {
            MLog.d(TAG, "SUCCESS: Notify set to 'off' for %s " + characteristic.getUuid());
        }
    } else {
        MLog.d(TAG, "ERROR: Changing notification state failed for %s" + characteristic.getUuid());
    }
}
 
Example #6
Source File: BluetoothCommunication.java    From openScale with GNU General Public License v3.0 5 votes vote down vote up
private void connectToDevice(BluetoothPeripheral peripheral) {

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Timber.d("Try to connect to BLE device " + peripheral.getAddress());

                stepNr = 0;

                central.connectPeripheral(peripheral, peripheralCallback);
            }
        }, 1000);
    }
 
Example #7
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {
    MLog.d(TAG, "Found peripheral " + peripheral.getName() + " " + peripheral.getAddress());

    if (peripheral.getAddress().equals(T1_MAC_ADDRESS)) {
        MLog.d(TAG, "found mac");
        central.connectPeripheral(peripheral, peripheralCallback);
        central.stopScan();
    }

}
 
Example #8
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onDisconnectedPeripheral(final BluetoothPeripheral peripheral, final int status) {
    MLog.d(TAG, "disconnected '%s' with status %d" + " " + peripheral.getName() + " " + status);

    // Reconnect to this device when it becomes available again
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            central.autoConnectPeripheral(peripheral, peripheralCallback);
        }
    }, 5000);
}
 
Example #9
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onConnectedPeripheral(BluetoothPeripheral peripheral) {
    MLog.d(TAG, "connected to '%s' " + peripheral.getName());
    ReturnObject ret = new ReturnObject();
    ret.put("deviceMac", peripheral.getAddress());
    ret.put("deviceName", peripheral.getAddress());
    ret.put("status", "connected");
    mHandler.post(() -> {
        if (mCallbackDevice != null) mCallbackDevice.event(ret);
    });
}
 
Example #10
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, int status) {
    MLog.d(TAG, "onCharWrite");

    /*
    if( status == GATT_SUCCESS) {
        MLog.d(TAG, "SUCCESS: Writing <%s> to <%s>", bytes2String(value), characteristic.getUuid().toString());
    } else {
        MLog.d(TAG, "ERROR: Failed writing <%s> to <%s>", bytes2String(value), characteristic.getUuid().toString());
    }
     */
}
 
Example #11
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
public PBluetoothLEClient write(String value, String macAddress, String serviceUUID, String charUUID) {
    BluetoothPeripheral peripheral = central.getPeripheral(macAddress);
    UUID sUUID = UUID.fromString(serviceUUID);
    MLog.d(TAG, "qq1->");
    UUID cUUID = UUID.fromString(charUUID);
    MLog.d(TAG, "qq2->");
    BluetoothGattCharacteristic btChar = peripheral.getCharacteristic(sUUID, cUUID);
    // peripheral.writeCharacteristic(btChar, value, type);
    peripheral.writeCharacteristic(btChar, value.getBytes(), WRITE_TYPE_DEFAULT);


    return this;
}
 
Example #12
Source File: BluetoothHandler.java    From blessed-android with MIT License 5 votes vote down vote up
@Override
public void onDisconnectedPeripheral(final BluetoothPeripheral peripheral, final int status) {
    Timber.i("disconnected '%s' with status %d", peripheral.getName(), status);

    // Reconnect to this device when it becomes available again
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            central.autoConnectPeripheral(peripheral, peripheralCallback);
        }
    }, 5000);
}
 
Example #13
Source File: BluetoothHandler.java    From blessed-android with MIT License 5 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, int status) {
    if( status == GATT_SUCCESS) {
        Timber.i("SUCCESS: Writing <%s> to <%s>", bytes2String(value), characteristic.getUuid().toString());
    } else {
        Timber.i("ERROR: Failed writing <%s> to <%s>", bytes2String(value), characteristic.getUuid().toString());
    }
}
 
Example #14
Source File: BluetoothHandler.java    From blessed-android with MIT License 5 votes vote down vote up
@Override
public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, int status) {
    if( status == GATT_SUCCESS) {
        if(peripheral.isNotifying(characteristic)) {
            Timber.i("SUCCESS: Notify set to 'on' for %s", characteristic.getUuid());
        } else {
            Timber.i("SUCCESS: Notify set to 'off' for %s", characteristic.getUuid());
        }
    } else {
        Timber.e("ERROR: Changing notification state failed for %s", characteristic.getUuid());
    }
}
 
Example #15
Source File: BluetoothHandler.java    From blessed-android with MIT License 4 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothPeripheral peripheral) {
    Timber.i("discovered services");

    // Request a new connection priority
    peripheral.requestConnectionPriority(CONNECTION_PRIORITY_HIGH);

    // Read manufacturer and model number from the Device Information Service
    if(peripheral.getService(DIS_SERVICE_UUID) != null) {
        peripheral.readCharacteristic(peripheral.getCharacteristic(DIS_SERVICE_UUID, MANUFACTURER_NAME_CHARACTERISTIC_UUID));
        peripheral.readCharacteristic(peripheral.getCharacteristic(DIS_SERVICE_UUID, MODEL_NUMBER_CHARACTERISTIC_UUID));
    }

    // Turn on notifications for Current Time Service
    if(peripheral.getService(CTS_SERVICE_UUID) != null) {
        BluetoothGattCharacteristic currentTimeCharacteristic = peripheral.getCharacteristic(CTS_SERVICE_UUID, CURRENT_TIME_CHARACTERISTIC_UUID);
        peripheral.setNotify(currentTimeCharacteristic, true);

        // If it has the write property we write the current time
        if((currentTimeCharacteristic.getProperties() & PROPERTY_WRITE) > 0) {
            // Write the current time unless it is an Omron device
            if(!(peripheral.getName().contains("BLEsmart_"))) {
                BluetoothBytesParser parser = new BluetoothBytesParser();
                parser.setCurrentTime(Calendar.getInstance());
                peripheral.writeCharacteristic(currentTimeCharacteristic, parser.getValue(), WRITE_TYPE_DEFAULT);
            }
        }
    }

    // Turn on notifications for Battery Service
    if(peripheral.getService(BTS_SERVICE_UUID) != null) {
        peripheral.setNotify(peripheral.getCharacteristic(BTS_SERVICE_UUID, BATTERY_LEVEL_CHARACTERISTIC_UUID), true);
    }

    // Turn on notifications for Blood Pressure Service
    if(peripheral.getService(BLP_SERVICE_UUID) != null) {
        peripheral.setNotify(peripheral.getCharacteristic(BLP_SERVICE_UUID, BLOOD_PRESSURE_MEASUREMENT_CHARACTERISTIC_UUID), true);
    }

    // Turn on notification for Health Thermometer Service
    if(peripheral.getService(HTS_SERVICE_UUID) != null) {
        peripheral.setNotify(peripheral.getCharacteristic(HTS_SERVICE_UUID, TEMPERATURE_MEASUREMENT_CHARACTERISTIC_UUID), true);
    }

    // Turn on notification for Heart Rate  Service
    if(peripheral.getService(HRS_SERVICE_UUID) != null) {
        peripheral.setNotify(peripheral.getCharacteristic(HRS_SERVICE_UUID, HEARTRATE_MEASUREMENT_CHARACTERISTIC_UUID), true);
    }
}
 
Example #16
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 4 votes vote down vote up
public PBluetoothLEClient connectDevice(String macAddress) {
    BluetoothPeripheral peripheral = central.getPeripheral(macAddress);
    peripheral.requestConnectionPriority(CONNECTION_PRIORITY_HIGH);
    central.connectPeripheral(peripheral, peripheralCallback);
    return this;
}
 
Example #17
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, int status) {
    // MLog.d(TAG, "onCharacteristicUpdate");

    if (status != GATT_SUCCESS) return;
    ReturnObject ret = new ReturnObject();
    ret.put("deviceMac", peripheral.getAddress());
    ret.put("deviceName", peripheral.getName());
    ret.put("serviceUUID", characteristic.getService().getUuid());
    ret.put("characteristicUUID", characteristic.getUuid());
    ret.put("value", value);

    mHandler.post(() -> {
        if (mCallbackCharacteristic != null) mCallbackCharacteristic.event(ret);
    });

    /*
    if (characteristicUUID.equals(BLOOD_PRESSURE_MEASUREMENT_CHARACTERISTIC_UUID)) {
        BloodPressureMeasurement measurement = new BloodPressureMeasurement(value);
        Intent intent = new Intent("BluetoothMeasurement");
        intent.putExtra("BloodPressure", measurement);
        context.sendBroadcast(intent);
        Timber.d("%s", measurement);
    }
    else if(characteristicUUID.equals(TEMPERATURE_MEASUREMENT_CHARACTERISTIC_UUID)) {
        TemperatureMeasurement measurement = new TemperatureMeasurement(value);
        Intent intent = new Intent("TemperatureMeasurement");
        intent.putExtra("Temperature", measurement);
        context.sendBroadcast(intent);
        Timber.d("%s", measurement);
    }
    else if(characteristicUUID.equals(HEARTRATE_MEASUREMENT_CHARACTERISTIC_UUID)) {
        HeartRateMeasurement measurement = new HeartRateMeasurement(value);
        Intent intent = new Intent("HeartRateMeasurement");
        intent.putExtra("HeartRate", measurement);
        context.sendBroadcast(intent);
        Timber.d("%s", measurement);
    }
    else if(characteristicUUID.equals(CURRENT_TIME_CHARACTERISTIC_UUID)) {
        Date currentTime = parser.getDateTime();
        MLog.d(TAG, "Received device time: %s", currentTime);

        // Deal with Omron devices where we can only write currentTime under specific conditions
        if(peripheral.getName().contains("BLEsmart_")) {
            boolean isNotifying = peripheral.isNotifying(peripheral.getCharacteristic(BLP_SERVICE_UUID, BLOOD_PRESSURE_MEASUREMENT_CHARACTERISTIC_UUID));
            if(isNotifying) currentTimeCounter++;

            // We can set device time for Omron devices only if it is the first notification and currentTime is more than 10 min from now
            long interval = abs(Calendar.getInstance().getTimeInMillis() - currentTime.getTime());
            if (currentTimeCounter == 1 && interval > 10*60*1000) {
                parser.setCurrentTime(Calendar.getInstance());6E400001-B5A3-F393-E0A9-E50E24DCCA9E
                peripheral.writeCharacteristic(characteristic, parser.getValue(), WRITE_TYPE_DEFAULT);
            }
        }
    }
    else if(characteristicUUID.equals(BATTERY_LEVEL_CHARACTERISTIC_UUID)) {
        int batteryLevel = parser.getIntValue(FORMAT_UINT8);
        MLog.d(TAG, "Received battery level %d%%", batteryLevel);
    }
    else if(characteristicUUID.equals(MANUFACTURER_NAME_CHARACTERISTIC_UUID)) {
        String manufacturer = parser.getStringValue(0);
        MLog.d(TAG, "Received manufacturer: %s", manufacturer);
    }
    else if(characteristicUUID.equals(MODEL_NUMBER_CHARACTERISTIC_UUID)) {
        String modelNumber = parser.getStringValue(0);
        MLog.d(TAG, "Received modelnumber: %s", modelNumber);
    }

     */
}
 
Example #18
Source File: BluetoothHandler.java    From blessed-android with MIT License 4 votes vote down vote up
@Override
public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {
    Timber.i("Found peripheral '%s'", peripheral.getName());
    central.stopScan();
    central.connectPeripheral(peripheral, peripheralCallback);
}
 
Example #19
Source File: PBluetoothLEClient.java    From PHONK with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onConnectionFailed(BluetoothPeripheral peripheral, final int status) {
    MLog.e(TAG, "connection '%s' failed with status %d " + peripheral.getName() + " " + status);
}
 
Example #20
Source File: BluetoothHandler.java    From blessed-android with MIT License 4 votes vote down vote up
@Override
public void onConnectionFailed(BluetoothPeripheral peripheral, final int status) {
    Timber.e("connection '%s' failed with status %d", peripheral.getName(), status);
}
 
Example #21
Source File: BluetoothSettingsFragment.java    From openScale with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {
    onDeviceFound(scanResult);
}
 
Example #22
Source File: BluetoothHandler.java    From blessed-android with MIT License 4 votes vote down vote up
@Override
public void onConnectedPeripheral(BluetoothPeripheral peripheral) {
    Timber.i("connected to '%s'", peripheral.getName());
}
 
Example #23
Source File: BluetoothCommunication.java    From openScale with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Method is triggered if a Bluetooth services from a device is discovered.
 *
 * @param peripheral
 */
protected void onBluetoothDiscovery(BluetoothPeripheral peripheral) { }