Build an application to manage Cloud Connector devices

Today we’re developing an Android app that adds Cloud Connector devices to ARTIK Cloud and authorizes them with the corresponding third-party cloud. This allows your users to do everything within your application, rather than performing the necessary operations in My ARTIK Cloud. We will mention the REST APIs used for these functionalities. 

Introduction

Third-party devices (e.g., Withings and Fitbit) may send data to a corresponding third-party cloud. Instead of retrieving data directly from these devices, ARTIK Cloud can connect to an eligible third-party cloud and use it as the data source. To achieve this, a Cloud Connector for that type of device must first be built on ARTIK Cloud. A user can then connect a device that belongs to this Cloud Connector device type to their ARTIK Cloud account. If the third-party cloud requires authentication, the user must authenticate once with the third-party cloud and grant permissions to ARTIK Cloud.

One way to do this is to ask a user to connect a device of the Cloud Connector device type in My ARTIK Cloud, and then to click the “AUTHORIZE” button, per the example in the documentation.

ARTIK Cloud also provides APIs for third-party applications to authenticate a Cloud Connector device and revoke a Cloud Connector device’s authentication within the app, so that a user would not need to perform such operations in My ARTIK Cloud

This article teaches shows you how to implement the authentication/authorization management of Cloud Connector devices, and how to programmatically add and delete devices.

Check out the source code for this demo.

Demo

  • Start ACManageCCDevice on an Android phone.
  • Click “login” and enter your ARTIK Cloud Account credentials to login. Note that these are also your Samsung account credentials.

login

  • Click “Allow” when the app asks for permission to access data from the “Withings Device” Cloud Connector. This screen appears when you use the app for the first time.

perm_screen

  • After you finish the authentication, you will see the “Manage Cloud Connector devices” screen.

1

  • Click the “Add device” button to create a Cloud Connector device in ARTIK Cloud. Afterward, the screen shows some info about the device you created (it will have the “Withings Device” device type ID). From there, you can see that this device needs third-party authentication in order to receive data from Withings. The “Authorize” button is enabled.

2

  • Click the “Authorize” button to begin authentication with Withings. Enter your Withings credentials and then grant permissions to ARTIK Cloud.

3 4_perm_screen

  • After successfully completing authentication with Withings, you are taken back to the “Manage Cloud Connector devices” screen. You should see that your Withings Cloud Connector device is now authenticated. From now on, the device ID specified here can receive data from the physical Withings device via the Withings cloud.

5_authorized_CC

  • Click “Remove authorization” button to revoke the authentication with Withings. The corresponding device stops receiving data from the Withings cloud. You can re-initiate the authorization or delete the device. 

6_revoke_authorization

Installation and setup

Log in to the Developer Dashboard to register your Android application on ARTIK Cloud. To properly test the application, I use two separate Samsung accounts with different email addresses:

  1. My official developer account. This is the account I use to log into the Developer Dashboard and register my application.
  2. A simulated user account. This is the account that I used in the above demo to log into ARTIK Cloud on phone and to log into the My ARTIK Cloud web portal.

Follow these instructions to create an application. For this Android app, select the following:

  • Under “AUTHORIZATION METHODS”, check “Client credentials, auth code, implicit”.
  • Set “Redirect URL” to app://redirect.
  • Under “PERMISSIONS”, check “Read” for “Profile”.
  • Click the “Add Device Type” button. Choose “Withings Device” (DTID: dt29673f0481b4401bb73a622353b96150) as the device type. Check “Read” and “Write” permissions for this device type.

Make a note of the client ID, which you will use in your source file later.

Prepare source files and libraries

Use the ARTIK Cloud Java/Android SDK v2.0.3 to manage all your REST calls to ARTIK Cloud. 

  • Check out ACManageCCDevice from GitHub.
  • In Android Studio, open the project. 
  • Use the client ID (obtained above, when registering the app in the Developer Dashboard) to replace YOUR CLIENT ID in ArtikCloudSession.java.

Now build the project, which will download the ARTIK Cloud SDK JAR from Maven Central Repository. Deploy the APK to an Android phone. You can play with the app like in the above demo.

Implementation

We need to implement the following functionalities:

  1. Authenticate a user using the OAuth 2.0 workflow.
  2. Collect user information such as username and user ID.
  3. Connect a device to a user’s ARTIK Cloud account.
  4. Delete a device from a user’s ARTIK Cloud account.
  5. Authenticate with the third-party cloud.
  6. Revoke authorization from the third party cloud.

For the first two functionalities, you can refer to the Your first Android app tutorial (“Login to obtain access token” and “Get user’s name from ARTIK Cloud”) for implementation details.

Add a Withings device to the user’s account

Clicking the “Add device” button creates a new device on the user’s ARTIK Cloud account. This device has the Cloud Connector device type “Withings Device”. Later on, this device will be authenticated with the Withings cloud.

To programmatically create a device, call the Create a Device REST API. The following method in  DeviceActivity illustrates an easy way to do it using the SDK:

