Java Code Examples for com.eveningoutpost.dexdrip.Models.ActiveBluetoothDevice#first()

The following examples show how to use com.eveningoutpost.dexdrip.Models.ActiveBluetoothDevice#first() . 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: SystemStatus.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private void set_current_values() {
    activeBluetoothDevice = ActiveBluetoothDevice.first();
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    setVersionName();
    setCollectionMethod();
    setCurrentDevice();
    if (Home.get_follower()) {
        setConnectionStatusFollower();
    } else if (prefs.getString("dex_collection_method", "bogus").equals("WifiWixel")) {
        setConnectionStatusWifiWixel();
    } else {
        setConnectionStatus();
    }
    setSensorStatus();
    setTransmitterStatus();
    setNotes();
    futureDataCheck();
}
 
Example 2
Source File: WatchUpdaterService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private void sendActiveBtDeviceData() {//KS
    if (is_using_bt) {//only required for Collector running on watch
        forceGoogleApiConnect();
        ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
        if (btDevice != null) {
            if (wear_integration) {
                DataMap dataMap = new DataMap();
                Log.d(TAG, "sendActiveBtDeviceData name=" + btDevice.name + " address=" + btDevice.address + " connected=" + btDevice.connected);

                dataMap.putLong("time", new Date().getTime()); // MOST IMPORTANT LINE FOR TIMESTAMP

                dataMap.putString("name", btDevice.name);
                dataMap.putString("address", btDevice.address);
                dataMap.putBoolean("connected", btDevice.connected);

                new SendToDataLayerThread(WEARABLE_ACTIVEBTDEVICE_DATA_PATH, googleApiClient).executeOnExecutor(xdrip.executor, dataMap);
            }
        }
    } else {
        Log.d(TAG, "Not sending activebluetoothdevice data as we are not using bt");
    }
}
 
Example 3
Source File: Blukon.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static boolean expectingBlukonDevice() {
    try {
        final ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
        if (btDevice.name.startsWith("BLU")) return true;
    } catch (Exception e) {
        //
    }
    return false;
}
 
Example 4
Source File: Blukon.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static boolean expectingBlukonDevice() {
    try {
        final ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
        if (btDevice.name.startsWith("BLU")) return true;
    } catch (Exception e) {
        //
    }
    return false;
}
 
Example 5
Source File: Blukon.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static void unBondIfBlukonAtInit() {
    try {
        if (Blukon.expectingBlukonDevice() && Pref.getBooleanDefaultFalse("blukon_unbonding")) {
            final ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
            if (btDevice != null) {
                UserError.Log.d(TAG, "Unbonding blukon at initialization");
                JoH.unBond(btDevice.address);
            }
        }
    } catch (Exception e) {
        UserError.Log.e(TAG, "Got exception trying to unbond blukon at init");
    }
}
 
Example 6
Source File: DexCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public void attemptConnection() {
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (mBluetoothManager != null) {
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter != null) {
            if (device != null) {
                mConnectionState = STATE_DISCONNECTED;
                for (BluetoothDevice bluetoothDevice : mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
                    if (bluetoothDevice.getAddress().compareTo(device.getAddress()) == 0) {
                        mConnectionState = STATE_CONNECTED;
                    }
                }
            }

            Log.w(TAG, "Connection state: " + mConnectionState);
            if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
                ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
                if (btDevice != null) {
                    mDeviceName = btDevice.name;
                    mDeviceAddress = btDevice.address;
                    if (mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getRemoteDevice(mDeviceAddress) != null) {
                        connect(mDeviceAddress);
                        return;
                    }
                }
            } else if (mConnectionState == STATE_CONNECTED) { //WOOO, we are good to go, nothing to do here!
                Log.w(TAG, "Looks like we are already connected, going to read!");
                return;
            }
        }
    }
    setRetryTimer();
}
 
