Initializing and Onboarding

The SDKs must be initialized from the application.

This topic explains how to initialize the SDKs for stand-alone things. If you connect things using the gateway feature of Thing Interaction Framework, use the initialization method described in Initializing and Onboarding with Gateway.

Follow the steps below to initialize the SDKs.

  1. Initializing the Kii Cloud SDK

  2. Initializing the Thing-IF SDK (Including the owner and schema definition)

  3. Installing a device

  4. Onboarding

Initializing the Kii Cloud SDK

Execute the following code from the Application class. This code will be executed upon the application launch.

Make sure to align the name of the application class with the name you've specified in the AndroidManifest.xml (See Adding the Thing-IF SDK).

// The MobileApp class should be declared in your mobile app's AndroidManifest.xml.
public class MobileApp extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    // Initialize the Kii Cloud SDK. Call this method before any other Kii SDK API calls.
    // This method can be called multiple times.
    Kii.initialize(getApplicationContext(), "___APPID___", "___APPKEY___", Kii.Site.JP, false);
  }
}

Replace the placeholders ___APPID___ and ___APPKEY___ with your application's AppID and an arbitrary value, respectively (See Creating a Kii Application for the details).

The fifth argument is set to false to indicate that we are not using the analytics feature of the Kii Cloud SDK. Leave this parameter to false unless you are going to use the analytics feature.

You can safely embed the AppID in your application as long as you apply the correct access control. See Security for more information.

Initializing the Thing-IF SDK

Next, initialize the Thing-IF SDK with the following sample code. You can execute the sample code at any time as long as the Kii Cloud SDK initialization in the previous step is done.

ThingIFAPI api;

// Instantiate your application on Kii Cloud.
KiiApp app = new KiiApp("___APPID___", "___APPKEY___", Site.JP);

// Instantiate a ThingIFAPIBuilder object.
ThingIFAPIBuilder ib = ThingIFAPIBuilder.newBuilder(getApplicationContext(), app, owner);

// Add a schema to the ThingIFAPIBuilder instance.
ib.addSchema(schema);

// Instantiate a Thing-IF API from the ThingIFAPIBuilder instance.
api = ib.build();
  • Replace the placeholders ___APPID___ and ___APPKEY___ with your application's AppID and an arbitrary value, respectively (See Creating a Kii Application for the details).

    You can also pass the server hostname api-jp.kii.com instead of passing Site. Read the Javadoc for more details.

  • Owner represents a user who will be the owner of the thing. See Defining an Owner to learn how to get them.

    There are many ways to specify the user (owner). Which method to select depends on the design of the mobile app. In this guide, we will present a method with a pseudo user that does not require any explicit user registration and login. If you want to implement the explicit user login, you will need to provide a login screen and initialize the Thing-IF SDK after the login processes are done.

  • Schema represents the schema definition of commands to be sent to the thing. See Defining Schema to learn how to set it up.

When initialization is complete, you can get the instance that implements the API. By executing the build method of the ThingIFAPIBuilder, the SDK is initialized, and you will get a ThingIFAPI instance. Preserve the ThingIFAPI instance in somewhere, for example in the class field or Activity class, so that you can call it in the subsequent processes. You can also use the method explained in Saving and Restoring the initialized information to preserve the instance and restore it when the process is relaunched.

You can initialize multiple ThingIFAPI to handle multiple schema and things. In this case, specify a unique tag in the argument of the ib's setTag method. The tag is used to identify each ThingIFAPI instance, and it will be used when you use the saveInstance and loadFromStoredInstance methods to save and restore the instance.

Installing a device

You need to install the device so that it can receive responses from the thing. This action associates the owner with the FCM device token on Kii Cloud.

Installing a device

Use the ThingIFAPI instance obtained when initializing the Thing-IF SDK to install the device as below. See the implementation examples described later for more information about the parameters.

try {
  // Register the device token for the thing owner to Kii Cloud.
  api.installPush(token, PushBackend.GCM);
} catch (ThingIFException e) {
  // Handle the error.
}

When the device is installed, the owner specified upon creating the ThingIFAPI will be associated with the device token and registered to Thing Interaction Framework. The installation process overwrites the previous device token if any and push notifications to the previous owner will not be sent to this device any longer.

Implementation example

