io.particle.android.sdk.utils.EZ Java Examples

The following examples show how to use io.particle.android.sdk.utils.EZ. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommandClient.java    From particle-android with Apache License 2.0 6 votes vote down vote up
private <T> T sendAndMaybeReceive(Command command, Class<T> responseType) throws IOException {
    log.i("Preparing to send command '" + command.getCommandName() + "'");
    String commandData = buildCommandData(command);

    BufferedSink buffer = null;
    try {
        // send command
        Socket socket = socketFactory.createSocket(ipAddress, port);
        buffer = wrapSocket(socket, DEFAULT_TIMEOUT_SECONDS);
        log.d("Writing command data");
        buffer.writeUtf8(commandData);
        buffer.flush();

        // if no response defined, just exit early.
        if (responseType.equals(Void.class)) {
            log.d("Done.");
            return null;
        }

        return readResponse(socket, responseType, DEFAULT_TIMEOUT_SECONDS);

    } finally {
        EZ.closeThisThingOrMaybeDont(buffer);
    }
}
 
Example #2
Source File: SetupStepsRunnerTask.java    From spark-setup-android with Apache License 2.0 6 votes vote down vote up
private void runSteps() throws SetupStepException, SetupProcessException {
    for (SetupStep step : steps) {

        throwIfCancelled();

        publishProgress(new StepProgress(
                step.getStepConfig().getStepId(),
                StepProgress.STARTING));

        try {
            EZ.threadSleep(1000);
            throwIfCancelled();

            step.runStep();

        } catch (SetupStepException e) {
            // give it a moment before trying again.
            EZ.threadSleep(2000);
            throw e;
        }

        publishProgress(new StepProgress(
                step.getStepConfig().getStepId(),
                StepProgress.SUCCEEDED));
    }
}
 
Example #3
Source File: WaitForDisconnectionFromDeviceStep.java    From spark-setup-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onRunStep() throws SetupStepException, SetupProcessException {
    for (int i = 0; i <= 5; i++) {
        if (isConnectedToSoftAp()) {
            // wait and try again
            EZ.threadSleep(200);
        } else {
            EZ.threadSleep(1000);
            // success, no longer connected.
            wasDisconnected = true;
            if (EZ.isUsingOlderWifiStack()) {
                // for some reason Lollipop doesn't need this??
                reenablePreviousWifi();
            }
            return;
        }
    }

    // Still connected after the above completed: fail
    throw new SetupStepException("Not disconnected from soft AP");
}
 
Example #4
Source File: EnsureSoftApNotVisible.java    From spark-setup-android with Apache License 2.0 6 votes vote down vote up
private void onStepNeverYetFulfilled() throws SetupStepException {
    for (int i = 0; i < 16; i++) {
        if (!isSoftApVisible()) {
            // it's gone!
            wasFulfilledOnce = true;
            return;
        }

        if (i % 6 == 0) {
            wifiFacade.startScan();
        }

        EZ.threadSleep(250);
    }
    throw new SetupStepException("Wi-Fi credentials appear to be incorrect or an error has occurred");
}
 
Example #5
Source File: WaitForCloudConnectivityStep.java    From spark-setup-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onRunStep() throws SetupStepException {
    // Wait for just a couple seconds for a WifiFacade connection if possible, in case we
    // flip from the soft AP, to mobile data, and then to WifiFacade in rapid succession.
    EZ.threadSleep(2000);
    int reachabilityRetries = 0;
    boolean isAPIHostReachable = checkIsApiHostAvailable();
    while (!isAPIHostReachable && reachabilityRetries <= MAX_RETRIES_REACHABILITY) {
        EZ.threadSleep(2000);
        isAPIHostReachable = checkIsApiHostAvailable();
        log.d("Checked for reachability " + reachabilityRetries + " times");
        reachabilityRetries++;
    }
    if (!isAPIHostReachable) {
        throw new SetupStepException("Unable to reach API host");
    }
}
 
Example #6
Source File: CommandClient.java    From spark-setup-android with Apache License 2.0 6 votes vote down vote up
private <T> T readResponse(Socket socket, Class<T> responseType, int timeoutValueInSeconds)
        throws IOException {
    BufferedSource buffer = Okio.buffer(Okio.source(socket));
    buffer.timeout().timeout(timeoutValueInSeconds, TimeUnit.SECONDS);

    log.d("Reading response data...");
    String line;
    do {
        // read (and throw away, for now) any headers
        line = buffer.readUtf8LineStrict();
    } while (truthy(line));

    String responseData = buffer.readUtf8();
    log.d("Command response (raw): " + CommandClientUtils.escapeJava(responseData));
    T tee = gson.fromJson(responseData, responseType);
    log.d("Command response: " + tee);
    EZ.closeThisThingOrMaybeDont(buffer);
    return tee;
}
 