Example 7
Source File: Amazfitservice.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public String getCurrentDevice() {
    activeBluetoothDevice = ActiveBluetoothDevice.first();
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    String currentdevice;
    if (activeBluetoothDevice != null) {
        currentdevice = activeBluetoothDevice.name;
    } else {
        currentdevice = "None Set";
    }

    String collection_method = prefs.getString("dex_collection_method", "BluetoothWixel");
    if (collection_method.compareTo("DexcomG5") == 0) {
        Transmitter defaultTransmitter = new Transmitter(prefs.getString("dex_txid", "ABCDEF"));
        if (Build.VERSION.SDK_INT >= 18) {
            mBluetoothAdapter = mBluetoothManager.getAdapter();
        }
        if (mBluetoothAdapter != null) {
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if ((pairedDevices != null) && (pairedDevices.size() > 0)) {
                for (BluetoothDevice device : pairedDevices) {
                    if (device.getName() != null) {

                        String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                        String deviceNameLastTwo = Extensions.lastTwoCharactersOfString(device.getName());

                        if (transmitterIdLastTwo.equals(deviceNameLastTwo)) {
                            currentdevice = defaultTransmitter.transmitterId;
                        }

                    }
                }
            }
        } else {
            currentdevice = "No Bluetooth";
        }
    }
    return currentdevice;
}
 
Example 8
Source File: Home.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
private void updateCurrentBgInfoForBtShare(TextView notificationText) {
    if ((android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)) {
        notificationText.setText("Unfortunately your android version does not support Bluetooth Low Energy");
        return;
    }

    String receiverSn = mPreferences.getString("share_key", "SM00000000").toUpperCase();
    if (receiverSn.compareTo("SM00000000") == 0 || receiverSn.length() == 0) {
        notificationText.setText("Please set your Dex Receiver Serial Number in App Settings");
        return;
    }

    if (receiverSn.length() < 10) {
        notificationText.setText("Double Check Dex Receiver Serial Number, should be 10 characters, don't forget the letters");
        return;
    }

    if (ActiveBluetoothDevice.first() == null) {
        notificationText.setText("Now pair with your Dexcom Share");
        return;
    }

    if (!Sensor.isActive()) {
        notificationText.setText("Now choose start your sensor in your settings");
        return;
    }

    displayCurrentInfo();
}
 
Example 9
Source File: Home.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private void updateCurrentBgInfoForBtBasedWixel(DexCollectionType collector, TextView notificationText) {
    if ((android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)) {
        notificationText.setText(R.string.unfortunately_andoird_version_no_blueooth_low_energy);
        return;
    }

    if (ActiveBluetoothDevice.first() == null) {
        notificationText.setText(R.string.first_use_menu_to_scan);
        return;
    }
    updateCurrentBgInfoCommon(collector, notificationText);
}
 
Example 10
Source File: Home.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private void updateCurrentBgInfoForBtShare(TextView notificationText) {
    if ((android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)) {
        notificationText.setText(R.string.unfortunately_andoird_version_no_blueooth_low_energy);
        return;
    }

    String receiverSn = Pref.getString("share_key", "SM00000000").toUpperCase();
    if (receiverSn.compareTo("SM00000000") == 0 || receiverSn.length() == 0) {
        notificationText.setText(R.string.please_set_dex_receiver_serial_number);
        return;
    }

    if (receiverSn.length() < 10) {
        notificationText.setText(R.string.double_check_dex_receiver_serial_number);
        return;
    }

    if (ActiveBluetoothDevice.first() == null) {
        notificationText.setText(R.string.now_pair_with_your_dexcom_share);
        return;
    }

    if (!Sensor.isActive()) {
        notificationText.setText(R.string.now_choose_start_sensor_in_settings);
        return;
    }

    displayCurrentInfo();
}
 
Example 11
Source File: Home.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private void updateCurrentBgInfoForBtShare(TextView notificationText) {
    if ((android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)) {
        notificationText.setText(R.string.unfortunately_andoird_version_no_blueooth_low_energy);
        return;
    }

    String receiverSn = Pref.getString("share_key", "SM00000000").toUpperCase();
    if (receiverSn.compareTo("SM00000000") == 0 || receiverSn.length() == 0) {
        notificationText.setText(R.string.please_set_dex_receiver_serial_number);
        return;
    }

    if (receiverSn.length() < 10) {
        notificationText.setText(R.string.double_check_dex_receiver_serial_number);
        return;
    }

    if (ActiveBluetoothDevice.first() == null) {
        notificationText.setText(R.string.now_pair_with_your_dexcom_share);
        return;
    }

    if (!Sensor.isActive()) {
        notificationText.setText(R.string.now_choose_start_sensor_in_settings);
        return;
    }

    displayCurrentInfo();
}
 