private void addDevice() {
    final String tag = TAG + " addDeviceAsync";
    Device device = new Device();
    device.setDtid(DEVICE_TYPE_ID);
    device.setUid(ArtikCloudSession.getInstance().getUserId());
    device.setName(DEVICE_NAME);
    mProgressDialog = ProgressDialog.show(DeviceActivity.this, "", "Connect the device to ARTIK Cloud...");
    try {
        ArtikCloudSession.getInstance().getDevicesApi().addDeviceAsync(device, new ApiCallback<DeviceEnvelope>() {
            @Override
            public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
                processFailure(tag, e);
            }

            @Override
            public void onSuccess(DeviceEnvelope result, int statusCode, Map<String, List<String>> responseHeaders) {
                ArtikCloudSession.getInstance().setDevice(result.getData());
                Device d = result.getData();
                String displayResult = "Successfully created:\n" + deviceInfoString(d);
                handleAddOrDeleteBtnOnUIThread(displayResult);
            }
    
            ...

        });
    } catch (ApiException exc) {
        processFailure(tag, exc);
    }
}

The Cloud Connector device name is hardcoded to “My Withings” in the source code. Below, we will use this name to refer to this device.

Delete a Withings device from the user’s account

To programmatically delete a device, call the Delete a Device REST API.  The following method in  DeviceActivity illustrates an easy way to do it using the SDK:

private void deleteDevice() {
    final String tag = TAG + " deleteDeviceAsync";
    Device d = ArtikCloudSession.getInstance().getDevice();

    mProgressDialog = ProgressDialog.show(DeviceActivity.this, "", "Delete the device from ARTIK Cloud...");
    try {
        ArtikCloudSession.getInstance().getDevicesApi().deleteDeviceAsync(d.getId(), new ApiCallback<DeviceEnvelope>() {
            @Override
            public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
                processFailure(tag, e);
            }

            @Override
            public void onSuccess(DeviceEnvelope result, int statusCode, Map<String, List<String>> responseHeaders) {
                Log.v(tag, " onSuccess " + result.toString());
                ArtikCloudSession.getInstance().setDevice(null);
                Device d = result.getData();
                String displayResult = "Successfully deleted\n" + deviceInfoString(d);
                handleAddOrDeleteBtnOnUIThread(displayResult);
            }

            ...

        });
    } catch (ApiException exc) {
        processFailure(tag, exc);
    }
}

Authenticate with Withings cloud

After “My Withings” is added to the user’s ARTIK Cloud account, the user must authenticate this device with the Withings cloud and grant ARTIK Cloud the permission to access data on the Withings account. “My Withings” can then receive data from the user’s physical device via the Withings cloud.

To do this within the application (instead of My ARTIK Cloud), call the Authenticate a Cloud Connector device REST API. This call triggers a sequence of redirections between ARTIK Cloud, the Withings cloud, and the Android application. Refer to the API reference for various options to construct the HTTP request. For this implementation, we pack the access token and referer in the HTTP POST request.

private void loadWebView(final String url) {
    Log.d(TAG, "loadWebView url " + url);
    String postData = "token=" + ArtikCloudSession.getInstance().getAccessToken() + "&referer=" + ArtikCloudSession.REFERER;
    mProgressBar = ProgressDialog.show(AuthorizeDeviceActivity.this, "", "Loading...");
    mWebView.setWebViewClient(webViewClient);
    mWebView.postUrl(url, EncodingUtils.getBytes(postData, "BASE64"));
}

After making the above call, the webview presents the login and permission screens to the user as in the demo. When the whole process finishes, ARTIK Cloud makes a callback to the link provided in the referer field of the HTTP request body. This is how the app is notified of success. In the following code, the app catches the redirection to the referer link.

public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.contains(ArtikCloudSession.REFERER)) {
        Log.d(TAG, "Catch Referer");
        handleAuthSuccess();
        return true;
    }

    return super.shouldOverrideUrlLoading(view, url);
}

Revoke the authorization with Withings cloud

After successfully authenticating with the Withings cloud, the button “Remove authorization” is enabled. Clicking it triggers a REST API call to revoke the device’s authentication with the Withings cloud. At this time, the ARTIK Cloud Android SDK 2.0.3 does not support this API. However, we can easily use Android HTTP library Volley to achieve it. The HTTP response with 200 code indicates success as follows:

private void deAuthDevice() {
    final String tag = TAG + " deAuthDevice";
    String uri = ArtikCloudSession.getInstance().getDeAuthWith3rdPartyCloudUri();
    if (uri == null) {
        Log.e(tag, "Cannot remove the authorization from the device: Device is null or device.id is null!");
        return;
    }
    RequestQueue queue = Volley.newRequestQueue(this);
    StringRequest sr = new StringRequest(Request.Method.DELETE, uri, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // De-authorization succeeded. Make another API call to get the updated Device Info.
            updateDeviceInfo();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            ... 
            }
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Authorization", "bearer " + ArtikCloudSession.getInstance().getAccessToken());
            return params;
    }

    };
    queue.add(sr);
    mProgressDialog =  ProgressDialog.show(DeviceActivity.this, "", "De-authorizing...");
}

Conclusion

If you’re using a Cloud Connector to communicate with a third-party cloud, you can easily manage Cloud Connector devices for your users within your application. Our Works with ARTIK Cloud page lists some of the Cloud Connectors we have developed. You can also build a Cloud Connector for an eligible third-party cloud that interests you. See Your First Cloud Connector and the Cloud Connector samples at GitHub for instructions on how to do this.

We hope this inspires you to keep building and connecting the devices and clouds you are passionate about! Feel free to email us at developer@artik.cloud if you have any questions or feedback. 

Looking to connect many devices to the cloud and build innovative IoT solutions? Click here to get started for free.