Example #7
Source File: CommandClient.java    From spark-setup-android with Apache License 2.0 6 votes vote down vote up
private <T> T sendAndMaybeReceive(Command command, Class<T> responseType) throws IOException {
    log.i("Preparing to send command '" + command.getCommandName() + "'");
    String commandData = buildCommandData(command);

    BufferedSink buffer = null;
    try {
        // send command
        Socket socket = socketFactory.createSocket(ipAddress, port);
        buffer = wrapSocket(socket, DEFAULT_TIMEOUT_SECONDS);
        log.d("Writing command data");
        buffer.writeUtf8(commandData);
        buffer.flush();

        // if no response defined, just exit early.
        if (responseType.equals(Void.class)) {
            log.d("Done.");
            return null;
        }

        return readResponse(socket, responseType, DEFAULT_TIMEOUT_SECONDS);

    } finally {
        EZ.closeThisThingOrMaybeDont(buffer);
    }
}
 
Example #8
Source File: ParticleCloudException.java    From spark-sdk-android with Apache License 2.0 6 votes vote down vote up
private String loadBody() {
    if (httpBodyInputStream == null) {
        return null;
    }
    BufferedSource buffer = null;
    try {
        buffer = Okio.buffer(Okio.source(httpBodyInputStream));
        return buffer.readUtf8();

    } catch (IOException e) {
        log.i("Error reading HTTP response body: ", e);
        return null;

    } finally {
        EZ.closeThisThingOrMaybeDont(buffer);
    }
}
 
Example #9
Source File: ParticleAccessToken.java    From spark-sdk-android with Apache License 2.0 6 votes vote down vote up
private void onExpiration() {
    log.d("Entering onExpiration()");
    this.expirationRunnable = null;

    if (this.delegate == null) {
        log.w("Token expiration delegate is null");
        this.accessToken = null;
        return;
    }

    // ensure that we don't call accessTokenExpiredAt() on the main thread, since
    // the delegate (in the default impl) will make a call to try logging back
    // in, but making network calls on the main thread is doubleplus ungood.
    // (It'll throw an exception if you even try this, as well it should!)
    EZ.runAsync(() -> delegate.accessTokenExpiredAt(ParticleAccessToken.this, expiryDate));
}
 
Example #10
Source File: ParticleCloudException.java    From particle-android with Apache License 2.0 6 votes vote down vote up
private String loadBody() {
    if (httpBodyInputStream == null) {
        return null;
    }
    BufferedSource buffer = null;
    try {
        buffer = Okio.buffer(Okio.source(httpBodyInputStream));
        return buffer.readUtf8();

    } catch (IOException e) {
        log.i("Error reading HTTP response body: ", e);
        return null;

    } finally {
        EZ.closeThisThingOrMaybeDont(buffer);
    }
}
 
Example #11
Source File: ParticleAccessToken.java    From particle-android with Apache License 2.0 6 votes vote down vote up
private void onExpiration() {
    log.d("Entering onExpiration()");
    this.expirationRunnable = null;

    if (this.delegate == null) {
        log.w("Token expiration delegate is null");
        this.accessToken = null;
        return;
    }

    // ensure that we don't call accessTokenExpiredAt() on the main thread, since
    // the delegate (in the default impl) will make a call to try logging back
    // in, but making network calls on the main thread is doubleplus ungood.
    // (It'll throw an exception if you even try this, as well it should!)
    EZ.runAsync(() -> delegate.accessTokenExpiredAt(ParticleAccessToken.this, expiryDate));
}
 
Example #12
Source File: SetupStepsRunnerTask.java    From particle-android with Apache License 2.0 6 votes vote down vote up
private void runSteps() throws SetupStepException, SetupProcessException {
    for (SetupStep step : steps) {

        throwIfCancelled();

        publishProgress(new StepProgress(
                step.getStepConfig().getStepId(),
                StepProgress.STARTING));

        try {
            EZ.threadSleep(1000);
            throwIfCancelled();

            step.runStep();

        } catch (SetupStepException e) {
            // give it a moment before trying again.
            EZ.threadSleep(2000);
            throw e;
        }

        publishProgress(new StepProgress(
                step.getStepConfig().getStepId(),
                StepProgress.SUCCEEDED));
    }
}
 
Example #13
Source File: WaitForDisconnectionFromDeviceStep.java    From particle-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onRunStep() throws SetupStepException, SetupProcessException {
    for (int i = 0; i <= 5; i++) {
        if (isConnectedToSoftAp()) {
            // wait and try again
            EZ.threadSleep(200);
        } else {
            EZ.threadSleep(1000);
            // success, no longer connected.
            wasDisconnected = true;
            if (EZ.isUsingOlderWifiStack()) {
                // for some reason Lollipop doesn't need this??
                reenablePreviousWifi();
            }
            return;
        }
    }

    // Still connected after the above completed: fail
    throw new SetupStepException("Not disconnected from soft AP");
}
 
