导航菜单

页面标题

页面副标题

xDrip+ v04633772025.07.16 - MiBandService.java 源代码

正在查看: xDrip+ v04633772025.07.16 应用的 MiBandService.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.eveningoutpost.dexdrip.watch.miband;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Pair;
import com.eveningoutpost.dexdrip.importedlibraries.usbserial.driver.UsbId;
import com.eveningoutpost.dexdrip.models.ActiveBgAlert;
import com.eveningoutpost.dexdrip.models.BgReading;
import com.eveningoutpost.dexdrip.models.HeartRate;
import com.eveningoutpost.dexdrip.models.JoH;
import com.eveningoutpost.dexdrip.models.UserError;
import com.eveningoutpost.dexdrip.services.JamBaseBluetoothSequencer;
import com.eveningoutpost.dexdrip.utilitymodels.AlertPlayer;
import com.eveningoutpost.dexdrip.utilitymodels.Inevitable;
import com.eveningoutpost.dexdrip.utilitymodels.StatusItem;
import com.eveningoutpost.dexdrip.utils.bt.Subscription;
import com.eveningoutpost.dexdrip.utils.framework.PoorMansConcurrentLinkedDeque;
import com.eveningoutpost.dexdrip.utils.framework.WakeLockTrampoline;
import com.eveningoutpost.dexdrip.watch.PrefBindingFactory;
import com.eveningoutpost.dexdrip.watch.miband.Firmware.FirmwareOperations;
import com.eveningoutpost.dexdrip.watch.miband.Firmware.WatchFaceGenerator;
import com.eveningoutpost.dexdrip.watch.miband.MiBand;
import com.eveningoutpost.dexdrip.watch.miband.message.AlertLevelMessage;
import com.eveningoutpost.dexdrip.watch.miband.message.AlertMessage;
import com.eveningoutpost.dexdrip.watch.miband.message.AuthMessages;
import com.eveningoutpost.dexdrip.watch.miband.message.DisplayControllMessage;
import com.eveningoutpost.dexdrip.watch.miband.message.DisplayControllMessageMiBand2;
import com.eveningoutpost.dexdrip.watch.miband.message.DisplayControllMessageMiband3_4;
import com.eveningoutpost.dexdrip.watch.miband.message.FeaturesControllMessage;
import com.eveningoutpost.dexdrip.watch.miband.message.OperationCodes;
import com.eveningoutpost.dexdrip.xdrip;
import com.polidea.rxandroidble2.RxBleConnection;
import com.polidea.rxandroidble2.RxBleDeviceServices;
import com.polidea.rxandroidble2.exceptions.BleCannotSetCharacteristicNotificationException;
import com.polidea.rxandroidble2.exceptions.BleCharacteristicNotFoundException;
import com.polidea.rxandroidble2.exceptions.BleDisconnectedException;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class MiBandService extends JamBaseBluetoothSequencer {
    static BatteryInfo batteryInfo = new BatteryInfo();
    private static long bgWakeupTime;
    static final List<UUID> huntCharacterstics;
    private Subscription authSubscription;
    private AuthMessages authorisation;
    private PendingIntent bgServiceIntent;
    private int defaultSnoozle;
    private FirmwareOperations firmware;
    private Boolean isNeedToAuthenticate;
    private Boolean isNeedToCheckRevision;
    private Boolean isNeedToRestoreNightMode;
    private boolean isNightMode;
    private boolean isWaitingCallResponce;
    private Boolean isWaitingSnoozeResponce;
    private final PoorMansConcurrentLinkedDeque<QueueMessage> messageQueue;
    private Subscription notifSubscriptionDeviceEvent;
    private Subscription notifSubscriptionHeartRateMeasurement;
    private MiBand.MiBandType prevDeviceType;
    private QueueMessage queueItem;
    private Subscription watchfaceSubscription;

    public enum MIBAND_INTEND_STATES {
        UPDATE_PREF_SCREEN,
        UPDATE_PREF_DATA
    }

    public static ObservableSource lambda$authPhase$16(Observable observable) throws Exception {
        return observable;
    }

    public static ObservableSource lambda$enableHeartRateNotification$41(Observable observable) throws Exception {
        return observable;
    }

    public static ObservableSource lambda$enableNotification$38(Observable observable) throws Exception {
        return observable;
    }

    public static ObservableSource lambda$installWatchface$24(Observable observable) throws Exception {
        return observable;
    }

    @Override
    public void resetBluetoothIfWeSeemToAlreadyBeConnected(String str) {
    }

    public MiBandService() {
        Boolean bool = Boolean.TRUE;
        this.isNeedToCheckRevision = bool;
        this.isNeedToAuthenticate = bool;
        this.isWaitingCallResponce = false;
        Boolean bool2 = Boolean.FALSE;
        this.isWaitingSnoozeResponce = bool2;
        this.isNeedToRestoreNightMode = bool2;
        this.isNightMode = false;
        this.prevDeviceType = MiBand.MiBandType.UNKNOWN;
        this.messageQueue = new PoorMansConcurrentLinkedDeque<>();
        this.mState = new MiBandState().setLI(this.I);
        this.I.backgroundStepDelay = 0;
        this.I.connectTimeoutMinutes = 300000;
        startBgTimer();
    }

    static {
        ArrayList arrayList = new ArrayList();
        huntCharacterstics = arrayList;
        arrayList.add(Const.UUID_CHAR_NEW_ALERT);
    }

    public class QueueMessage {
        private int defaultSnoozle;
        private String functionName;
        private String message;
        private String message_type;
        private String title;

        public QueueMessage(String str) {
            this.message_type = "";
            this.message = "";
            this.title = "";
            this.defaultSnoozle = 0;
            this.functionName = str;
        }

        public QueueMessage(MiBandService miBandService, String str, String str2, String str3, String str4, int i) {
            this(str);
            this.message_type = str2;
            this.message = str3;
            this.title = str4;
            this.defaultSnoozle = i;
        }
    }

    private Class getPrefBinder() {
        if (MiBand.getMibandType() == MiBand.MiBandType.MI_BAND2) {
            return Miband2PrefBinding.class;
        }
        return Miband3_4PrefBinding.class;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    private boolean readyToProcessCommand() {
        boolean z = this.I.state.equals("Sleeping") || this.I.state.equals("Closed") || this.I.state.equals("Closing") || this.I.state.equals("Initializing") || this.I.state.equals("Connecting");
        if (!z) {
            UserError.Log.d(this.TAG, "readyToProcessCommand not ready because state :" + this.I.state.toString());
        }
        return z;
    }

    @Override
    public int onStartCommand(Intent intent, int i, int i2) {
        String stringExtra;
        PowerManager.WakeLock wakeLock = JoH.getWakeLock("Miband service", UsbId.SILABS_CP2102);
        try {
            if (shouldServiceRun()) {
                String persistentAuthMac = MiBand.getPersistentAuthMac();
                String mac = MiBand.getMac();
                MiBand.MiBandType mibandType = MiBand.getMibandType();
                if (mibandType != this.prevDeviceType && mibandType != MiBand.MiBandType.UNKNOWN) {
                    this.prevDeviceType = mibandType;
                    UserError.Log.d(this.TAG, "Found new device: " + mibandType.toString());
                    MiBandEntry.sendPrefIntent(MIBAND_INTEND_STATES.UPDATE_PREF_SCREEN, 0, "");
                }
                if (!persistentAuthMac.equalsIgnoreCase(mac) || persistentAuthMac.isEmpty()) {
                    this.prevDeviceType = MiBand.getMibandType();
                    if (!persistentAuthMac.isEmpty()) {
                        String model = MiBand.getModel();
                        MiBand.setPersistentAuthMac("");
                        MiBand.setModel(model, mac);
                    }
                    this.isNeedToAuthenticate = Boolean.TRUE;
                }
                if (JoH.emptyString(mac)) {
                    new FindNearby().scan();
                } else {
                    setAddress(mac);
                    if (intent != null && (stringExtra = intent.getStringExtra("function")) != null) {
                        UserError.Log.d(this.TAG, "onStartCommand was called with function:" + stringExtra);
                        String stringExtra2 = intent.getStringExtra("message_type");
                        String stringExtra3 = intent.getStringExtra("message");
                        String stringExtra4 = intent.getStringExtra("title");
                        String stringExtra5 = intent.getStringExtra("default_snoozle");
                        String str = stringExtra3 != null ? stringExtra3 : "";
                        String str2 = stringExtra2 != null ? stringExtra2 : "";
                        String str3 = stringExtra4 != null ? stringExtra4 : "";
                        if (stringExtra5 == null) {
                            stringExtra5 = "0";
                        }
                        if (stringExtra.equals("refresh")) {
                            if (!JoH.pratelimit("miband-set-time-via-refresh-" + MiBand.getMac(), 5)) {
                                return 1;
                            }
                        }
                        this.messageQueue.add(new QueueMessage(this, stringExtra, str2, str, str3, Integer.parseInt(stringExtra5)));
                        if (readyToProcessCommand()) {
                            handleCommand();
                        }
                    }
                }
                return 1;
            }
            UserError.Log.d(this.TAG, "Service is NOT set be active - shutting down");
            stopBgUpdateTimer();
            stopConnection();
            changeState("Closing");
            stopSelf();
            JoH.releaseWakeLock(wakeLock);
            return 2;
        } finally {
            JoH.releaseWakeLock(wakeLock);
        }
    }

    private void handleCommand() {
        if (this.messageQueue.isEmpty()) {
        }
        QueueMessage poll = this.messageQueue.poll();
        this.queueItem = poll;
        String str = poll.functionName;
        str.hashCode();
        switch (str) {
            case "update_bg_force":
                startBgTimer();
                ((MiBandState) this.mState).setSendReadingSequence();
                changeState("Initializing");
                break;
            case "update_bg":
                if (!this.isNightMode) {
                    startBgTimer();
                    ((MiBandState) this.mState).setSendReadingSequence();
                    changeState("Initializing");
                    break;
                }
                break;
            case "update_bg_as_notification":
                ((MiBandState) this.mState).setSendReadingSequence();
                changeState("Initializing");
                break;
            case "glucose_after":
                if (this.isWaitingSnoozeResponce.booleanValue()) {
                    ((MiBandState) this.mState).setQueueSequence();
                    changeState("Initializing");
                    break;
                }
                break;
            case "message":
                ((MiBandState) this.mState).setQueueSequence();
                this.defaultSnoozle = this.queueItem.defaultSnoozle;
                changeState("Initializing");
                break;
            case "refresh":
                whenToRetryNextBgTimer();
                ((MiBandState) this.mState).setSettingsSequence();
                changeState("Initializing");
                break;
        }
    }

    private static final boolean isBetweenValidTime(Date date, Date date2, Date date3) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(1, 1, 1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(date2);
        calendar2.set(1, 1, 1);
        Calendar calendar3 = Calendar.getInstance();
        calendar3.setTime(date3);
        calendar3.set(1, 1, 1);
        if (calendar2.compareTo(calendar) > 0) {
            return calendar3.compareTo(calendar) >= 0 && calendar3.compareTo(calendar2) <= 0;
        }
        if (calendar2.compareTo(calendar) < 0) {
            return calendar3.compareTo(calendar2) < 0 || calendar3.compareTo(calendar) > 0;
        }
        return false;
    }

    private static final int compareTime(Date date, Date date2) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(1, 1, 1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(date2);
        calendar2.set(1, 1, 1);
        return calendar2.compareTo(calendar);
    }

    private long whenToRetryNextBgTimer() {
        int nightModeInterval;
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis() + 1800000);
        this.isNightMode = false;
        if (MiBandEntry.isNightModeEnabled() && (nightModeInterval = MiBandEntry.getNightModeInterval()) != 5) {
            Date time = Calendar.getInstance().getTime();
            Date nightModeStart = MiBandEntry.getNightModeStart();
            Date nightModeEnd = MiBandEntry.getNightModeEnd();
            Boolean valueOf = Boolean.valueOf(isBetweenValidTime(nightModeStart, nightModeEnd, time));
            UserError.Log.d(this.TAG, "isBetweenValidTime: " + valueOf);
            if (valueOf.booleanValue()) {
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTimeInMillis(System.currentTimeMillis() + (nightModeInterval * 60000));
                if (compareTime(nightModeEnd, calendar2.getTime()) >= 0) {
                    Calendar calendar3 = Calendar.getInstance();
                    calendar3.setTime(nightModeEnd);
                    calendar2.set(11, calendar3.get(11));
                    calendar2.set(12, calendar3.get(12));
                }
                calendar.setTimeInMillis(calendar2.getTimeInMillis());
                this.isNightMode = true;
            }
        }
        return calendar.getTimeInMillis() - JoH.tsl();
    }

    private void stopBgUpdateTimer() {
        JoH.cancelAlarm(xdrip.getAppContext(), this.bgServiceIntent);
        bgWakeupTime = 0L;
        this.isNightMode = false;
    }

    private void startBgTimer() {
        stopBgUpdateTimer();
        if (shouldServiceRun() && MiBand.isAuthenticated() && !MiBandEntry.isNeedSendReadingAsNotification()) {
            long whenToRetryNextBgTimer = whenToRetryNextBgTimer();
            UserError.Log.d(this.TAG, "Scheduling next BgTimer in: " + JoH.niceTimeScalar(whenToRetryNextBgTimer) + " @ " + JoH.dateTimeText(JoH.tsl() + whenToRetryNextBgTimer));
            this.bgServiceIntent = WakeLockTrampoline.getPendingIntent(getClass(), UsbId.VENDOR_FTDI, this.isNightMode ? "update_bg_force" : "update_bg");
            JoH.wakeUpIntent(xdrip.getAppContext(), whenToRetryNextBgTimer, this.bgServiceIntent);
            bgWakeupTime = JoH.tsl() + whenToRetryNextBgTimer;
            return;
        }
        UserError.Log.d(this.TAG, "Not setting retry timer as service should not be running");
    }

    private void acknowledgeFindPhone() {
        UserError.Log.d(this.TAG, "acknowledgeFindPhone");
        this.I.connection.writeCharacteristic(Const.UUID_CHARACTERISTIC_3_CONFIGURATION, OperationCodes.COMMAND_ACK_FIND_PHONE_IN_PROGRESS).subscribe(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$acknowledgeFindPhone$0((byte[]) obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$acknowledgeFindPhone$1((Throwable) obj);
            }
        });
    }

    public void lambda$acknowledgeFindPhone$0(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote acknowledgeFindPhone: " + JoH.bytesToHex(bArr));
    }

    public void lambda$acknowledgeFindPhone$1(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not write acknowledgeFindPhone: " + th);
    }

    private void handleDeviceEvent(byte[] bArr) {
        if (bArr == null || bArr.length == 0) {
            return;
        }
        byte b = bArr[0];
        if (b == -2) {
            UserError.Log.d(this.TAG, "got music control");
            byte b2 = bArr[1];
            if (b2 == -32) {
                UserError.Log.d(this.TAG, "Music app started");
                return;
            }
            if (b2 == -31) {
                UserError.Log.d(this.TAG, "Music app terminated");
                return;
            }
            if (b2 == 0) {
                UserError.Log.d(this.TAG, "Music app Event.PLAY");
                return;
            }
            if (b2 == 1) {
                UserError.Log.d(this.TAG, "Music app Event.PAUSE");
                return;
            }
            if (b2 == 3) {
                UserError.Log.d(this.TAG, "Music app Event.NEXT");
                return;
            }
            if (b2 == 4) {
                UserError.Log.d(this.TAG, "Music app Event.PREVIOUS");
                return;
            }
            if (b2 == 5) {
                UserError.Log.d(this.TAG, "Music app Event.VOLUMEUP");
                return;
            }
            if (b2 == 6) {
                UserError.Log.d(this.TAG, "Music app Event.VOLUMEDOWN");
                return;
            }
            UserError.Log.d(this.TAG, "unhandled music control event " + ((int) bArr[1]));
            return;
        }
        if (b == 22) {
            int i = (bArr[1] & 255) | ((bArr[2] & 255) << 8);
            UserError.Log.d(this.TAG, "device announced MTU of " + i);
            return;
        }
        if (b == 1) {
            UserError.Log.d(this.TAG, "Fell asleep");
            return;
        }
        if (b == 2) {
            UserError.Log.d(this.TAG, "Woke up");
            return;
        }
        if (b == 3) {
            UserError.Log.d(this.TAG, "Steps goal reached");
            return;
        }
        if (b == 4) {
            UserError.Log.d(this.TAG, "button pressed");
            return;
        }
        if (b == 14) {
            UserError.Log.d(this.TAG, "Tick 30 min (?)");
            return;
        }
        if (b != 15) {
            switch (b) {
                case 6:
                    UserError.Log.d(this.TAG, "non-wear start detected");
                    break;
                case 7:
                    UserError.Log.d(this.TAG, "call rejected");
                    if (ActiveBgAlert.currentlyAlerting() && this.isWaitingSnoozeResponce.booleanValue()) {
                        try {
                            this.isWaitingSnoozeResponce = Boolean.FALSE;
                            AlertPlayer.getPlayer().Snooze(xdrip.getAppContext(), this.defaultSnoozle, true);
                            String str = "Alert snoozed for " + this.defaultSnoozle + " min";
                            UserError.Log.d(this.TAG, str);
                            this.messageQueue.addFirst(new QueueMessage(this, "message", "NOTIFY_TYPE_MESSAGE", str, "Alert snoozed", 0));
                            if (readyToProcessCommand()) {
                                handleCommand();
                            }
                        } catch (NumberFormatException unused) {
                            UserError.Log.d(this.TAG, "Alert was attempted to be snoozed by watch, but snoozleVal was wrong");
                        }
                    }
                    this.isWaitingCallResponce = false;
                    break;
                case 8:
                    UserError.Log.d(this.TAG, "find phone started");
                    if (JoH.ratelimit("band_find phone_sound", 3)) {
                        JoH.playSoundUri(JoH.getResourceURI(2131689476));
                    }
                    acknowledgeFindPhone();
                    break;
                case 9:
                    UserError.Log.d(this.TAG, "call ignored");
                    this.isWaitingSnoozeResponce = Boolean.FALSE;
                    this.isWaitingCallResponce = false;
                    break;
                case 10:
                    UserError.Log.d(this.TAG, "An alarm was toggled");
                    break;
                case 11:
                    UserError.Log.d(this.TAG, "button long-pressed ");
                    break;
                default:
                    UserError.Log.d(this.TAG, "unhandled event " + ((int) bArr[0]));
                    break;
            }
            return;
        }
        UserError.Log.d(this.TAG, "find phone stopped");
        JoH.stopSoundUri();
    }

    @Override
    protected void onServicesDiscovered(RxBleDeviceServices rxBleDeviceServices) {
        boolean z = false;
        for (BluetoothGattService bluetoothGattService : rxBleDeviceServices.getBluetoothGattServices()) {
            UserError.Log.d(this.TAG, "Service: " + JamBaseBluetoothSequencer.getUUIDName(bluetoothGattService.getUuid()));
            for (BluetoothGattCharacteristic bluetoothGattCharacteristic : bluetoothGattService.getCharacteristics()) {
                UserError.Log.d(this.TAG, "-- Character: " + JamBaseBluetoothSequencer.getUUIDName(bluetoothGattCharacteristic.getUuid()));
                for (UUID uuid : huntCharacterstics) {
                    if (bluetoothGattCharacteristic.getUuid().equals(uuid)) {
                        this.I.readCharacteristic = uuid;
                        z = true;
                    }
                }
            }
        }
        if (z) {
            this.I.isDiscoveryComplete = true;
            this.I.discoverOnce = true;
            changeNextState();
            return;
        }
        UserError.Log.e(this.TAG, "Could not find characteristic during service discovery. This is very unusual");
    }

    @SuppressLint({"CheckResult"})
    private void getSoftwareRevision() {
        this.I.connection.readCharacteristic(Const.UUID_CHAR_SOFTWARE_REVISION_STRING).subscribe(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$getSoftwareRevision$2((byte[]) obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$getSoftwareRevision$3((Throwable) obj);
            }
        });
    }

    public void lambda$getSoftwareRevision$2(byte[] bArr) throws Exception {
        String str = new String(bArr);
        UserError.Log.d(this.TAG, "Got software revision: " + str);
        MiBand.setVersion(str, MiBand.getPersistentAuthMac());
        this.isNeedToCheckRevision = Boolean.FALSE;
        changeNextState();
    }

    public void lambda$getSoftwareRevision$3(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not read software revision: " + th);
        changeNextState();
    }

    @SuppressLint({"CheckResult"})
    private void getBatteryInfo() {
        this.I.connection.readCharacteristic(Const.UUID_CHARACTERISTIC_6_BATTERY_INFO).subscribe(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$getBatteryInfo$4((byte[]) obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$getBatteryInfo$5((Throwable) obj);
            }
        });
    }

    public void lambda$getBatteryInfo$4(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Got battery info: " + JoH.bytesToHex(bArr));
        batteryInfo = new BatteryInfo(bArr);
    }

    public void lambda$getBatteryInfo$5(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not read battery info: " + th);
    }

    @SuppressLint({"CheckResult"})
    private void getModelName() {
        this.I.connection.readCharacteristic(Const.UUID_CHAR_DEVICE_NAME).subscribe(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$getModelName$6((byte[]) obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$getModelName$7((Throwable) obj);
            }
        });
    }

    public void lambda$getModelName$6(byte[] bArr) throws Exception {
        if (bArr != null) {
            String str = new String(bArr);
            UserError.Log.d(this.TAG, "Got device name: " + str);
            MiBand.setModel(str, MiBand.getPersistentAuthMac());
        } else {
            UserError.Log.e(this.TAG, "Got null device name");
        }
        changeNextState();
    }

    public void lambda$getModelName$7(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not read device name: " + th);
        changeNextState();
    }

    private Boolean sendBG() {
        BgReading last = BgReading.last();
        AlertMessage alertMessage = new AlertMessage();
        if (last == null || last.isStale()) {
            return Boolean.FALSE;
        }
        String str = "BG: " + last.displayValue(null) + " " + last.displaySlopeArrow();
        UserError.Log.uel(this.TAG, "Send alert msg: " + str);
        if (MiBand.getMibandType() == MiBand.MiBandType.MI_BAND2) {
            new JamBaseBluetoothSequencer.QueueMe().setBytes(alertMessage.getAlertMessageOld(str.toUpperCase(), AlertMessage.AlertCategory.SMS_MMS)).setDescription("Send alert msg: " + str).setQueueWriteCharacterstic(alertMessage.getCharacteristicUUID()).expireInSeconds(30).setDelayMs(0).queue();
        } else {
            new JamBaseBluetoothSequencer.QueueMe().setBytes(alertMessage.getAlertMessage(str.toUpperCase(), AlertMessage.AlertCategory.CustomHuami, AlertMessage.CustomIcon.APP_11, str.toUpperCase())).setDescription("Send alert msg: " + str).setQueueWriteCharacterstic(alertMessage.getCharacteristicUUID()).expireInSeconds(30).setDelayMs(0).queue();
        }
        return Boolean.TRUE;
    }

    private void vibrateAlert(AlertLevelMessage.AlertLevelType alertLevelType) {
        if (alertLevelType == AlertLevelMessage.AlertLevelType.NoAlert) {
            new JamBaseBluetoothSequencer.QueueMe().setBytes(OperationCodes.COMMAND_DISABLE_CALL).setDescription("Send specific disable command for" + alertLevelType).setQueueWriteCharacterstic(Const.UUID_CHARACTERISTIC_CHUNKEDTRANSFER).expireInSeconds(30).setDelayMs(0).queue();
        }
        AlertLevelMessage alertLevelMessage = new AlertLevelMessage();
        new JamBaseBluetoothSequencer.QueueMe().setBytes(alertLevelMessage.getAlertLevelMessage(alertLevelType)).setDescription("Send vibrateAlert: " + alertLevelType).setQueueWriteCharacterstic(alertLevelMessage.getCharacteristicUUID()).expireInSeconds(30).setDelayMs(0).queue();
    }

    private void sendSettings() {
        DisplayControllMessage displayControllMessageMiband3_4;
        List<Pair<Integer, Boolean>> states = PrefBindingFactory.getInstance(getPrefBinder()).getStates("miband_feature_");
        FeaturesControllMessage featuresControllMessage = new FeaturesControllMessage();
        for (Pair<Integer, Boolean> pair : states) {
            byte[] message = featuresControllMessage.getMessage(pair);
            if (message.length != 0) {
                new JamBaseBluetoothSequencer.QueueMe().setBytes(message).setQueueWriteCharacterstic(featuresControllMessage.getCharacteristicUUID()).setDescription("Set feature:" + pair.first + ":" + pair.second).expireInSeconds(30).setDelayMs(0).queue();
            }
        }
        List<Integer> enabled = PrefBindingFactory.getInstance(getPrefBinder()).getEnabled("miband_screen");
        if (MiBand.getMibandType() == MiBand.MiBandType.MI_BAND2) {
            displayControllMessageMiband3_4 = new DisplayControllMessageMiBand2();
        } else {
            displayControllMessageMiband3_4 = new DisplayControllMessageMiband3_4();
        }
        new JamBaseBluetoothSequencer.QueueMe().setBytes(displayControllMessageMiband3_4.getDisplayItemsCmd(enabled)).setQueueWriteCharacterstic(displayControllMessageMiband3_4.getCharacteristicUUID()).setDescription("Set screens").expireInSeconds(30).setDelayMs(0).queue();
        setNightMode();
    }

    private void queueMessage() {
        String str;
        AlertMessage alertMessage;
        str = this.queueItem.message;
        UserError.Log.d(this.TAG, "Queuing message alert: " + str);
        if (this.isWaitingSnoozeResponce.booleanValue()) {
            vibrateAlert(AlertLevelMessage.AlertLevelType.NoAlert);
            this.isWaitingSnoozeResponce = Boolean.FALSE;
        }
        alertMessage = new AlertMessage();
        String str2 = this.queueItem.message_type != null ? this.queueItem.message_type : "null";
        str2.hashCode();
        switch (str2) {
            case "NOTIFY_TYPE_CALL":
                new JamBaseBluetoothSequencer.QueueMe().setBytes(alertMessage.getAlertMessageOld(str, AlertMessage.AlertCategory.Call)).setDescription("Send call alert: " + str).setQueueWriteCharacterstic(alertMessage.getCharacteristicUUID()).setRunnable(new Runnable() {
                    @Override
                    public final void run() {
                        MiBandService.this.lambda$queueMessage$8();
                    }
                }).expireInSeconds(30).setDelayMs(0).queue();
                UserError.Log.d(this.TAG, "Queued call alert: " + str);
                break;
            case "NOTIFY_TYPE_CANCEL":
                if (this.isWaitingCallResponce) {
                    vibrateAlert(AlertLevelMessage.AlertLevelType.NoAlert);
                    this.isWaitingCallResponce = false;
                    UserError.Log.d(this.TAG, "Call disabled");
                    break;
                }
                break;
            case "NOTIFY_TYPE_MESSAGE":
                if (MiBand.getMibandType() != MiBand.MiBandType.MI_BAND2) {
                    new JamBaseBluetoothSequencer.QueueMe().setBytes(alertMessage.getAlertMessage(str, AlertMessage.AlertCategory.CustomHuami, AlertMessage.CustomIcon.RED_WHITE_FIRE_8, this.queueItem.title)).setDescription("Sent message: " + str).setQueueWriteCharacterstic(alertMessage.getCharacteristicUUID()).expireInSeconds(30).setDelayMs(0).queue();
                    break;
                } else {
                    new JamBaseBluetoothSequencer.QueueMe().setBytes(alertMessage.getAlertMessageOld(str, AlertMessage.AlertCategory.SMS_MMS)).setDescription("Sent message: " + str).setQueueWriteCharacterstic(alertMessage.getCharacteristicUUID()).expireInSeconds(30).setDelayMs(0).queue();
                    break;
                }
            case "NOTIFY_TYPE_ALARM":
                new JamBaseBluetoothSequencer.QueueMe().setBytes(alertMessage.getAlertMessageOld(str, AlertMessage.AlertCategory.Call)).setDescription("Sent glucose alert: " + str).setQueueWriteCharacterstic(alertMessage.getCharacteristicUUID()).expireInSeconds(30).setRunnable(new Runnable() {
                    @Override
                    public final void run() {
                        MiBandService.this.lambda$queueMessage$9();
                    }
                }).setDelayMs(0).queue();
                this.bgServiceIntent = WakeLockTrampoline.getPendingIntent(getClass(), UsbId.VENDOR_FTDI, "glucose_after");
                JoH.wakeUpIntent(xdrip.getAppContext(), 10000L, this.bgServiceIntent);
                break;
        }
        Inevitable.task("miband-s-queue", 200L, new Runnable() {
            @Override
            public final void run() {
                MiBandService.this.lambda$queueMessage$10();
            }
        });
    }

    public void lambda$queueMessage$8() {
        this.isWaitingCallResponce = true;
    }

    public void lambda$queueMessage$9() {
        this.isWaitingSnoozeResponce = Boolean.TRUE;
    }

    public void lambda$queueMessage$10() {
        changeState(this.mState.next());
    }

    @SuppressLint({"CheckResult"})
    private void authPhase() {
        extendWakeLock(30000L);
        final RxBleConnection rxBleConnection = this.I.connection;
        UserError.Log.d(this.TAG, "Authorizing");
        if (this.I.connection == null) {
            UserError.Log.d(this.TAG, "Cannot enable as connection is null!");
            return;
        }
        String persistentAuthKey = MiBand.getPersistentAuthKey();
        if (MiBand.getMibandType() == MiBand.MiBandType.MI_BAND4 && persistentAuthKey.isEmpty()) {
            persistentAuthKey = MiBand.getAuthKey();
            if (persistentAuthKey.isEmpty()) {
                persistentAuthKey = AuthMessages.getAuthCodeFromFilesSystem(MiBand.getMac());
            }
            if (!AuthMessages.isValidAuthKey(persistentAuthKey).booleanValue()) {
                JoH.static_toast_long("Wrong miband authorization key, please recheck a key and try to reconnect again");
                changeState("Authorization failed");
                return;
            }
            MiBand.setAuthKey(persistentAuthKey);
        }
        if (!AuthMessages.isValidAuthKey(persistentAuthKey).booleanValue()) {
            persistentAuthKey = "";
        }
        UserError.Log.d(this.TAG, "authKey: " + persistentAuthKey);
        this.authorisation = new AuthMessages(MiBand.getMibandType(), persistentAuthKey);
        UserError.Log.d(this.TAG, "localKey: " + JoH.bytesToHex(this.authorisation.getLocalKey()));
        this.authSubscription = new Subscription(rxBleConnection.setupNotification(this.authorisation.getCharacteristicUUID()).timeout(20L, TimeUnit.SECONDS).doOnNext(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$authPhase$15(rxBleConnection, (Observable) obj);
            }
        }).flatMap(new Function() {
            public final Object apply(Object obj) {
                ObservableSource lambda$authPhase$16;
                lambda$authPhase$16 = MiBandService.lambda$authPhase$16((Observable) obj);
                return lambda$authPhase$16;
            }
        }).subscribe(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$authPhase$17(rxBleConnection, (byte[]) obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$authPhase$18((Throwable) obj);
            }
        }));
    }

    public void lambda$authPhase$15(RxBleConnection rxBleConnection, Observable observable) throws Exception {
        UserError.Log.d(this.TAG, "Notification for auth enabled");
        if (MiBand.isAuthenticated()) {
            rxBleConnection.writeCharacteristic(this.authorisation.getCharacteristicUUID(), this.authorisation.getAuthKeyRequest()).subscribe(new Consumer() {
                public final void accept(Object obj) {
                    MiBandService.this.lambda$authPhase$11((byte[]) obj);
                }
            }, new Consumer() {
                public final void accept(Object obj) {
                    MiBandService.this.lambda$authPhase$12((Throwable) obj);
                }
            });
        } else {
            rxBleConnection.writeCharacteristic(this.authorisation.getCharacteristicUUID(), this.authorisation.getAuthCommand()).subscribe(new Consumer() {
                public final void accept(Object obj) {
                    MiBandService.this.lambda$authPhase$13((byte[]) obj);
                }
            }, new Consumer() {
                public final void accept(Object obj) {
                    MiBandService.this.lambda$authPhase$14((Throwable) obj);
                }
            });
        }
    }

    public void lambda$authPhase$11(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote getAuthKeyRequest: " + JoH.bytesToHex(bArr));
    }

    public void lambda$authPhase$12(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not getAuthKeyRequest: " + th);
    }

    public void lambda$authPhase$13(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote getAuthCommand, got: " + JoH.bytesToHex(bArr));
    }

    public void lambda$authPhase$14(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not write getAuthCommand: " + th);
    }

    public void lambda$authPhase$17(RxBleConnection rxBleConnection, byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Received auth notification bytes: " + JoH.bytesToHex(bArr));
        ProcessAuthCommands(rxBleConnection, bArr);
    }

    public void lambda$authPhase$18(Throwable th) throws Exception {
        UserError.Log.d(this.TAG, "Throwable in Record Notification: " + th);
        if (th instanceof BleCharacteristicNotFoundException) {
            UserError.Log.d(this.TAG, "Characteristic not found for notification");
        } else if (th instanceof BleCannotSetCharacteristicNotificationException) {
            UserError.Log.e(this.TAG, "Problems setting notifications - disconnecting");
        } else if (th instanceof BleDisconnectedException) {
            UserError.Log.d(this.TAG, "Disconnected while enabling notifications");
        } else if ((th instanceof TimeoutException) && !MiBand.isAuthenticated()) {
            UserError.Log.d(this.TAG, "MiBand authentication failed due to authentication timeout. When your Mi Band vibrates and blinks, tap it a few times in a row.");
            JoH.static_toast_long("MiBand authentication failed due to authentication timeout. When your Mi Band vibrates and blinks, tap it a few times in a row.");
        }
        Subscription subscription = this.authSubscription;
        if (subscription != null) {
            subscription.unsubscribe();
        }
        changeState("Closing");
    }

    @SuppressLint({"CheckResult"})
    private void ProcessAuthCommands(RxBleConnection rxBleConnection, byte[] bArr) {
        byte b = bArr[0];
        if (b == 16 && bArr[1] == 1 && (bArr[2] & 15) == 1) {
            rxBleConnection.writeCharacteristic(this.authorisation.getCharacteristicUUID(), this.authorisation.getAuthKeyRequest()).subscribe(new Consumer() {
                public final void accept(Object obj) {
                    MiBandService.this.lambda$ProcessAuthCommands$19((byte[]) obj);
                }
            }, new Consumer() {
                public final void accept(Object obj) {
                    MiBandService.this.lambda$ProcessAuthCommands$20((Throwable) obj);
                }
            });
            return;
        }
        if (b == 16 && (bArr[1] & 15) == 2 && bArr[2] == 1) {
            try {
                rxBleConnection.writeCharacteristic(this.authorisation.getCharacteristicUUID(), this.authorisation.calculateAuthReply(Arrays.copyOfRange(bArr, 3, 19))).subscribe(new Consumer() {
                    public final void accept(Object obj) {
                        MiBandService.this.lambda$ProcessAuthCommands$21((byte[]) obj);
                    }
                }, new Consumer() {
                    public final void accept(Object obj) {
                        MiBandService.this.lambda$ProcessAuthCommands$22((Throwable) obj);
                    }
                });
                return;
            } catch (Exception e) {
                JoH.static_toast_long(e.getMessage());
                UserError.Log.e(this.TAG, e.getMessage());
                changeState("Authorization failed");
                return;
            }
        }
        if (b == 16 && (bArr[1] & 15) == 3 && bArr[2] == 1) {
            this.isNeedToAuthenticate = Boolean.FALSE;
            if (MiBand.getPersistentAuthMac().isEmpty()) {
                MiBand.setPersistentAuthMac(MiBand.getMac());
                MiBand.setPersistentAuthKey(JoH.bytesToHex(this.authorisation.getLocalKey()), MiBand.getPersistentAuthMac());
                JoH.static_toast_long("MiBand was successfully authenticated");
                UserError.Log.e(this.TAG, "MiBand was successfully authenticated");
            }
            Subscription subscription = this.authSubscription;
            if (subscription != null) {
                subscription.unsubscribe();
            }
            changeNextState();
            return;
        }
        if (b == 16) {
            byte b2 = bArr[2];
            if ((b2 & 15) == 4 || b2 == 81 || b2 == 8) {
                MiBand.setPersistentAuthKey("", MiBand.getPersistentAuthMac());
                Subscription subscription2 = this.authSubscription;
                if (subscription2 != null) {
                    subscription2.unsubscribe();
                }
                JoH.static_toast_long("Cannot authorize miband, please recheck Auth code");
                UserError.Log.e(this.TAG, "Cannot authorize miband, please recheck Auth code");
                changeState("Authorization failed");
            }
        }
    }

    public void lambda$ProcessAuthCommands$19(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote OPCODE_AUTH_REQ1: " + JoH.bytesToHex(bArr));
    }

    public void lambda$ProcessAuthCommands$20(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not write OPCODE_AUTH_REQ1: " + th);
    }

    public void lambda$ProcessAuthCommands$21(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote OPCODE_AUTH_REQ2: " + JoH.bytesToHex(bArr));
    }

    public void lambda$ProcessAuthCommands$22(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not write OPCODE_AUTH_REQ2: " + th);
    }

    @SuppressLint({"CheckResult"})
    private void installWatchface() {
        RxBleConnection rxBleConnection = this.I.connection;
        UserError.Log.d(this.TAG, "Install WatchFace");
        if (this.I.connection == null) {
            UserError.Log.d(this.TAG, "Cannot enable as connection is null!");
            return;
        }
        try {
            byte[] genWatchFace = new WatchFaceGenerator(getBaseContext().getAssets()).genWatchFace();
            if (genWatchFace != null && genWatchFace.length != 0) {
                this.firmware = new FirmwareOperations(genWatchFace);
                UserError.Log.d(this.TAG, "Begin uploading Watchface, lenght: " + this.firmware.getSize());
                UserError.Log.d(this.TAG, "Requesting to enable notifications for installWatchface");
                this.watchfaceSubscription = new Subscription(rxBleConnection.setupNotification(this.firmware.getFirmwareCharacteristicUUID()).timeout(400L, TimeUnit.SECONDS).doOnNext(new Consumer() {
                    public final void accept(Object obj) {
                        MiBandService.this.lambda$installWatchface$23((Observable) obj);
                    }
                }).flatMap(new Function() {
                    public final Object apply(Object obj) {
                        ObservableSource lambda$installWatchface$24;
                        lambda$installWatchface$24 = MiBandService.lambda$installWatchface$24((Observable) obj);
                        return lambda$installWatchface$24;
                    }
                }).subscribe(new Consumer() {
                    public final void accept(Object obj) {
                        MiBandService.this.lambda$installWatchface$25((byte[]) obj);
                    }
                }, new Consumer() {
                    public final void accept(Object obj) {
                        MiBandService.this.lambda$installWatchface$26((Throwable) obj);
                    }
                }));
                return;
            }
            resetFirmwareState(Boolean.FALSE, "Empty image");
        } catch (Exception e) {
            resetFirmwareState(Boolean.FALSE, "FirmwareOperations error " + e.getMessage());
        }
    }

    public void lambda$installWatchface$23(Observable observable) throws Exception {
        UserError.Log.d(this.TAG, "Notification for firmware enabled");
        this.firmware.nextSequence();
        processFirmwareCommands(null, true);
    }

    public void lambda$installWatchface$25(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Received firmware notification bytes: " + JoH.bytesToHex(bArr));
        processFirmwareCommands(bArr, false);
    }

    public void lambda$installWatchface$26(Throwable th) throws Exception {
        UserError.Log.d(this.TAG, "Throwable in firmware Notification: " + th);
        if (th instanceof BleCharacteristicNotFoundException) {
            UserError.Log.d(this.TAG, "Characteristic not found for notification");
        } else if (th instanceof BleCannotSetCharacteristicNotificationException) {
            UserError.Log.e(this.TAG, "Problems setting notifications - disconnecting");
        } else if (th instanceof BleDisconnectedException) {
            UserError.Log.d(this.TAG, "Disconnected while enabling notifications");
        } else if (th instanceof TimeoutException) {
            UserError.Log.d(this.TAG, "Timeout");
        }
        resetFirmwareState(Boolean.FALSE);
    }

    @SuppressLint({"CheckResult"})
    private void processFirmwareCommands(byte[] bArr, boolean z) {
        String str;
        Boolean bool;
        RxBleConnection rxBleConnection = this.I.connection;
        FirmwareOperations.SequenceType sequence = this.firmware.getSequence();
        UserError.Log.d(this.TAG, "processFirmwareCommands: " + JoH.bytesToHex(bArr) + ": seq:" + sequence.toString());
        if (z) {
            int i = AnonymousClass2.$SwitchMap$com$eveningoutpost$dexdrip$watch$miband$Firmware$FirmwareOperations$SequenceType[sequence.ordinal()];
            if (i != 1) {
                if (i != 2) {
                    return;
                }
                rxBleConnection.writeCharacteristic(this.firmware.getFirmwareCharacteristicUUID(), this.firmware.prepareFWUploadInitCommand()).subscribe(new Consumer() {
                    public final void accept(Object obj) {
                        MiBandService.this.lambda$processFirmwareCommands$29((byte[]) obj);
                    }
                }, new Consumer() {
                    public final void accept(Object obj) {
                        MiBandService.this.lambda$processFirmwareCommands$30((Throwable) obj);
                    }
                });
                this.firmware.nextSequence();
                return;
            }
            this.isNeedToRestoreNightMode = Boolean.TRUE;
            DisplayControllMessageMiband3_4 displayControllMessageMiband3_4 = new DisplayControllMessageMiband3_4();
            Calendar calendar = Calendar.getInstance();
            calendar.set(11, 0);
            calendar.set(12, 0);
            Date time = calendar.getTime();
            rxBleConnection.writeCharacteristic(displayControllMessageMiband3_4.getCharacteristicUUID(), displayControllMessageMiband3_4.setNightModeCmd(DisplayControllMessageMiband3_4.NightMode.Sheduled, time, time)).subscribe(new Consumer() {
                public final void accept(Object obj) {
                    MiBandService.this.lambda$processFirmwareCommands$27((byte[]) obj);
                }
            }, new Consumer() {
                public final void accept(Object obj) {
                    MiBandService.this.lambda$processFirmwareCommands$28((Throwable) obj);
                }
            });
            return;
        }
        if (bArr.length != 3 && bArr.length != 11) {
            UserError.Log.e(this.TAG, "Notifications should be 3 or 11 bytes long.");
            return;
        }
        byte b = bArr[2];
        boolean z2 = b == 1;
        if (bArr[0] == 16 && z2) {
            try {
                byte b2 = bArr[1];
                if (b2 != 1) {
                    if (b2 == 3) {
                        sendFirmwareData();
                    } else if (b2 == 4) {
                        this.firmware.nextSequence();
                        if (this.firmware.getFirmwareType() != FirmwareOperations.FirmwareType.FIRMWARE) {
                            UserError.Log.e(this.TAG, "Watch Face has been installed successfully");
                            resetFirmwareState(Boolean.TRUE);
                        }
                    } else if (b2 == 5) {
                        UserError.Log.e(this.TAG, "Reboot command successfully sent.");
                        resetFirmwareState(Boolean.TRUE);
                    } else {
                        resetFirmwareState(Boolean.FALSE, "Unexpected response during firmware update");
                    }
                } else if (sequence == FirmwareOperations.SequenceType.TRANSFER_FW_START) {
                    rxBleConnection.writeCharacteristic(this.firmware.getFirmwareCharacteristicUUID(), this.firmware.getFirmwareStartCommand()).subscribe(new Consumer() {
                        public final void accept(Object obj) {
                            MiBandService.this.lambda$processFirmwareCommands$31((byte[]) obj);
                        }
                    }, new Consumer() {
                        public final void accept(Object obj) {
                            MiBandService.this.lambda$processFirmwareCommands$32((Throwable) obj);
                        }
                    });
                    this.firmware.nextSequence();
                } else if (sequence == FirmwareOperations.SequenceType.TRANSFER_SEND_WF_INFO) {
                    rxBleConnection.writeCharacteristic(this.firmware.getFirmwareCharacteristicUUID(), this.firmware.sendFwInfo()).subscribe(new Consumer() {
                        public final void accept(Object obj) {
                            MiBandService.this.lambda$processFirmwareCommands$33((byte[]) obj);
                        }
                    }, new Consumer() {
                        public final void accept(Object obj) {
                            MiBandService.this.lambda$processFirmwareCommands$34((Throwable) obj);
                        }
                    });
                    this.firmware.nextSequence();
                }
                return;
            } catch (Exception unused) {
                resetFirmwareState(Boolean.FALSE);
                return;
            }
        }
        Boolean bool2 = Boolean.FALSE;
        if (b == 34) {
            bool = Boolean.TRUE;
            str = "Cannot upload watchface, low battery, please charge device";
        } else {
            if (b == 33) {
                str = "Cannot upload watchface, timer running on band";
            } else if (b == 34) {
                str = "Cannot upload watchface, call in progress";
            } else {
                str = "Unexpected notification during firmware update:" + JoH.bytesToHex(bArr);
            }
            bool = bool2;
        }
        resetFirmwareState(bool2, str);
        if (bool.booleanValue()) {
            emptyQueue();
            JoH.startService(MiBandService.class, "function", "update_bg_as_notification");
            changeState("Sleeping");
        }
    }

    static class AnonymousClass2 {
        static final int[] $SwitchMap$com$eveningoutpost$dexdrip$watch$miband$Firmware$FirmwareOperations$SequenceType;

        static {
            int[] iArr = new int[FirmwareOperations.SequenceType.values().length];
            $SwitchMap$com$eveningoutpost$dexdrip$watch$miband$Firmware$FirmwareOperations$SequenceType = iArr;
            try {
                iArr[FirmwareOperations.SequenceType.SET_NIGHTMODE.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$watch$miband$Firmware$FirmwareOperations$SequenceType[FirmwareOperations.SequenceType.PREPARE_UPLOAD.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
        }
    }

    public void lambda$processFirmwareCommands$27(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote nigntmode, got: " + JoH.bytesToHex(bArr));
        this.firmware.nextSequence();
        processFirmwareCommands(null, true);
    }

    public void lambda$processFirmwareCommands$28(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not write nigntmode: " + th);
        this.firmware.nextSequence();
        processFirmwareCommands(null, true);
    }

    public void lambda$processFirmwareCommands$29(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote prepareFWUploadInitCommand, got: " + JoH.bytesToHex(bArr));
    }

    public void lambda$processFirmwareCommands$30(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not write prepareFWUploadInitCommand: " + th);
        resetFirmwareState(Boolean.FALSE);
    }

    public void lambda$processFirmwareCommands$31(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote Start command, got: " + JoH.bytesToHex(bArr));
    }

    public void lambda$processFirmwareCommands$32(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not write Start command: " + th);
        resetFirmwareState(Boolean.FALSE);
    }

    public void lambda$processFirmwareCommands$33(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote sendFwInfo, got: " + JoH.bytesToHex(bArr));
    }

    public void lambda$processFirmwareCommands$34(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not write firmware info: " + th);
        resetFirmwareState(Boolean.FALSE);
    }

    private void resetFirmwareState(Boolean bool) {
        resetFirmwareState(bool, null);
    }

    private void resetFirmwareState(Boolean bool, String str) {
        Subscription subscription = this.watchfaceSubscription;
        if (subscription != null) {
            subscription.unsubscribe();
            this.watchfaceSubscription = null;
        }
        if (str == null) {
            if (!bool.booleanValue()) {
                str = xdrip.getAppContext().getResources().getString(2131755827);
            } else {
                str = xdrip.getAppContext().getResources().getString(2131755828);
            }
        }
        UserError.Log.d(this.TAG, "resetFirmwareState result:" + bool + ":" + str);
        if (this.isNeedToRestoreNightMode.booleanValue()) {
            JoH.threadSleep(7000L);
            setNightMode();
        }
        if (bool.booleanValue()) {
            changeNextState();
        } else {
            changeState("Sleeping");
        }
    }

    private void sendFirmwareData() {
        byte[] bytes = this.firmware.getBytes();
        int size = this.firmware.getSize();
        int mtu = this.I.connection.getMtu();
        if (!MiBandEntry.isNeedToDisableHightMTU()) {
            this.firmware.setMTU(mtu);
        }
        int packeLenght = this.firmware.getPackeLenght();
        UserError.Log.d(this.TAG, "Firmware packet lengh: " + packeLenght);
        int i = size / packeLenght;
        int i2 = 0;
        for (int i3 = 0; i3 < i; i3++) {
            int i4 = i3 * packeLenght;
            byte[] copyOfRange = Arrays.copyOfRange(bytes, i4, i4 + packeLenght);
            sendFirmwareCommand(this.firmware.getFirmwareDataCharacteristicUUID(), copyOfRange, "Chunk:" + i3).queue();
            i2 += packeLenght;
            int i5 = (int) ((((float) i2) / ((float) size)) * 100.0f);
            if (i3 > 0 && i3 % 30 == 0) {
                sendFirmwareCommand(this.firmware.getFirmwareCharacteristicUUID(), this.firmware.sendSync(), "Sync " + i5 + "%").queue();
            }
        }
        if (i2 < size) {
            sendFirmwareCommand(this.firmware.getFirmwareDataCharacteristicUUID(), Arrays.copyOfRange(bytes, i * packeLenght, size), "Last chunk").queue();
        }
        sendFirmwareCommand(this.firmware.getFirmwareCharacteristicUUID(), this.firmware.sendChecksum(), "sendChecksum").setRunnable(new Runnable() {
            @Override
            public void run() {
                MiBandService.this.firmware.nextSequence();
            }
        }).send();
    }

    JamBaseBluetoothSequencer.QueueMe sendFirmwareCommand(UUID uuid, byte[] bArr, String str) {
        return new JamBaseBluetoothSequencer.QueueMe().setBytes(bArr).setDescription(str).setQueueWriteCharacterstic(uuid).expireInSeconds(BgReading.BG_READING_MAXIMUM_VALUE).setDelayMs(0);
    }

    private void setNightMode() {
        Date date;
        Date date2;
        UserError.Log.d(this.TAG, "Restore night mode");
        DisplayControllMessageMiband3_4.NightMode nightMode = DisplayControllMessageMiband3_4.NightMode.Off;
        if (MiBandEntry.isNightModeEnabled()) {
            nightMode = DisplayControllMessageMiband3_4.NightMode.Sheduled;
            date = MiBandEntry.getNightModeStart();
            date2 = MiBandEntry.getNightModeEnd();
        } else {
            date = null;
            date2 = null;
        }
        RxBleConnection rxBleConnection = this.I.connection;
        DisplayControllMessageMiband3_4 displayControllMessageMiband3_4 = new DisplayControllMessageMiband3_4();
        rxBleConnection.writeCharacteristic(displayControllMessageMiband3_4.getCharacteristicUUID(), displayControllMessageMiband3_4.setNightModeCmd(nightMode, date, date2)).subscribe(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$setNightMode$35((byte[]) obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$setNightMode$36((Throwable) obj);
            }
        });
    }

    public void lambda$setNightMode$35(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Wrote nightmode");
        this.isNeedToRestoreNightMode = Boolean.FALSE;
    }

    public void lambda$setNightMode$36(Throwable th) throws Exception {
        UserError.Log.e(this.TAG, "Could not write nightmode: " + th);
    }

    private void handleHeartrate(byte[] bArr) {
        if (bArr.length == 2 && bArr[0] == 0) {
            int i = bArr[1] & 255;
            UserError.Log.d(this.TAG, "heart rate: " + i);
            HeartRate.create(JoH.tsl(), i, 1);
        }
    }

    @SuppressLint({"CheckResult"})
    private void enableNotification() {
        UserError.Log.d(this.TAG, "enableNotifications called");
        if (this.I.connection == null) {
            UserError.Log.d(this.TAG, "Cannot enable as connection is null!");
            return;
        }
        enableHeartRateNotification();
        if (this.I.isNotificationEnabled) {
            UserError.Log.d(this.TAG, "Notifications already enabled");
            changeNextState();
            return;
        }
        Subscription subscription = this.notifSubscriptionDeviceEvent;
        if (subscription != null) {
            subscription.unsubscribe();
        }
        Subscription subscription2 = this.notifSubscriptionHeartRateMeasurement;
        if (subscription2 != null) {
            subscription2.unsubscribe();
        }
        UserError.Log.d(this.TAG, "Requesting to enable device event notifications");
        this.I.connection.requestMtu(247).subscribe();
        this.notifSubscriptionDeviceEvent = new Subscription(this.I.connection.setupNotification(Const.UUID_CHARACTERISTIC_DEVICEEVENT).doOnNext(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$enableNotification$37((Observable) obj);
            }
        }).flatMap(new Function() {
            public final Object apply(Object obj) {
                ObservableSource lambda$enableNotification$38;
                lambda$enableNotification$38 = MiBandService.lambda$enableNotification$38((Observable) obj);
                return lambda$enableNotification$38;
            }
        }).observeOn(Schedulers.newThread()).subscribe(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$enableNotification$39((byte[]) obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$enableNotification$40((Throwable) obj);
            }
        }));
    }

    public void lambda$enableNotification$37(Observable observable) throws Exception {
        this.I.isNotificationEnabled = true;
        changeNextState();
    }

    public void lambda$enableNotification$39(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Received device notification bytes: " + JoH.bytesToHex(bArr));
        handleDeviceEvent(bArr);
    }

    public void lambda$enableNotification$40(Throwable th) throws Exception {
        UserError.Log.d(this.TAG, "Throwable in Record Notification: " + th);
        this.I.isNotificationEnabled = false;
        if (th instanceof BleCharacteristicNotFoundException) {
            UserError.Log.d(this.TAG, "Characteristic not found for notification");
            changeNextState();
        } else {
            UserError.Log.d(this.TAG, "Disconnected exception");
            this.isNeedToAuthenticate = Boolean.TRUE;
            this.messageQueue.clear();
            changeState("Closing");
        }
    }

    private void enableHeartRateNotification() {
        if (MiBandEntry.isNeedToCollectHR()) {
            if (this.notifSubscriptionHeartRateMeasurement != null) {
                return;
            }
        } else {
            Subscription subscription = this.notifSubscriptionHeartRateMeasurement;
            if (subscription != null) {
                subscription.unsubscribe();
                this.notifSubscriptionHeartRateMeasurement = null;
                return;
            }
        }
        UserError.Log.d(this.TAG, "Requesting to enable HR notifications");
        this.notifSubscriptionHeartRateMeasurement = new Subscription(this.I.connection.setupNotification(Const.UUID_CHAR_HEART_RATE_MEASUREMENT).flatMap(new Function() {
            public final Object apply(Object obj) {
                ObservableSource lambda$enableHeartRateNotification$41;
                lambda$enableHeartRateNotification$41 = MiBandService.lambda$enableHeartRateNotification$41((Observable) obj);
                return lambda$enableHeartRateNotification$41;
            }
        }).observeOn(Schedulers.newThread()).subscribe(new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$enableHeartRateNotification$42((byte[]) obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                MiBandService.this.lambda$enableHeartRateNotification$43((Throwable) obj);
            }
        }));
    }

    public void lambda$enableHeartRateNotification$42(byte[] bArr) throws Exception {
        UserError.Log.d(this.TAG, "Received HR notification bytes: " + JoH.bytesToHex(bArr));
        handleHeartrate(bArr);
    }

    public void lambda$enableHeartRateNotification$43(Throwable th) throws Exception {
        this.notifSubscriptionHeartRateMeasurement.unsubscribe();
        this.notifSubscriptionHeartRateMeasurement = null;
        UserError.Log.d(this.TAG, "HR Throwable in Record Notification: " + th);
        if (th instanceof BleCharacteristicNotFoundException) {
            UserError.Log.d(this.TAG, "HR Characteristic not found for notification");
        } else {
            UserError.Log.d(this.TAG, "HR Disconnected exception");
        }
    }

    @Override
    protected synchronized boolean automata() {
        char c;
        UserError.Log.d(this.TAG, "Automata called in" + this.TAG);
        extendWakeLock(2000L);
        if (shouldServiceRun()) {
            String str = this.I.state;
            switch (str.hashCode()) {
                case -2014394435:
                    if (str.equals("Updating Settings")) {
                        c = 6;
                        break;
                    }
                    c = 65535;
                    break;
                case -1806607458:
                    if (str.equals("Getting model name")) {
                        c = 1;
                        break;
                    }
                    c = 65535;
                    break;
                case -1728014770:
                    if (str.equals("Watchface installation")) {
                        c = '\b';
                        break;
                    }
                    c = 65535;
                    break;
                case -1321219637:
                    if (str.equals("Sleeping")) {
                        c = 14;
                        break;
                    }
                    c = 65535;
                    break;
                case -927184824:
                    if (str.equals("Enable notification")) {
                        c = 5;
                        break;
                    }
                    c = 65535;
                    break;
                case -827702216:
                    if (str.equals("Getting software revision")) {
                        c = 2;
                        break;
                    }
                    c = 65535;
                    break;
                case -684798986:
                    if (str.equals("Watchface installation in progress")) {
                        c = '\t';
                        break;
                    }
                    c = 65535;
                    break;
                case -235759507:
                    if (str.equals("Initializing")) {
                        c = 0;
                        break;
                    }
                    c = 65535;
                    break;
                case 61311588:
                    if (str.equals("Authorize phase")) {
                        c = 4;
                        break;
                    }
                    c = 65535;
                    break;
                case 327238616:
                    if (str.equals("Queue message")) {
                        c = '\r';
                        break;
                    }
                    c = 65535;
                    break;
                case 622030557:
                    if (str.equals("Setting Time")) {
                        c = 7;
                        break;
                    }
                    c = 65535;
                    break;
                case 1578058244:
                    if (str.equals("Watchface installation finished")) {
                        c = '\n';
                        break;
                    }
                    c = 65535;
                    break;
                case 1789203037:
                    if (str.equals("Getting battery info")) {
                        c = '\f';
                        break;
                    }
                    c = 65535;
                    break;
                case 1885436661:
                    if (str.equals("Authenticate")) {
                        c = 3;
                        break;
                    }
                    c = 65535;
                    break;
                case 2021313932:
                    if (str.equals("Closed")) {
                        c = 15;
                        break;
                    }
                    c = 65535;
                    break;
                case 2115964239:
                    if (str.equals("Vibrate")) {
                        c = 11;
                        break;
                    }
                    c = 65535;
                    break;
                default:
                    c = 65535;
                    break;
            }
            switch (c) {
                case 0:
                    changeNextState();
                    break;
                case 1:
                    cancelRetryTimer();
                    if (this.isNeedToRestoreNightMode.booleanValue()) {
                        setNightMode();
                    }
                    if (MiBand.getModel().isEmpty()) {
                        getModelName();
                        break;
                    } else {
                        changeNextState();
                        break;
                    }
                case 2:
                    if (!MiBand.getVersion().isEmpty() && !this.isNeedToCheckRevision.booleanValue()) {
                        changeNextState();
                        break;
                    }
                    getSoftwareRevision();
                    break;
                case 3:
                    if (this.isNeedToAuthenticate.booleanValue()) {
                        changeNextState();
                        break;
                    } else {
                        changeState("Enable notification");
                        break;
                    }
                case 4:
                    authPhase();
                    break;
                case 5:
                    enableNotification();
                    break;
                case 6:
                    sendSettings();
                    changeNextState();
                    break;
                case 7:
                    if (!MiBandEntry.isNeedSendReading()) {
                        changeState("Sending Queue");
                        break;
                    } else {
                        if (this.isWaitingSnoozeResponce.booleanValue()) {
                            vibrateAlert(AlertLevelMessage.AlertLevelType.NoAlert);
                            this.isWaitingSnoozeResponce = Boolean.FALSE;
                        }
                        String str2 = this.queueItem.functionName;
                        if (MiBand.getMibandType() == MiBand.MiBandType.MI_BAND4 && !MiBandEntry.isNeedSendReadingAsNotification() && !str2.equals("update_bg_as_notification")) {
                            changeState("Watchface installation");
                            break;
                        }
                        if (!sendBG().booleanValue()) {
                            changeState("Sending Queue");
                            break;
                        } else {
                            changeState("Vibrate");
                            break;
                        }
                    }
                    break;
                case '\b':
                    installWatchface();
                    changeNextState();
                    break;
                case '\t':
                case '\n':
                    break;
                case 11:
                    if (MiBandEntry.isVibrateOnReadings() && !MiBandEntry.isNeedSendReadingAsNotification()) {
                        vibrateAlert(AlertLevelMessage.AlertLevelType.VibrateAlert);
                    }
                    changeNextState();
                    break;
                case '\f':
                    getBatteryInfo();
                    changeNextState();
                    break;
                case '\r':
                    queueMessage();
                    changeNextState();
                    break;
                case 14:
                    handleCommand();
                    break;
                case 15:
                    stopConnection();
                    return super.automata();
                default:
                    return super.automata();
            }
        } else {
            UserError.Log.d(this.TAG, "Service should not be running inside automata");
            stopSelf();
        }
        return true;
    }

    private void stopConnection() {
        this.isNeedToAuthenticate = Boolean.TRUE;
        this.isWaitingCallResponce = false;
        this.isWaitingSnoozeResponce = Boolean.FALSE;
        this.messageQueue.clear();
        setRetryTimerReal();
    }

    private boolean shouldServiceRun() {
        return MiBandEntry.isEnabled();
    }

    @Override
    protected void setRetryTimerReal() {
        if (shouldServiceRun() && MiBand.isAuthenticated()) {
            long whenToRetryNext = whenToRetryNext();
            UserError.Log.d(this.TAG, "setRetryTimerReal: Restarting in: " + (whenToRetryNext / 1000) + " seconds");
            this.I.serviceIntent = WakeLockTrampoline.getPendingIntent(getClass(), 1026, "message");
            this.I.retry_time = JoH.wakeUpIntent(xdrip.getAppContext(), whenToRetryNext, this.I.serviceIntent);
            this.I.wakeup_time = JoH.tsl() + whenToRetryNext;
            return;
        }
        UserError.Log.d(this.TAG, "Not setting retry timer as service should not be running");
    }

    private void cancelRetryTimer() {
        JoH.cancelAlarm(xdrip.getAppContext(), this.I.serviceIntent);
        this.I.wakeup_time = 0L;
    }

    private long whenToRetryNext() {
        this.I.retry_backoff = 30000L;
        return this.I.retry_backoff;
    }

    static class MiBandState extends JamBaseBluetoothSequencer.BaseState {
        MiBandState() {
        }

        void prepareInitialSequences() {
            this.sequence.clear();
            this.sequence.add("Initializing");
            this.sequence.add("Connecting");
            this.sequence.add("Getting model name");
            this.sequence.add("Getting software revision");
            this.sequence.add("Authenticate");
            this.sequence.add("Authorize phase");
            this.sequence.add("Enable notification");
        }

        void prepareFinalSequences() {
            this.sequence.add("Sending Queue");
            this.sequence.add("Getting battery info");
            this.sequence.add("Sleeping");
            this.sequence.add("Authorization failed");
        }

        void setSendReadingSequence() {
            UserError.Log.d("MiBandStateSequence", "SET UPDATE WATCHFACE DATA SEQUENCE");
            prepareInitialSequences();
            this.sequence.add("Setting Time");
            this.sequence.add("Watchface installation");
            this.sequence.add("Watchface installation in progress");
            this.sequence.add("Watchface installation finished");
            this.sequence.add("Vibrate");
            prepareFinalSequences();
        }

        void setQueueSequence() {
            UserError.Log.d("MiBandStateSequence", "SET QUEUE SEQUENCE");
            prepareInitialSequences();
            this.sequence.add("Queue message");
            prepareFinalSequences();
        }

        void setSettingsSequence() {
            UserError.Log.d("MiBandStateSequence", "SET SETTINGS SEQUENCE");
            prepareInitialSequences();
            this.sequence.add("Updating Settings");
            prepareFinalSequences();
        }
    }

    public static List<StatusItem> megaStatus() {
        String str;
        ArrayList arrayList = new ArrayList();
        JamBaseBluetoothSequencer.Inst inst = JamBaseBluetoothSequencer.Inst.get(MiBandService.class.getSimpleName());
        arrayList.add(new StatusItem("Model", MiBand.getModel()));
        arrayList.add(new StatusItem("Software version", MiBand.getVersion()));
        arrayList.add(new StatusItem("Mac address", MiBand.getMac()));
        arrayList.add(new StatusItem("Connected", inst.isConnected ? xdrip.gs(2131757071) : xdrip.gs(2131755900)));
        arrayList.add(new StatusItem("Is authenticated", MiBand.isAuthenticated() ? xdrip.gs(2131757071) : xdrip.gs(2131755900)));
        if (inst.isConnected) {
            int levelInPercent = batteryInfo.getLevelInPercent();
            if (levelInPercent == 1000) {
                str = "Unknown";
            } else {
                str = levelInPercent + "%";
            }
            arrayList.add(new StatusItem("Battery", str));
        }
        long j = inst.wakeup_time;
        if (j != 0) {
            long msTill = JoH.msTill(j);
            if (msTill > 0) {
                arrayList.add(new StatusItem("Wake Up", JoH.niceTimeScalar(msTill)));
            }
        }
        long j2 = bgWakeupTime;
        if (j2 != 0) {
            long msTill2 = JoH.msTill(j2);
            if (msTill2 > 0) {
                arrayList.add(new StatusItem("Next time update", JoH.niceTimeScalar(msTill2)));
            }
        }
        arrayList.add(new StatusItem("State", inst.state));
        int queueSize = inst.getQueueSize();
        if (queueSize > 0) {
            arrayList.add(new StatusItem("Queue", queueSize + " items"));
        }
        return arrayList;
    }
}