Example 12
Source File: DexCollectionService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
synchronized void checkConnection() {
    status("Attempting connection");
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager == null) {
        status("No bluetooth manager");
        setRetryTimer();
        return;
    }

    mBluetoothAdapter = bluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        status("No bluetooth adapter");
        setRetryTimer();
        return;
    }

    if (!mBluetoothAdapter.isEnabled()) {
        mConnectionState = STATE_DISCONNECTED; // can't be connected if BT is disabled
        if (Pref.getBoolean("automatically_turn_bluetooth_on", true)) {
            Log.i(TAG, "Turning bluetooth on as appears disabled");
            status("Turning bluetooth on");
            JoH.setBluetoothEnabled(getApplicationContext(), true);
        } else {
            Log.d(TAG, "Not automatically turning on bluetooth due to preferences");
        }
    }

    if (device != null) {
        boolean found = false;
        for (BluetoothDevice bluetoothDevice : bluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
            if (bluetoothDevice.getAddress().equals(device.getAddress())) {
                found = true;
                if (mConnectionState != STATE_CONNECTED) {
                    UserError.Log.d(TAG, "Detected state change by checking connected devices");
                    handleConnectedStateChange();
                }
                break;
            }
        }
        if (!found) {
            if (mConnectionState == STATE_CONNECTED) {
                UserError.Log.d(TAG, "Marking disconnected as not in list of connected devices");
                mConnectionState = STATE_DISCONNECTED; // not in connected list so should be disconnected we think
            }

        }
    } else {
        UserError.Log.d(TAG, "Device is null in checkConnection");
        mConnectionState = STATE_DISCONNECTED; // can't be connected if we don't know the device
    }

    Log.i(TAG, "checkConnection: Connection state: " + getStateStr(mConnectionState));
    if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
        final ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
        if (btDevice != null) {
            final String deviceAddress = btDevice.address;
            mDeviceAddress = deviceAddress;
            try {
                if (mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getRemoteDevice(deviceAddress) != null) {
                    if (useScanning()) {
                        status(gs(R.string.scanning) + (Home.get_engineering_mode() ? ": " + deviceAddress : ""));
                        scanMeister.setAddress(deviceAddress).addCallBack(this, TAG).scan();
                    } else {
                        status("Connecting" + (Home.get_engineering_mode() ? ": " + deviceAddress : ""));
                        connect(deviceAddress);
                    }
                    mStaticState = mConnectionState;
                    return;
                }
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "IllegalArgumentException: " + e);
            }
        }
    } else if (mConnectionState == STATE_CONNECTING) {
        mStaticState = mConnectionState;
        if (JoH.msSince(last_connect_request) > (getTrustAutoConnect() ? Constants.SECOND_IN_MS * 3600 : Constants.SECOND_IN_MS * 30)) {
            Log.i(TAG, "Connecting for too long, shutting down");
            retry_backoff = 0;
            close();
        }
    } else if (mConnectionState == STATE_CONNECTED) { //WOOO, we are good to go, nothing to do here!
        status("Last Connected");
        Log.i(TAG, "checkConnection: Looks like we are already connected, ready to receive");
        retry_backoff = 0;
        mStaticState = mConnectionState;
        if (use_polling && (JoH.msSince(lastPacketTime) >= POLLING_PERIOD)) {
            pollForData();
        }

        return;
    }
    setRetryTimer();
}
 
