Search in sources :

Example 11 with Subscription

use of com.eveningoutpost.dexdrip.utils.bt.Subscription in project xDrip-plus by jamorham.

the class MedtrumCollectionService method enable_features_and_listen.

private synchronized void enable_features_and_listen() {
    UserError.Log.d(TAG, "enable features - enter");
    stopListening();
    if (connection != null) {
        notificationSubscription = new Subscription(connection.setupNotification(Const.CGM_CHARACTERISTIC_NOTIFY).timeout(LISTEN_STASIS_SECONDS, // WARN
        TimeUnit.SECONDS).observeOn(Schedulers.newThread()).doOnNext(notificationObservable -> {
            UserError.Log.d(TAG, "Notifications enabled");
        }).flatMap(notificationObservable -> notificationObservable).subscribe(bytes -> {
            final PowerManager.WakeLock wl = JoH.getWakeLock("medtrum-receive-n", 60000);
            try {
                UserError.Log.d(TAG, "Received notification bytes: " + JoH.bytesToHex(bytes));
                lastInteractionTime = JoH.tsl();
                setFailOverTimer();
                lastAnnex = new AnnexARx(bytes);
                UserError.Log.d(TAG, "Notification: " + lastAnnex.toS());
                createRecordFromAnnexData(lastAnnex);
                backFillIfNeeded(lastAnnex);
            } finally {
                JoH.releaseWakeLock(wl);
            }
        }, throwable -> {
            UserError.Log.d(TAG, "notification throwable: " + throwable);
        }));
        final InboundStream inboundStream = new InboundStream();
        indicationSubscription = new Subscription(connection.setupIndication(CGM_CHARACTERISTIC_INDICATE).timeout(LISTEN_STASIS_SECONDS, // WARN
        TimeUnit.SECONDS).observeOn(Schedulers.newThread()).doOnNext(notificationObservable -> {
            UserError.Log.d(TAG, "Indications enabled");
            sendTx(new AuthTx(serial));
        }).flatMap(notificationObservable -> notificationObservable).subscribe(bytes -> {
            final PowerManager.WakeLock wl = JoH.getWakeLock("medtrum-receive-i", 60000);
            try {
                UserError.Log.d(TAG, "Received indication bytes: " + JoH.bytesToHex(bytes));
                if (inboundStream.hasSomeData() && msSince(lastInteractionTime) > Constants.SECOND_IN_MS * 10) {
                    UserError.Log.d(TAG, "Resetting stream due to earlier timeout");
                }
                lastInteractionTime = JoH.tsl();
                inboundStream.push(bytes);
                if (!checkAndProcessInboundStream(inboundStream)) {
                    Inevitable.task("mt-reset-stream-no-data", 3000, () -> {
                        if (inboundStream.hasSomeData()) {
                            UserError.Log.d(TAG, "Resetting stream as incomplete after 3s");
                            inboundStream.reset();
                        }
                    });
                }
            } finally {
                JoH.releaseWakeLock(wl);
            }
        }, throwable -> {
            UserError.Log.d(TAG, "indication throwable: " + throwable);
        }));
    } else {
        UserError.Log.e(TAG, "Connection null when trying to set notifications");
    }
}
Also used : PersistentStore(com.eveningoutpost.dexdrip.UtilityModels.PersistentStore) com.eveningoutpost.dexdrip.xdrip(com.eveningoutpost.dexdrip.xdrip) AuthTx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.AuthTx) PendingIntent(android.app.PendingIntent) Inevitable(com.eveningoutpost.dexdrip.UtilityModels.Inevitable) Pref(com.eveningoutpost.dexdrip.UtilityModels.Pref) PowerManager(android.os.PowerManager) StatusItem(com.eveningoutpost.dexdrip.UtilityModels.StatusItem) TimeKeeper.timeStampFromTickCounter(com.eveningoutpost.dexdrip.cgm.medtrum.TimeKeeper.timeStampFromTickCounter) BtCallBack(com.eveningoutpost.dexdrip.utils.BtCallBack) BackFillRx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.BackFillRx) InboundStream(com.eveningoutpost.dexdrip.cgm.medtrum.messages.InboundStream) Schedulers(io.reactivex.schedulers.Schedulers) Ok(com.eveningoutpost.dexdrip.cgm.medtrum.SensorState.Ok) RxBleClient(com.polidea.rxandroidble2.RxBleClient) CALIBRATE(com.eveningoutpost.dexdrip.cgm.medtrum.MedtrumCollectionService.STATE.CALIBRATE) AnnexARx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.AnnexARx) CLOSE(com.eveningoutpost.dexdrip.cgm.medtrum.MedtrumCollectionService.STATE.CLOSE) BAD(com.eveningoutpost.dexdrip.UtilityModels.StatusItem.Highlight.BAD) NotCalibrated(com.eveningoutpost.dexdrip.cgm.medtrum.SensorState.NotCalibrated) OPCODE_CALI_REPLY(com.eveningoutpost.dexdrip.cgm.medtrum.Const.OPCODE_CALI_REPLY) ENABLE(com.eveningoutpost.dexdrip.cgm.medtrum.MedtrumCollectionService.STATE.ENABLE) BgReading.bgReadingInsertMedtrum(com.eveningoutpost.dexdrip.Models.BgReading.bgReadingInsertMedtrum) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) NORMAL(com.eveningoutpost.dexdrip.UtilityModels.StatusItem.Highlight.NORMAL) CalibrateRx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.CalibrateRx) MEDTRUM_SERVICE_RETRY_ID(com.eveningoutpost.dexdrip.UtilityModels.Constants.MEDTRUM_SERVICE_RETRY_ID) TransmitterData(com.eveningoutpost.dexdrip.Models.TransmitterData) TimeTx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.TimeTx) JoH(com.eveningoutpost.dexdrip.Models.JoH) List(java.util.List) Disposable(io.reactivex.disposables.Disposable) ConnParamTx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.ConnParamTx) StatusRx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.StatusRx) R(com.eveningoutpost.dexdrip.R) Subscription(com.eveningoutpost.dexdrip.utils.bt.Subscription) Home(com.eveningoutpost.dexdrip.Home) BgGraphBuilder(com.eveningoutpost.dexdrip.UtilityModels.BgGraphBuilder) BaseMessage(com.eveningoutpost.dexdrip.cgm.medtrum.messages.BaseMessage) JoH.msTill(com.eveningoutpost.dexdrip.Models.JoH.msTill) OPCODE_AUTH_REPLY(com.eveningoutpost.dexdrip.cgm.medtrum.Const.OPCODE_AUTH_REPLY) INIT(com.eveningoutpost.dexdrip.cgm.medtrum.MedtrumCollectionService.STATE.INIT) WakeLockTrampoline(com.eveningoutpost.dexdrip.utils.framework.WakeLockTrampoline) Constants(com.eveningoutpost.dexdrip.UtilityModels.Constants) Pair(android.util.Pair) AuthRx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.AuthRx) ActiveBluetoothDevice(com.eveningoutpost.dexdrip.Models.ActiveBluetoothDevice) RxBleConnection(com.polidea.rxandroidble2.RxBleConnection) MEDTRUM_SERVICE_FAILOVER_ID(com.eveningoutpost.dexdrip.UtilityModels.Constants.MEDTRUM_SERVICE_FAILOVER_ID) Intent(android.content.Intent) HOUR_IN_MS(com.eveningoutpost.dexdrip.UtilityModels.Constants.HOUR_IN_MS) CRITICAL(com.eveningoutpost.dexdrip.UtilityModels.StatusItem.Highlight.CRITICAL) GOOD(com.eveningoutpost.dexdrip.UtilityModels.StatusItem.Highlight.GOOD) HexDump(com.eveningoutpost.dexdrip.ImportedLibraries.usbserial.util.HexDump) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ArrayList(java.util.ArrayList) CGM_CHARACTERISTIC_INDICATE(com.eveningoutpost.dexdrip.cgm.medtrum.Const.CGM_CHARACTERISTIC_INDICATE) BackFillTx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.BackFillTx) OPCODE_CONN_REPLY(com.eveningoutpost.dexdrip.cgm.medtrum.Const.OPCODE_CONN_REPLY) SuppressLint(android.annotation.SuppressLint) Prediction(com.eveningoutpost.dexdrip.Models.Prediction) Scheduler(io.reactivex.Scheduler) Observable(io.reactivex.Observable) OPCODE_TIME_REPLY(com.eveningoutpost.dexdrip.cgm.medtrum.Const.OPCODE_TIME_REPLY) Build(android.os.Build) CLOSED(com.eveningoutpost.dexdrip.cgm.medtrum.MedtrumCollectionService.STATE.CLOSED) JamBaseBluetoothService(com.eveningoutpost.dexdrip.Services.JamBaseBluetoothService) SET_CONN_PARAM(com.eveningoutpost.dexdrip.cgm.medtrum.MedtrumCollectionService.STATE.SET_CONN_PARAM) SCAN(com.eveningoutpost.dexdrip.cgm.medtrum.MedtrumCollectionService.STATE.SCAN) SpannableString(android.text.SpannableString) com.eveningoutpost.dexdrip.xdrip.gs(com.eveningoutpost.dexdrip.xdrip.gs) JoH.msSince(com.eveningoutpost.dexdrip.Models.JoH.msSince) CalibrateTx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.CalibrateTx) TimeRx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.TimeRx) Medtrum.getSerial(com.eveningoutpost.dexdrip.cgm.medtrum.Medtrum.getSerial) TimeUnit(java.util.concurrent.TimeUnit) StatusTx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.StatusTx) CONNECT(com.eveningoutpost.dexdrip.cgm.medtrum.MedtrumCollectionService.STATE.CONNECT) JoH.quietratelimit(com.eveningoutpost.dexdrip.Models.JoH.quietratelimit) RxBleProvider(com.eveningoutpost.dexdrip.UtilityModels.RxBleProvider) DexCollectionType(com.eveningoutpost.dexdrip.utils.DexCollectionType) ConnParamRx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.ConnParamRx) OPCODE_STAT_REPLY(com.eveningoutpost.dexdrip.cgm.medtrum.Const.OPCODE_STAT_REPLY) DisconnectReceiver(com.eveningoutpost.dexdrip.utils.DisconnectReceiver) OPCODE_BACK_REPLY(com.eveningoutpost.dexdrip.cgm.medtrum.Const.OPCODE_BACK_REPLY) UserError(com.eveningoutpost.dexdrip.Models.UserError) Span(com.eveningoutpost.dexdrip.ui.helpers.Span) RxBleDevice(com.polidea.rxandroidble2.RxBleDevice) MINUTE_IN_MS(com.eveningoutpost.dexdrip.UtilityModels.Constants.MINUTE_IN_MS) PowerManager(android.os.PowerManager) AnnexARx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.AnnexARx) Subscription(com.eveningoutpost.dexdrip.utils.bt.Subscription) InboundStream(com.eveningoutpost.dexdrip.cgm.medtrum.messages.InboundStream) AuthTx(com.eveningoutpost.dexdrip.cgm.medtrum.messages.AuthTx)