Example #14
Source File: EnsureSoftApNotVisible.java    From particle-android with Apache License 2.0 6 votes vote down vote up
private void onStepNeverYetFulfilled() throws SetupStepException {
    for (int i = 0; i < 16; i++) {
        if (!isSoftApVisible()) {
            // it's gone!
            wasFulfilledOnce = true;
            return;
        }

        if (i % 6 == 0) {
            wifiFacade.startScan();
        }

        EZ.threadSleep(250);
    }
    throw new SetupStepException("Wi-Fi credentials appear to be incorrect or an error has occurred");
}
 
Example #15
Source File: WaitForCloudConnectivityStep.java    From particle-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onRunStep() throws SetupStepException {
    // Wait for just a couple seconds for a WifiFacade connection if possible, in case we
    // flip from the soft AP, to mobile data, and then to WifiFacade in rapid succession.
    EZ.threadSleep(2000);
    int reachabilityRetries = 0;
    boolean isAPIHostReachable = checkIsApiHostAvailable();
    while (!isAPIHostReachable && reachabilityRetries <= MAX_RETRIES_REACHABILITY) {
        EZ.threadSleep(2000);
        isAPIHostReachable = checkIsApiHostAvailable();
        log.d("Checked for reachability " + reachabilityRetries + " times");
        reachabilityRetries++;
    }
    if (!isAPIHostReachable) {
        throw new SetupStepException("Unable to reach API host");
    }
}
 
Example #16
Source File: CommandClient.java    From particle-android with Apache License 2.0 6 votes vote down vote up
private <T> T readResponse(Socket socket, Class<T> responseType, int timeoutValueInSeconds)
        throws IOException {
    BufferedSource buffer = Okio.buffer(Okio.source(socket));
    buffer.timeout().timeout(timeoutValueInSeconds, TimeUnit.SECONDS);

    log.d("Reading response data...");
    String line;
    do {
        // read (and throw away, for now) any headers
        line = buffer.readUtf8LineStrict();
    } while (truthy(line));

    String responseData = buffer.readUtf8();
    log.d("Command response (raw): " + CommandClientUtils.escapeJava(responseData));
    T tee;
    try {
        tee = gson.fromJson(responseData, responseType);
    } catch (Exception ex) {
        throw new IOException(ex);
    }

    log.d("Command response: " + tee);
    EZ.closeThisThingOrMaybeDont(buffer);
    return tee;
}
 