Example 13
Source File: DexShareCollectionService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public void attemptConnection() {
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (mBluetoothManager != null) {
        if (device != null) {
            mConnectionState = STATE_DISCONNECTED;
            for (BluetoothDevice bluetoothDevice : mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
                if (bluetoothDevice.getAddress().compareTo(device.getAddress()) == 0) {
                    mConnectionState = STATE_CONNECTED;
                }
            }
        }
        Log.i(TAG, "Connection state: " + mConnectionState);
        if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
            ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
            if (btDevice != null) {
                mDeviceName = btDevice.name;
                mDeviceAddress = btDevice.address;
                mBluetoothAdapter = mBluetoothManager.getAdapter();
                try {
                    if (mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getRemoteDevice(mDeviceAddress) != null) {
                        connect(mDeviceAddress);
                        return;
                    } else {
                        Log.w(TAG, "Bluetooth is disabled or BT device cant be found");
                        setRetryTimer();
                        return;
                    }
                } catch (IllegalArgumentException e) {
                    if (JoH.ratelimit("dex-share-error-log", 180)) {
                        Log.wtf(TAG, "Error connecting: " + e);
                    }
                }
            } else {
                Log.w(TAG, "No bluetooth device to try and connect to");
                setRetryTimer();
                return;
            }
        } else if (mConnectionState == STATE_CONNECTED) {
            Log.i(TAG, "Looks like we are already connected, going to read!");
            attemptRead();
            return;
        } else {
            setRetryTimer();
            return;
        }
    } else {
        setRetryTimer();
        return;
    }
}
 
Example 14
Source File: ListenerService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private void sendCollectorStatus (Context context, String path) {
    String msg;
    //long last_timestamp = 0;
    DataMap dataMap = new DataMap();
    switch (DexCollectionType.getDexCollectionType()) {
        case DexcomG5:

            if (DexCollectionType.getCollectorServiceClass() == G5CollectionService.class) {
                dataMap = G5CollectionService.getWatchStatus();//msg, last_timestamp
            } else {
                dataMap = Ob1G5CollectionService.getWatchStatus();//msg, last_timestamp
            }
            break;
        case DexcomShare://TODO getLastState() in non-G5 Services
            BluetoothManager mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            ActiveBluetoothDevice activeBluetoothDevice = ActiveBluetoothDevice.first();
            boolean connected = false;
            if (mBluetoothManager != null && activeBluetoothDevice != null) {
                for (BluetoothDevice bluetoothDevice : mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
                    if (bluetoothDevice.getAddress().compareTo(activeBluetoothDevice.address) == 0) {
                        connected = true;
                    }
                }
            }
            if (connected) {
                msg = "Connected on watch";
            } else {
                msg = "Not Connected";
            }
            dataMap.putString("lastState", msg);
            break;
        default:
            dataMap = DexCollectionService.getWatchStatus();
            break;
    }
    if (dataMap != null) {
        dataMap.putString("action_path", path);
    }

    //sendReplyMsg (msg, last_timestamp, path, false);
    sendData(WEARABLE_REPLYMSG_PATH, dataMap.toByteArray());
}
 
Example 15
Source File: MedtrumCollectionService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    xdrip.checkAppContext(getApplicationContext());
    if (shouldServiceRun()) {
        final PowerManager.WakeLock wl = JoH.getWakeLock("medtrum-start-service", 600000);
        try {
            UserError.Log.d(TAG, "WAKE UP WAKE UP WAKE UP WAKE UP @ " + JoH.dateTimeText(JoH.tsl()) + " State: " + state);
            setFailOverTimer();

            if (wakeup_time > 0) {
                wakeup_jitter = JoH.msSince(wakeup_time);
                if (wakeup_jitter < 0) {
                    UserError.Log.d(TAG, "Woke up Early..");
                } else {
                    if (wakeup_jitter > 1000) {
                        UserError.Log.d(TAG, "Wake up, time jitter: " + JoH.niceTimeScalar(wakeup_jitter));
                        if ((wakeup_jitter > TOLERABLE_JITTER) && (!JoH.buggy_samsung) && JoH.isSamsung()) {
                            UserError.Log.wtf(TAG, "Enabled Buggy Samsung workaround due to jitter of: " + JoH.niceTimeScalar(wakeup_jitter));
                            JoH.buggy_samsung = true;
                            PersistentStore.incrementLong(BUGGY_SAMSUNG_ENABLED);
                            max_wakeup_jitter = 0;
                        } else {
                            max_wakeup_jitter = Math.max(max_wakeup_jitter, wakeup_jitter);
                        }

                    }
                }
                wakeup_time = 0; // don't check this one again
            }


            retry_time = 0; // we have woken up
            last_wake_up_time = JoH.tsl();
            try {
                address = ActiveBluetoothDevice.first().address;
            } catch (NullPointerException e) {
                // bluetooth device not set - launch scan ui???
            }

            processInitialState();
            background_automata();

            if (intent != null) {

            }
        } finally {
            JoH.releaseWakeLock(wl);
        }
        return START_STICKY;
    } else {
        UserError.Log.d(TAG, "Should not be running so shutting down");
        stopSelf();
        return START_NOT_STICKY;
    }
}
 