Example 12 with Subscription

use of com.eveningoutpost.dexdrip.utils.bt.Subscription in project xDrip-plus by jamorham.

the class MedtrumCollectionService method connect_to_device.

private synchronized void connect_to_device(boolean auto) {
    if (state == CONNECT) {
        // UserError.Log.d(TAG, "Address length: " + address.length());
        if (address != null && address.length() > 6) {
            status("Connecting");
            stopConnect();
            bleDevice = rxBleClient.getBleDevice(address);
            // Listen for connection state changes
            stateSubscription = new Subscription(bleDevice.observeConnectionStateChanges().subscribeOn(Schedulers.io()).subscribe(this::onConnectionStateChange, throwable -> {
                UserError.Log.wtf(TAG, "Got Error from state subscription: " + throwable);
            }));
            // Attempt to establish a connection
            listen_connected = false;
            // auto not allowed due to timeout
            auto = false;
            connectionSubscription = new Subscription(bleDevice.establishConnection(auto).timeout(LISTEN_STASIS_SECONDS, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).subscribe(this::onConnectionReceived, this::onConnectionFailure));
        } else {
            UserError.Log.wtf(TAG, "No transmitter mac address!");
            changeState(SCAN);
        }
    } else {
        UserError.Log.wtf(TAG, "Attempt to connect when not in CONNECT state");
    }
}
Also used : Subscription(com.eveningoutpost.dexdrip.utils.bt.Subscription)

