Filter results by

Implement a Cloud Connector

This article explains how to use the Cloud Connector SDK to write Connector Code for a Cloud Connector implementation. The Groovy code tells ARTIK cloud services how to interact with third-party APIs in order to get data from a third-party cloud. It implements a derived class of CloudConnector base class from the SDK.

Connector Code is submitted in the Developer Dashboard. Read Using Cloud Connectors for a high-level overview of the feature.

Setup

Create your project by copying and renaming the template folder.

Finally, read our coding guide and see these working Cloud Connector samples.

Each command mentioned in this document should be launched from the current project directory, which contains the build.gradle file.

Implementation steps

In the following steps, certain Cloud Connector methods may be overridden according to your use case.

  1. Authenticate
  2. Initialize
  3. Modify requests
  4. Subscribe/Notify
  5. Send messages
  6. Handle Actions
  7. Set device status
  8. Set up polling
  9. Manage sub-devices
  10. Helper functions
  11. Test code

Authenticate

Authenticate the external account with the ARTIK cloud services device.

Cloud Connector authentication

OAuth1/OAuth2

If the third-party cloud supports OAuth1/OAuth2, you can specify the parameters in the Developer Dashboard without coding.

ARTIK cloud services support OAuth2 with grant_type=code or username/password. Read Authentication for details.

If you need to customize OAuth1 or OAuth2, override the following methods.

Method Description
signAndPrepare Add credentials to requests (e.g., in Authentication header)
normalizeOauth2Code Modify response received with OAuth2 code
normalizeOauth2Token Modify response received with OAuth2 token

Credentials obtained through authentication are stored in the DeviceInfo structure in credentials.

Use case Sample
OAuth1 Withings
OAuth2 (code, token) Moves, Fitbit, Foursquare, iHealth, Instagram
OAuth2 (username/password, token) Parrot Flower Power
Oauth2, use normalize methods Samsung Smart Home

External ID

After authorization, the Cloud Connector device type is linked with the user or device on the third-party cloud. The unique external ID can be stored in DeviceInfo using extId.

Use case Sample
External ID is user ID Instagram, Foursquare, Moves
Use ARTIK cloud services device ID Withings

Custom authentication/identification

If the third-party cloud uses another way to authenticate or identify the user, you can display a custom form to obtain, verify, and store user credentials.

Method Description
onCustomAuthentication Display authentication form to the user and store obtained credentials

The user or device can be identified by one or more fields (e.g, serial number or user token).

Use case Sample
Enter token LifX
Enter serial number SIGFOX

No authentication

Some clouds do not require authentication.

Use case Sample
No authentication OpenWeatherMap

Initialize

You can send request(s) to a third-party cloud when your Cloud Connector is loaded by ARTIK cloud services.

Method Description
initialize Send multiple requests to external cloud to set up the application
onInitializeResponse Receive response to the requests sent in initialize

initialize is not called per user. It is called when ARTIK cloud services load the Cloud Connector and may be called subsequently.

Use case Sample
Create a subscription for the application (not for each user) Instagram

Modify requests

The requests initiated by your Cloud Connector can be modified at each of the phases (e.g., initialization, subscription, notification, fetch).

Method Description
signAndPrepare Add or remove information (e.g., token, signature, scope) to/from request (e.g., headers, query, body) as necessary
Use case Sample
Sign all requests and add signature in header Fitbit
Add extra parameters during authentication and refresh token Philips
Add extra headers Twitter

Subscribe/Notify

A third-party cloud must provide API endpoints for subscription/notification so that ARTIK cloud services can subscribe to receive notification when new data are available.

Subscription

Use subscribe to send a request(s) to the third-party cloud to subscribe to notifications. Requests are made sequentially and responses are parsed with onSubscribeResponse.

In the Developer Dashboard, provide the following endpoint/webhook for the third-party cloud to call for notifications. (The device type ID is listed with the device in the Developer Dashboard.)

1
https://api.artik.cloud/v1.1/cloudconnectors/YOUR_DEVICE_TYPE_ID/thirdpartynotifications

subscribe is called after the user has authorized their device.

Method Description
subscribe Send request(s) to external cloud to set up notifications for user (after authorization)
onSubscribeResponse Parse responses to requests sent in subscribe
Use case Sample
Need subscription per user to receive notifications Fitbit, Withings
Do not need subscription per user to receive notifications Moves

Notification

Use onNotification to process notifications received at the URL you provided for the subscription.

After authorization and subscription, ARTIK cloud services send a notification to the endpoint postsubscription. This is received by onNotification and allows you to send extra requests to the third-party cloud.

ARTIK cloud services call fetch for each HTTP request returned by onNotification and onAction to fetch data on the third-party cloud.