Example 16
Source File: DexShareCollectionService.java    From xDrip-Experimental with GNU General Public License v3.0 4 votes vote down vote up
public void attemptConnection() {
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (mBluetoothManager != null) {
        if (device != null) {
            mConnectionState = STATE_DISCONNECTED;
            for (BluetoothDevice bluetoothDevice : mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
                if (bluetoothDevice.getAddress().compareTo(device.getAddress()) == 0) {
                    mConnectionState = STATE_CONNECTED;
                }
            }
        }
        Log.i(TAG, "Connection state: " + mConnectionState);
        if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
            ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
            if (btDevice != null) {
                mDeviceName = btDevice.name;
                mDeviceAddress = btDevice.address;
                mBluetoothAdapter = mBluetoothManager.getAdapter();
                if (mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getRemoteDevice(mDeviceAddress) != null) {
                    connect(mDeviceAddress);
                    return;
                } else {
                    Log.w(TAG, "Bluetooth is disabled or BT device cant be found");
                    setRetryTimer();
                    return;
                }
            } else {
                Log.w(TAG, "No bluetooth device to try and connect to");
                setRetryTimer();
                return;
            }
        } else if (mConnectionState == STATE_CONNECTED) {
            Log.i(TAG, "Looks like we are already connected, going to read!");
            attemptRead();
            return;
        } else {
            setRetryTimer();
            return;
        }
    } else {
        setRetryTimer();
        return;
    }
}
 
Example 17
Source File: MedtrumCollectionService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    xdrip.checkAppContext(getApplicationContext());
    if (shouldServiceRun()) {
        final PowerManager.WakeLock wl = JoH.getWakeLock("medtrum-start-service", 600000);
        try {
            UserError.Log.d(TAG, "WAKE UP WAKE UP WAKE UP WAKE UP @ " + JoH.dateTimeText(JoH.tsl()) + " State: " + state);
            setFailOverTimer();

            if (wakeup_time > 0) {
                wakeup_jitter = JoH.msSince(wakeup_time);
                if (wakeup_jitter < 0) {
                    UserError.Log.d(TAG, "Woke up Early..");
                } else {
                    if (wakeup_jitter > 1000) {
                        UserError.Log.d(TAG, "Wake up, time jitter: " + JoH.niceTimeScalar(wakeup_jitter));
                        if ((wakeup_jitter > TOLERABLE_JITTER) && (!JoH.buggy_samsung) && JoH.isSamsung()) {
                            UserError.Log.wtf(TAG, "Enabled Buggy Samsung workaround due to jitter of: " + JoH.niceTimeScalar(wakeup_jitter));
                            JoH.buggy_samsung = true;
                            PersistentStore.incrementLong(BUGGY_SAMSUNG_ENABLED);
                            max_wakeup_jitter = 0;
                        } else {
                            max_wakeup_jitter = Math.max(max_wakeup_jitter, wakeup_jitter);
                        }

                    }
                }
                wakeup_time = 0; // don't check this one again
            }


            retry_time = 0; // we have woken up
            last_wake_up_time = JoH.tsl();
            try {
                address = ActiveBluetoothDevice.first().address;
            } catch (NullPointerException e) {
                // bluetooth device not set - launch scan ui???
            }

            processInitialState();
            background_automata();

            if (intent != null) {

            }
        } finally {
            JoH.releaseWakeLock(wl);
        }
        return START_STICKY;
    } else {
        UserError.Log.d(TAG, "Should not be running so shutting down");
        stopSelf();
        return START_NOT_STICKY;
    }
}
 