This example is a modified version of the sample code in the Android (FCM) Push Notification Tutorial for Thing-IF. The device is asynchronously installed with JDeferred because the sample code in the push notification tutorial installs the device in the main thread of MainActivity.

You can call installPush in a worker thread without JDeferred if you create a worker thread to call the API as in the Hello Thing-IF Tutorial.

Create a method to call the API using a promise with JDeferred.

private Promise<Void, Throwable, Void> installFCMPush(final ThingIFAPI api, final String token) {
  return mAdm.when(new DeferredAsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackgroundSafe(final Void... params) throws Exception {
      // Register the device token for the thing owner to Kii Cloud.
      api.installPush(token, PushBackend.GCM);
      return null;
    }
  });
}

Include the method in MainActivity.

private AndroidDeferredManager mAdm = new AndroidDeferredManager();

@Override
protected void onCreate(Bundle savedInstanceState) {
  ......

  // Get a FCM token.
  String fcmToken = FirebaseInstanceId.getInstance().getToken();
  if (fcmToken == null) {
    Toast.makeText(MainActivity.this, "Error FCM is not ready", Toast.LENGTH_LONG).show();
    return;
  }

  // Register the device token for the thing owner to Kii Cloud.
  mAdm.when(installFCMPush(apiEndNode1, fcmToken)
  ).then(new DoneCallback<Void>() {
    @Override
    public void onDone(Void param) {
      Toast.makeText(MainActivity.this, "Succeeded push registration", Toast.LENGTH_LONG).show();
    }
  }).fail(new FailCallback<Throwable>() {
    @Override
    public void onFail(final Throwable tr) {
      Toast.makeText(MainActivity.this, "Error push registration:" + tr.getLocalizedMessage(), Toast.LENGTH_LONG).show();
    }
  });
  ......
}

Uninstalling a device

Execute the following code to uninstall the device.

try {
  // Unregister the push notification for the thing owner.
  api.uninstallPush(api.getInstallationID());
} catch (ThingIFException e) {
  // Handle the error.
}

This code assumes that the device is installed. If the device is not installed, the GetInstallationID method will return a null value.

If the uninstallation is successful, the push notification will be no longer deliver to this device.

Onboarding

To control a thing from a mobile app, you need to bind the application to the thing. This binding process is called Onboarding.

The onboarding can be made in one of the following two ways:

You will get the same result for both, but their flows are a bit different. Use the method that matches well with how your thing is to be implemented.

For the overview of the onboarding process, see Onboarding in the Function Guide.

You need to execute the onboarding before executing any ThingIFAPI method (other than onboarding). Any attempt to execute a method (e.g., executing a command and getting a thing state) without the onboarding will give you an error.

Including the onboarding API, all of the APIs in the Thing-IF SDK are blocking APIs. The user interface stops if the main thread calls any blocking API. Call the APIs of the Thing-IF SDK with any asynchronous technology discussed in Implementation Guidelines or from a worker thread created by yourself.

Onboarding from the mobile app

In this method, the mobile app will handle the most of the binding processes.

As explained in Onboarding in the Function Guide, in this method, only the mobile app will access Thing Interaction Framework to perform the onboarding. This will allow the implementation of the thing simple. You need, however, to establish a secure connection between the mobile app and the thing (e.g., via Bluetooth) to share the result of the onboarding to the thing.

Step 1: Onboarding from the mobile app

First, the mobile app gets the thing's vendorThingID and thingPassword from the thing. This information is required for performing the onboarding.

Pass the information to the mobile app in any desirable way (See Thing identifier for more discussion).

The following sample code shows how you can onboard the thing from the mobile app.

try {
  // Set the thing credentials.
  String vendorThingID = "nbvadgjhcbn";
  String thingPassword = "123456";

  // Set onboarding options.
  OnboardWithVendorThingIDOptions.Builder builder = new OnboardWithVendorThingIDOptions.Builder();
  builder.setThingType("AirConditioner");
  builder.setThingProperties(new JSONObject());
  builder.setDataGroupingInterval(DataGroupingInterval.INTERVAL_15_MINUTES);
  OnboardWithVendorThingIDOptions options = builder.build();

  // Onboard the thing.
  api.onboard(vendorThingID, thingPassword, options);
} catch (ThingIFException e) {
  // Handle the error.
}