Method Description
onNotification Extract notifications and external device ID (to route the notification to the right user/device) sent by external cloud
onNotificationData Send data embedded in notifications as messages to ARTIK cloud services
onFetchResponse Receive response to fetch requests sent by onNotification and send data as messages to ARTIK cloud services
Use case Sample
Data embedded in notification Foursquare
Data must be requested Fitbit, Withings
Use /postsubscription notification Fitbit

Unsubscribe

Use unsubscribe to unsubscribe from third-party cloud notifications.

Method Description
unsubscribe Send request to external cloud when a device is unauthorized or deleted
unsubscribeLast Send request to external cloud when user's last remaining device of the device type is unauthorized or deleted
onUnsubscribeResponse Receive response to requests sent in unsubscribe and unsubscribeLast
Use case Sample
Unsubscribe Withings, Jawbone, Runkeeper

Send messages

Messages received in notifications or as Actions can be posted to ARTIK cloud services in onNotificationData and onFetchResponse.

To send a message, return an event with kind: EventType.data. The event payload contains an object to be normalized by your Manifest.

1
2
3
4
5
6
{
  "field1": "value1",
  "parent1": {
    "field2": "value2"
  }
}
Use case Sample
onFetchResponse (with notifications) Moves (see extractSummaryNotification)
onFetchResponse (with Actions) OpenWeatherMap
onNotificationData Foursquare

Handle Actions

Use onAction to receive Actions sent to your devices.

Actions must have been declared in the device type Manifest.

Method Description
onAction Extract Action parameters sent by external cloud to your devices
onActionData Send data messages to ARTIK cloud services
onFetchResponse Receive response to fetch requests sent by onAction and send data as messages to ARTIK cloud services
Use case Sample
Send data to ARTIK cloud services  
Send request to external cloud OpenWeatherMap, Twitter, LifX

Set device status

You can update a device's status by sending the event kind: EventType.updateDeviceStatus. Device status represents the availability of a device to send messages and/or receive Actions via a supported protocol.

  • kind: EventType.updateDeviceStatus
  • extSdid: unique ID of the device in the external cloud
  • payload: device status
1
2
3
{
    "availability": "online"
}

The possible values of availability are online, offline, and unknown. See the API reference for more information about this parameter.

Polling

You can set ARTIK cloud services to call Actions at a specific frequency in the Developer Dashboard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
[...]
    // Setup polling
    // cron: a cron expression
    // action: the action that will be called
    "polling": [{
        "cron": "0 0 * * * *", // every hour
        "action" : {
            "name": "actionName",
            "parameters": {
                "param1": "paramvalue1",
                "param2": 2
            }
        }
    }]
}

Note that 1 hour is the minimum frequency.

Use case Sample
Check for new data every hour Runkeeper

Sub-device

Some third-party clouds handle multiple devices per account. To manage these devices, you can use the Developer Dashboard to create a sub-device of the parent Cloud Connector device type. The external device type ID must then be mapped to the sub-device, which has its own Manifest.

List sub-devices

Use findExtSubDeviceId from the Context object to list sub-devices.

Use the following method to display a message after authorization and subscription that notifies the user of newly created sub-devices.

Method Description
generateWelcomeMessage Build and display a message to the user

Manage sub-devices

Use onFetchResponse to send events to create, update, or delete sub-devices.

  • kind: EventType.createIfNotExist to create the sub-device; EventType.createOrUpdateDevice to create or update the sub-device; EventType.deleteDevice to delete the sub-device
  • extSubDeviceId: external ID of the sub-device
  • extSubDeviceTypeId: the external device type ID of the sub-device (if not specified, uses the parent device type)
  • payload: device name of the sub-device

Messages sent to ARTIK cloud services can be routed to the sub-device if you specify extSubDeviceId in the event.

  • kind: EventType.data
  • extSubDeviceId: external ID of the sub-device
  • payload: raw message to be normalized by the sub-device type Manifest
Method Description
onFetchResponse CRUD sub-device(s)
onActionData CRUD sub-device(s)
onNotificationData CRUD sub-device(s)
Use case Sample
CRUD, messages, or Actions for sub-devices with the same device type Ring
CRUD, messages, or Actions for sub-devices with multiple device types Samsung Smart Home, LifX, Philips Hue

Helpers

Use the following functions in the sample code to perform JSON transformations.

Use case Sample
Clean and remove all empty values transformJson (Foursquare)
Rename Keys renameJsonKey (Foursquare), weatherJsonTransFormation (OpenWeatherMap)
Filter Keys outputJson (OpenWeatherMap)

Test code

Finally, test your Connector Code. See our coding guide and Your First Cloud Connector to learn how to run unit and integration tests.

To compile:

1
../gradlew classes