Example 13 with Subscription

use of com.eveningoutpost.dexdrip.utils.bt.Subscription in project xDrip-plus by jamorham.

the class InPenScanMeister method scan.

@Override
public synchronized void scan() {
    extendWakeLock((scanSeconds + 1) * Constants.SECOND_IN_MS);
    stopScan("Scan start");
    UserError.Log.d(TAG, "startScan called: hunting: " + address + " " + name);
    scanSubscription = new Subscription(rxBleClient.scanBleDevices(new ScanSettings.Builder().setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(SCAN_SERVICE_UUID)).build()).timeout(scanSeconds, // is unreliable
    TimeUnit.SECONDS).subscribeOn(Schedulers.io()).subscribe(this::onScanResult, this::onScanFailure));
    Inevitable.task(STOP_SCAN_TASK_ID, scanSeconds * Constants.SECOND_IN_MS, this::stopScanWithTimeoutCallback);
}
Also used : ScanSettings(com.polidea.rxandroidble2.scan.ScanSettings) Subscription(com.eveningoutpost.dexdrip.utils.bt.Subscription)

Example 14 with Subscription

use of com.eveningoutpost.dexdrip.utils.bt.Subscription in project xDrip-plus by jamorham.

the class PendiqService method connect_to_device.

private synchronized void connect_to_device(boolean auto) {
    if ((state == CONNECT) || (state == STATE.CONNECT_NOW)) {
        // TODO check mac
        if (address != null) {
            // msg("Connect request");
            if (state == STATE.CONNECT_NOW) {
                if (connection_linger != null)
                    JoH.releaseWakeLock(connection_linger);
                connection_linger = JoH.getWakeLock("jam-pendiq-pconnect", 60000);
            }
            // if (d)
            // UserError.Log.d(TAG, "Local bonding state: " + (isDeviceLocallyBonded() ? "BONDED" : "NOT Bonded"));
            stopConnect();
            bleDevice = rxBleClient.getBleDevice(address);
            // / / Listen for connection state changes
            stateSubscription = new Subscription(bleDevice.observeConnectionStateChanges().subscribeOn(Schedulers.io()).subscribe(this::onConnectionStateChange, throwable -> {
                UserError.Log.wtf(TAG, "Got Error from state subscription: " + throwable);
            }));
            // Attempt to establish a connection
            connectionSubscription = new Subscription(bleDevice.establishConnection(auto).timeout(7, TimeUnit.MINUTES).subscribeOn(Schedulers.io()).subscribe(this::onConnectionReceived, this::onConnectionFailure));
        } else {
            UserError.Log.wtf(TAG, "No transmitter mac address!");
            changeState(SCAN);
        // state = STATE.SCAN;
        // backoff_automata(); // note backoff
        }
    } else {
        UserError.Log.wtf(TAG, "Attempt to connect when not in CONNECT state");
    }
}
Also used : Subscription(com.eveningoutpost.dexdrip.utils.bt.Subscription)