Example 18
Source File: DexCollectionService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
synchronized void checkConnection() {
    status("Attempting connection");
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager == null) {
        status("No bluetooth manager");
        setRetryTimer();
        return;
    }

    mBluetoothAdapter = bluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        status("No bluetooth adapter");
        setRetryTimer();
        return;
    }

    if (!mBluetoothAdapter.isEnabled()) {
        mConnectionState = STATE_DISCONNECTED; // can't be connected if BT is disabled
        if (Pref.getBoolean("automatically_turn_bluetooth_on", true)) {
            Log.i(TAG, "Turning bluetooth on as appears disabled");
            status("Turning bluetooth on");
            JoH.setBluetoothEnabled(getApplicationContext(), true);
        } else {
            Log.d(TAG, "Not automatically turning on bluetooth due to preferences");
        }
    }

    if (device != null) {
        boolean found = false;
        for (BluetoothDevice bluetoothDevice : bluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
            if (bluetoothDevice.getAddress().equals(device.getAddress())) {
                found = true;
                if (mConnectionState != STATE_CONNECTED) {
                    UserError.Log.d(TAG, "Detected state change by checking connected devices");
                    handleConnectedStateChange();
                }
                break;
            }
        }
        if (!found) {
            if (mConnectionState == STATE_CONNECTED) {
                UserError.Log.d(TAG, "Marking disconnected as not in list of connected devices");
                mConnectionState = STATE_DISCONNECTED; // not in connected list so should be disconnected we think
            }

        }
    } else {
        UserError.Log.d(TAG, "Device is null in checkConnection");
        mConnectionState = STATE_DISCONNECTED; // can't be connected if we don't know the device
    }

    Log.i(TAG, "checkConnection: Connection state: " + getStateStr(mConnectionState));
    if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
        final ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
        if (btDevice != null) {
            final String deviceAddress = btDevice.address;
            mDeviceAddress = deviceAddress;
            try {
                if (mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getRemoteDevice(deviceAddress) != null) {
                    if (useScanning()) {
                        status(gs(R.string.scanning) + (Home.get_engineering_mode() ? ": " + deviceAddress : ""));
                        scanMeister.setAddress(deviceAddress).addCallBack(this, TAG).scan();
                    } else {
                        status("Connecting" + (Home.get_engineering_mode() ? ": " + deviceAddress : ""));
                        connect(deviceAddress);
                    }
                    mStaticState = mConnectionState;
                    return;
                }
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "IllegalArgumentException: " + e);
            }
        }
    } else if (mConnectionState == STATE_CONNECTING) {
        mStaticState = mConnectionState;
        if (JoH.msSince(last_connect_request) > (getTrustAutoConnect() ? Constants.SECOND_IN_MS * 3600 : Constants.SECOND_IN_MS * 30)) {
            Log.i(TAG, "Connecting for too long, shutting down");
            retry_backoff = 0;
            close();
        }
    } else if (mConnectionState == STATE_CONNECTED) { //WOOO, we are good to go, nothing to do here!
        status("Last Connected");
        Log.i(TAG, "checkConnection: Looks like we are already connected, ready to receive");
        retry_backoff = 0;
        mStaticState = mConnectionState;
        if (use_polling && (JoH.msSince(lastPacketTime) >= POLLING_PERIOD)) {
            pollForData();
        }

        return;
    }
    setRetryTimer();
}
 