We are setting the following values in the sample code:

  • vendorThingID: The ID of the thing that the thing vendor assigned. See here for more information. Any string with alphanumeric, hyphen, underscore and period up to 200 characters is accepted as long as it is unique in the application. This field value cannot be modified later.
  • thingPassword: The password of the thing. Basically, a unique password is assigned to each thing to secure the resources allocated for the thing in Thing Interaction Framework. You cannot change the password later.
  • setThingType(): The type of the thing. Any string with alphanumeric, hyphen, underscore and period up to 100 characters is accepted. Specify the same type that you've assigned in the schema.
  • setThingProperties(): The properties of the thing in JSON Object format. These properties are useful when you use the Kii Cloud SDK together with the Thing-IF SDK. In this example, we are setting an empty JSON object.
  • setDataGroupingInterval(): The grouping interval for storing state history. The history will not be stored if no grouping interval is specified. The available intervals are INTERVAL_1_MINUTE, INTERVAL_15_MINUTES, INTERVAL_30_MINUTES, INTERVAL_1_HOUR, and INTERVAL_12_HOURS. See this page for the details.

Note that once you onboard a thing, the setThingType(), setThingProperties() and setDataGroupingInterval() will be fixed on the device. An attempt to modify these values later will be ignored.

Note that the state history is not available until onboarding from the mobile app completes. The thing can upload state information but it is not stored as history data until the first mobile app gets associated with the thing.

Step 2: Initializing the thing

The mobile app needs to pass the result of the onboarding to the thing. More specifically, the mobile app needs to get the thingID and access token of the thing with the following sample code and pass them to the thing.

// Instantiate the thing.
Target target = api.getTarget();

// Get the thing ID.
String thingID = target.getTypedID().getID();

// Get the thing access token.
String thingAccessToken = target.getAccessToken();

Once the thing gets this information, it will execute the initialization (the thing will not access Thing Interaction Framework in this initialization). See here for the details.

The access token is the confidential information. Like a password, anyone who gets it will be able to control the thing. Use a secure method, like using the Bluetooth, when you pass it to the thing.

Onboarding from both the thing and the mobile app

In this method, you first execute the onboarding request from a thing. Then, you execute the onboarding request from a mobile app.

You can actually start onboarding from either one of them. Both onboarding requests need to be processed, however, to start sending commands and getting thing state information.

As explained in Onboarding in the Function Guide, both the thing and mobile app will access Thing Interaction Framework while performing the onboarding in this method. The direct connection between the mobile app and thing, however, is not needed in this approach.

Step 1: Onboarding from the thing

Start onboarding from the thing. Once the onboarding is done, the thing will be able to report its state and receive commands.

See here for more details.

Step 2: Onboarding from the mobile app

Next, perform the onboarding from the mobile app. Once the onboarding is done, the mobile app will be able to send commands and get the thing state.

Here is the sample code:

try {
  // Set the thing credentials.
  String vendorThingID = "nbvadgjhcbn";
  String thingPassword = "123456";

  // Set the data grouping interval option.
  OnboardWithVendorThingIDOptions.Builder builder = new OnboardWithVendorThingIDOptions.Builder();
  builder.setDataGroupingInterval(DataGroupingInterval.INTERVAL_15_MINUTES);
  OnboardWithVendorThingIDOptions options = builder.build();

  // Onboard the thing.
  api.onboard(vendorThingID, thingPassword, options);
} catch (ThingIFException e) {
  // Handle the error.
}

We are setting the following values in the sample code:

  • vendorThingID: The ID of the thing that the thing vendor assigned. See here for more information. Specify the vendorThingID you have set in Step 1.
  • thingPassword: The password of the thing. Basically, a unique password is assigned to each thing to secure the resources allocated for the thing in Thing Interaction Framework. Specify the password you have set in Step 1.
  • setDataGroupingInterval(): The grouping interval for storing state history. The history will not be stored if no grouping interval is specified. The available intervals are INTERVAL_1_MINUTE, INTERVAL_15_MINUTES, INTERVAL_30_MINUTES, INTERVAL_1_HOUR, and INTERVAL_12_HOURS. See this page for the details.

Alternatively, the above API can use the thingID transferred from the thing (e.g., via Bluetooth) instead of using the vendorThingID.

Note that the state history is not available until onboarding from the mobile app completes. The thing can upload state information but it is not stored as history data until the first mobile app gets associated with the thing.