Example 15 with Subscription

use of com.eveningoutpost.dexdrip.utils.bt.Subscription in project xDrip-plus by jamorham.

the class PendiqService method scan_for_device.

private synchronized void scan_for_device() {
    extendWakeLock((SCAN_SECONDS + 1) * Constants.SECOND_IN_MS);
    stopScan();
    scanSubscription = new Subscription(rxBleClient.scanBleDevices(new ScanSettings.Builder().setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()).timeout(SCAN_SECONDS, // is unreliable
    TimeUnit.SECONDS).subscribeOn(Schedulers.io()).subscribe(this::onScanResult, this::onScanFailure));
    Inevitable.task("stop_pendiq_scan", SCAN_SECONDS * Constants.SECOND_IN_MS, this::stopScan);
}
Also used : ScanSettings(com.polidea.rxandroidble2.scan.ScanSettings) Subscription(com.eveningoutpost.dexdrip.utils.bt.Subscription)

Aggregations

Subscription (com.eveningoutpost.dexdrip.utils.bt.Subscription)34 SuppressLint (android.annotation.SuppressLint)10 Intent (android.content.Intent)10 PowerManager (android.os.PowerManager)10 Pair (android.util.Pair)10 BgReading (com.eveningoutpost.dexdrip.Models.BgReading)10 JoH (com.eveningoutpost.dexdrip.Models.JoH)10 JoH.msTill (com.eveningoutpost.dexdrip.Models.JoH.msTill)10 UserError (com.eveningoutpost.dexdrip.Models.UserError)10 R (com.eveningoutpost.dexdrip.R)10 Constants (com.eveningoutpost.dexdrip.UtilityModels.Constants)10 Inevitable (com.eveningoutpost.dexdrip.UtilityModels.Inevitable)10 StatusItem (com.eveningoutpost.dexdrip.UtilityModels.StatusItem)10 WakeLockTrampoline (com.eveningoutpost.dexdrip.utils.framework.WakeLockTrampoline)10 com.eveningoutpost.dexdrip.xdrip (com.eveningoutpost.dexdrip.xdrip)10 com.eveningoutpost.dexdrip.xdrip.gs (com.eveningoutpost.dexdrip.xdrip.gs)10 BleCharacteristicNotFoundException (com.polidea.rxandroidble2.exceptions.BleCharacteristicNotFoundException)10 Schedulers (io.reactivex.schedulers.Schedulers)10 ArrayList (java.util.ArrayList)10 List (java.util.List)10