Example 19
Source File: DexCollectionService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
synchronized void checkConnection() {
    status("Attempting connection");
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager == null) {
        status("No bluetooth manager");
        setRetryTimer();
        return;
    }

    mBluetoothAdapter = bluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        status("No bluetooth adapter");
        setRetryTimer();
        return;
    }

    if (!mBluetoothAdapter.isEnabled()) {
        mConnectionState = STATE_DISCONNECTED; // can't be connected if BT is disabled
        if (Pref.getBoolean("automatically_turn_bluetooth_on", true)) {
            Log.i(TAG, "Turning bluetooth on as appears disabled");
            status("Turning bluetooth on");
            JoH.setBluetoothEnabled(getApplicationContext(), true);
        } else {
            Log.d(TAG, "Not automatically turning on bluetooth due to preferences");
        }
    }

    if (device != null) {
        boolean found = false;
        for (BluetoothDevice bluetoothDevice : bluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
            if (bluetoothDevice.getAddress().equals(device.getAddress())) {
                found = true;
                if (mConnectionState != STATE_CONNECTED) {
                    UserError.Log.d(TAG, "Detected state change by checking connected devices");
                    handleConnectedStateChange();
                }
                break;
            }
        }
        if (!found) {
            if (mConnectionState == STATE_CONNECTED) {
                UserError.Log.d(TAG, "Marking disconnected as not in list of connected devices");
                mConnectionState = STATE_DISCONNECTED; // not in connected list so should be disconnected we think
            }

        }
    } else {
        UserError.Log.d(TAG, "Device is null in checkConnection");
        mConnectionState = STATE_DISCONNECTED; // can't be connected if we don't know the device
    }

    Log.i(TAG, "checkConnection: Connection state: " + getStateStr(mConnectionState));
    if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
        final ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
        if (btDevice != null) {
            final String deviceAddress = btDevice.address;
            mDeviceAddress = deviceAddress;
            try {
                if (mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getRemoteDevice(deviceAddress) != null) {
                    if (useScanning()) {
                        status(gs(R.string.scanning) + (Home.get_engineering_mode() ? ": " + deviceAddress : ""));
                        scanMeister.setAddress(deviceAddress).addCallBack(this, TAG).scan();
                    } else {
                        status("Connecting" + (Home.get_engineering_mode() ? ": " + deviceAddress : ""));
                        connect(deviceAddress);
                    }
                    mStaticState = mConnectionState;
                    return;
                }
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "IllegalArgumentException: " + e);
            }
        }
    } else if (mConnectionState == STATE_CONNECTING) {
        mStaticState = mConnectionState;
        if (JoH.msSince(last_connect_request) > (getTrustAutoConnect() ? Constants.SECOND_IN_MS * 3600 : Constants.SECOND_IN_MS * 30)) {
            Log.i(TAG, "Connecting for too long, shutting down");
            retry_backoff = 0;
            close();
        }
    } else if (mConnectionState == STATE_CONNECTED) { //WOOO, we are good to go, nothing to do here!
        status("Last Connected");
        Log.i(TAG, "checkConnection: Looks like we are already connected, ready to receive");
        retry_backoff = 0;
        mStaticState = mConnectionState;
        if (use_polling && (JoH.msSince(lastPacketTime) >= POLLING_PERIOD)) {
            pollForData();
        }

        return;
    }
    setRetryTimer();
}
 
Example 20
Source File: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public void attemptConnection() {
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    if (mBluetoothManager != null) {
        if (device != null) {
            mConnectionState = STATE_DISCONNECTED;
            for (BluetoothDevice bluetoothDevice : mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT)) {
                if (bluetoothDevice.getAddress().compareTo(device.getAddress()) == 0) {
                    mConnectionState = STATE_CONNECTED;
                }
            }
        }
        Log.i(TAG, "Connection state: " + mConnectionState);
        if (mConnectionState == STATE_DISCONNECTED || mConnectionState == STATE_DISCONNECTING) {
            ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
            if (btDevice != null) {
                mDeviceName = btDevice.name;
                mDeviceAddress = btDevice.address;
                mBluetoothAdapter = mBluetoothManager.getAdapter();
                try {
                    if (mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getRemoteDevice(mDeviceAddress) != null) {
                        connect(mDeviceAddress);
                        return;
                    } else {
                        Log.w(TAG, "Bluetooth is disabled or BT device cant be found");
                        setRetryTimer();
                        return;
                    }
                } catch (IllegalArgumentException e) {
                    if (JoH.ratelimit("dex-share-error-log", 180)) {
                        Log.wtf(TAG, "Error connecting: " + e);
                    }
                }
            } else {
                Log.w(TAG, "No bluetooth device to try and connect to");
                setRetryTimer();
                return;
            }
        } else if (mConnectionState == STATE_CONNECTED) {
            Log.i(TAG, "Looks like we are already connected, going to read!");
            attemptRead();
            return;
        } else {
            setRetryTimer();
            return;
        }
    } else {
        setRetryTimer();
        return;
    }
}