Example #17
Source File: ConnectingProcessWorkerTask.java    From particle-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPostExecute(SetupProcessException error) {
    int resultCode;

    if (error != null) {
        resultCode = error.failedStep.getStepConfig().resultCode;

    } else {
        log.d("HUZZAH, VICTORY!");
        resultCode = SuccessActivity.RESULT_SUCCESS;

        if (!BaseActivity.setupOnly) {
            EZ.runAsync(() -> {
                try {
                    // collect a list of unique, non-null device names
                    Set<String> names = set(Funcy.transformList(
                            sparkCloud.getDevices(),
                            Funcy.notNull(),
                            ParticleDevice::getName,
                            Py::truthy
                    ));
                    ParticleDevice device = sparkCloud.getDevice(deviceId);
                    if (device != null && !truthy(device.getName())) {
                        device.setName(CoreNameGenerator.generateUniqueName(names));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    Activity activity = activityReference.get();
    if (activity != null) {
        activity.startActivity(SuccessActivity.buildIntent(activity, resultCode, deviceId));
        activity.finish();
    }
}
 
Example #18
Source File: SplashActivity.java    From particle-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onStart() {
    super.onStart();
    if (finished) {
        onShowingSplashComplete();
        return;
    }

    EZ.runOnMainThreadDelayed(SPLASH_DISPLAY_TIME, () -> {
        finished = true;
        onShowingSplashComplete();
    });
}
 
Example #19
Source File: DiscoverDeviceActivity.java    From particle-android with Apache License 2.0 4 votes vote down vote up
@SuppressLint("StaticFieldLeak")
private void startConnectWorker() {
    // first, make sure we haven't actually been called twice...
    if (connectToApTask != null) {
        log.d("Already running connect worker " + connectToApTask + ", refusing to start another");
        return;
    }

    wifiListFragment.stopAggroLoading();
    if (!canStartProcessAgain()) {
        hideProgressDialog();
        onMaxAttemptsReached();
        return;
    }

    discoverProcessAttempts++;

    // This just has doInBackground() return null on success, or if an
    // exception was thrown, it passes that along instead to indicate failure.
    connectToApTask = new AsyncTask<Void, Void, SetupStepException>() {

        @Override
        protected SetupStepException doInBackground(Void... voids) {
            try {
                // including this sleep because without it,
                // we seem to attempt a socket connection too early,
                // and it makes the process time out(!)
                log.d("Waiting a couple seconds before trying the socket connection...");
                EZ.threadSleep(2000);
                discoverProcessWorker.doTheThing();
                return null;

            } catch (SetupStepException e) {
                log.d("Setup exception thrown: ", e);
                return e;
            }
        }

        @Override
        protected void onPostExecute(SetupStepException error) {
            connectToApTask = null;
            if (error == null || (BaseActivity.setupOnly && error instanceof DeviceAlreadyClaimed)) {
                // no exceptions thrown, huzzah
                hideProgressDialog();
                startActivity(SelectNetworkActivity.buildIntent(
                        DiscoverDeviceActivity.this, selectedSoftApSSID));
                finish();
            } else if (error instanceof DeviceAlreadyClaimed) {
                hideProgressDialog();
                onDeviceClaimedByOtherUser();
            } else {
                // nope, do it all over again.
                startConnectWorker();
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example #20
Source File: ConnectingProcessWorkerTask.java    From spark-setup-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onPostExecute(SetupProcessException error) {
    int resultCode;

    if (error != null) {
        resultCode = error.failedStep.getStepConfig().resultCode;

    } else {
        log.d("HUZZAH, VICTORY!");
        // FIXME: handle "success, no ownership" case
        resultCode = SuccessActivity.RESULT_SUCCESS;

        if (!BaseActivity.setupOnly) {
            EZ.runAsync(() -> {
                try {
                    // collect a list of unique, non-null device names
                    Set<String> names = set(Funcy.transformList(
                            sparkCloud.getDevices(),
                            Funcy.notNull(),
                            ParticleDevice::getName,
                            Py::truthy
                    ));
                    ParticleDevice device = sparkCloud.getDevice(deviceId);
                    if (device != null && !truthy(device.getName())) {
                        device.setName(CoreNameGenerator.generateUniqueName(names));
                    }
                } catch (Exception e) {
                    // FIXME: do real error handling here, and only
                    // handle ParticleCloudException instead of swallowing everything
                    e.printStackTrace();
                }
            });
        }
    }

    Activity activity = activityReference.get();
    if (activity != null) {
        activity.startActivity(SuccessActivity.buildIntent(activity, resultCode, deviceId));
        activity.finish();
    }
}
 
Example #21
Source File: DiscoverDeviceActivity.java    From spark-setup-android with Apache License 2.0 4 votes vote down vote up
@SuppressLint("StaticFieldLeak")
private void startConnectWorker() {
    // first, make sure we haven't actually been called twice...
    if (connectToApTask != null) {
        log.d("Already running connect worker " + connectToApTask + ", refusing to start another");
        return;
    }

    wifiListFragment.stopAggroLoading();
    // FIXME: verify first that we're still connected to the intended network
    if (!canStartProcessAgain()) {
        hideProgressDialog();
        onMaxAttemptsReached();
        return;
    }

    discoverProcessAttempts++;

    // This just has doInBackground() return null on success, or if an
    // exception was thrown, it passes that along instead to indicate failure.
    connectToApTask = new AsyncTask<Void, Void, SetupStepException>() {

        @Override
        protected SetupStepException doInBackground(Void... voids) {
            try {
                // including this sleep because without it,
                // we seem to attempt a socket connection too early,
                // and it makes the process time out(!)
                log.d("Waiting a couple seconds before trying the socket connection...");
                EZ.threadSleep(2000);
                discoverProcessWorker.doTheThing();
                return null;

            } catch (SetupStepException e) {
                log.d("Setup exception thrown: ", e);
                return e;
            }
        }

        @Override
        protected void onPostExecute(SetupStepException error) {
            connectToApTask = null;
            if (error == null || (BaseActivity.setupOnly && error instanceof DeviceAlreadyClaimed)) {
                // no exceptions thrown, huzzah
                hideProgressDialog();
                startActivity(SelectNetworkActivity.buildIntent(
                        DiscoverDeviceActivity.this, selectedSoftApSSID));
                finish();
            } else if (error instanceof DeviceAlreadyClaimed) {
                hideProgressDialog();
                onDeviceClaimedByOtherUser();
            } else {
                // nope, do it all over again.
                // FIXME: this might be a good time to display some feedback...
                startConnectWorker();
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example #22
Source File: ConnectToApFragment.java    From spark-setup-android with Apache License 2.0 4 votes vote down vote up
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    apConnectorClient = EZ.getCallbacksOrThrow(this, Client.class);
}