Cloud Code Exposed APIs

This document describes how to interact with the exposed external services in the cloud code.

Analytics.kpis

Allows to create custom kpis and assign different tags associated to them.

analytics.kpis.create(name, value, tags)

/** @type {string} */
var name = 'KPI_NAME';
/** @type {any} */
var value = 'KPI_VALUE';
/** @type {string[]} - Tags should be an array of Strings, containing only alphanumeric characters and "-" or "\_" */
var tags = [];

analytics.kpis.create(name, value, tags);



Async

Version: 1.5.0
Async is a utility module which provides straightforward functions for working with asynchronous JavaScript.

Documentation official:
https://www.npmjs.com/package/async/v/1.5.0




Console

Print messages in the developers console.

📘

Tip

Due to the large number of logs that can be displayed in the developers console, we recommend adding some identifying text to the message to be printed that allows it to be filtered.

/** @type {string|number|boolean|object} */
var infoMsg = 'INFORMATIVE_MESSAGE_TEXT';

// Print informative message
console.log(infoMsg);

// Print informative message (recommendation)
console.log('ID_TEXT', infoMsg);
/** @type {string|number|boolean|object} */
var errorMsg = 'ERROR_MESSAGE_TEXT';

// Print error message
console.error(errorMsg);

// Print error message (recommendation)
console.error('ID_TEXT', errorMsg);



Email

Send mail(s) using your favorite provider.

/**
 * @typedef             EmailSendGridCredentials
 * @prop {'SendGrid'}   service         - Service provider name
 * @prop {Object}       auth            - Authentication data provided by the provider
 * @prop {string}       auth.api_user   - API User
 * @prop {string}       auth.api_key    - API Key
 */

/** @type {EmailSendGridCredentials} */
var emailCredentials = {
    service: 'SendGrid',
    auth: {
        api_user: 'YOUR_API_USER',
        api_key: 'YOUR_API_KEY'
    }
};

/**
 * @typedef             EmailOptions
 * @prop {string}       from            - Sender's email
 * @prop {string}       to              - Recipient email
 * @prop {string}       subject         - Mail subject
 * @prop {string}       [text]          - Email content (use when the message is plain text only)
 * @prop {string}       [html]          - Email content (use when message contains HTML)
 */

/** @type {EmailOptions} */
var emailOptions = {
    from: 'SENDER_EMAIL',
    to: 'RECEIVER_EMAIL',
    subject: 'EMAIL_SUBJECT_TEXT',
    text: 'EMAIL_CONTENT_TEXT'
};

// Send mail
email(emailCredentials, emailOptions);
/**
 * @typedef             EmailMandrillCredentials
 * @prop {'Mandrill'}   service         - Service provider name
 * @prop {Object}       auth            - Authentication data provided by the provider
 * @prop {string}       auth.apiKey     - API Key
 */

/** @type {EmailMandrillCredentials} */
var emailCredentials = {
    service: 'Mandrill',
    auth: {
        apiKey: 'YOUR_API_KEY'
    }
};

/**
 * @typedef             EmailOptions
 * @prop {string}       from            - Sender's email
 * @prop {string}       to              - Recipient email
 * @prop {string}       subject         - Mail subject
 * @prop {string}       [text]          - Email content (use when the message is plain text only)
 * @prop {string}       [html]          - Email content (use when message contains HTML)
 */

/** @type {EmailOptions} */
var emailOptions = {
    from: 'SENDER_EMAIL',
    to: 'RECEIVER_EMAIL',
    subject: 'EMAIL_SUBJECT_TEXT',
    text: 'EMAIL_CONTENT_TEXT'
};

// Send mail
email(emailCredentials, emailOptions);
/**
 * @typedef             EmailMailchimpCredentials
 * @prop {'Mailchimp'}  service         - Service provider name
 * @prop {Object}       auth            - Authentication data provided by the provider
 * @prop {string}       auth.apiKey     - API Key
 */

/** @type {EmailMailchimpCredentials} */
var emailCredentials = {
    service: 'Mailchimp',
    auth: {
        apiKey: 'YOUR_API_KEY'
    }
};

/**
 * @typedef             EmailOptions
 * @prop {string}       from            - Sender's email
 * @prop {string}       to              - Recipient email
 * @prop {string}       subject         - Mail subject
 * @prop {string}       [text]          - Email content (use when the message is plain text only)
 * @prop {string}       [html]          - Email content (use when message contains HTML)
 */

/** @type {EmailOptions} */
var emailOptions = {
    from: 'SENDER_EMAIL',
    to: 'RECEIVER_EMAIL',
    subject: 'EMAIL_SUBJECT_TEXT',
    text: 'EMAIL_CONTENT_TEXT'
};

// Send mail
email(emailCredentials, emailOptions);
/**
 * @typedef             EmailSesCredentials
 * @prop {'SES'}        service                 - Service provider name
 * @prop {Object}       auth                    - Authentication data provided by the provider
 * @prop {string}       auth.accessKeyId        - Access Key ID
 * @prop {string}       auth.secretAccessKey    - Secret Access Key 
 * @prop {string}       auth.region             - Region (For more info: https://www.aws-services.info/ses.html)
 */

/** @type {EmailSesCredentials} */
var emailCredentials = {
    service: 'SES',
    auth: {
        accessKeyId: 'YOUR_ACCESS_KEY_ID',
        secretAccessKey: 'YOUR_SECRET_ACCESS_KEY',
        region: 'us-west-2'
    }
};

/**
 * @typedef             EmailOptions
 * @prop {string}       from                    - Sender's email
 * @prop {string}       to                      - Recipient email
 * @prop {string}       subject                 - Mail subject
 * @prop {string}       [text]                  - Email content (use when the message is plain text only)
 * @prop {string}       [html]                  - Email content (use when message contains HTML)
 */

/** @type {EmailOptions} */
var emailOptions = {
    from: 'SENDER_EMAIL',
    to: 'RECEIVER_EMAIL',
    subject: 'EMAIL_SUBJECT_TEXT',
    text: 'EMAIL_CONTENT_TEXT'
};

// Send mail
email(emailCredentials, emailOptions);
/**
 * @typedef             EmailGmailCredentials
 * @prop {'Gmail'}      service         - Service provider name
 * @prop {Object}       auth            - Authentication data provided by the provider
 * @prop {string}       auth.user       - API User
 * @prop {string}       auth.pass       - API Pass
 */

/** @type {EmailGmailCredentials} */
var emailCredentials = {
    service: 'Gmail',
    auth: {
        user: 'YOUR_USER',
        pass: 'YOUR_PASS'
    }
};

/**
 * @typedef             EmailOptions
 * @prop {string}       from            - Sender's email
 * @prop {string}       to              - Recipient email
 * @prop {string}       subject         - Mail subject
 * @prop {string}       [text]          - Email content (use when the message is plain text only)
 * @prop {string}       [html]          - Email content (use when message contains HTML)
 */

/** @type {EmailOptions} */
var emailOptions = {
    from: 'SENDER_EMAIL',
    to: 'RECEIVER_EMAIL',
    subject: 'EMAIL_SUBJECT_TEXT',
    text: 'EMAIL_CONTENT_TEXT'
};

// Send mail
email(emailCredentials, emailOptions);



HttpRequest

Sends an http request to an external web service. If you need to send a https request, set secure to true.

/**
 * @typedef {'GET'|'POST'|'PUT'|'PATCH'|'DELETE'}   HttpRequestMethods
 * @typedef {{ [headerName: string]: string }}      HttpRequestHeaders
 * 
 * @typedef                                         HttpRequestOptions
 * @prop {string}                                   host
 * @prop {string}                                   path
 * @prop {number}                                   [port=80]
 * @prop {HttpRequestMethods}                       [method='GET']
 * @prop {boolean}                                  [secure=false]
 * @prop {HttpRequestHeaders}                       [headers]
 */

/** @type {HttpRequestOptions} */
var requestOptions = {
    host: 'example.com',
    path: '/test',
    secure: true
};

/** @type {object} */
var requestBody = {};

httpRequest(requestOptions, requestBody, function (error, result) { /* ... */ });

If no callback is provided, the request will be executed too and errors will be redirected to the console.




Moment

Version: 2.22.2
A date library for parsing, validating, manipulating, and formatting dates.

Documentation official:
https://www.npmjs.com/package/moment/v/2.22.2
https://github.com/moment/moment/blob/develop/CHANGELOG.md#2222-see-full-changelog




SMS and voice calls with twilio

This service lets you send SMS and make voice calls. You have to introduce your twilio credentials.

// Create Twilio client
var twilioClient = new Twilio('YOUR_ACCOUNT_SID', 'YOUR_AUTH_TOKEN');

/**
 * @typedef         	TwilioMessageConfig
 * @prop {string}   	to          	- Message recipient number
 * @prop {string}   	from        	- Message sender number (It must be a number purchased from Twilio)
 * @prop {string}   	body        	- SMS message text
 */

/** @type {TwilioMessageConfig} */
var messageConfig = {
    to: 'RECIPIENT_NUMBER',
    from: 'SENDER_NUMBER',
    body: 'MESSAGE_TEXT'
};

// Send an SMS text message
twilioClient.sendMessage(messageConfig, function (error, response) { /* ... */ });
// Create Twilio client
var twilioClient = new Twilio('YOUR_ACCOUNT_SID', 'YOUR_AUTH_TOKEN');

/**
 * @typedef         	TwilioCallConfig
 * @prop {string}   	to         		- Call recipient number
 * @prop {string}   	from        	- Call sender number (It must be a number purchased from Twilio)
 * @prop {string}   	url         	- A URL that produces an XML document (TwiML) which contains instructions for the call
 */

/** @type {TwilioCallConfig} */
var callConfig = {
    to: 'RECIPIENT_NUMBER',
    from: 'SENDER_NUMBER',
    url: 'EXTERNAL_URL'
};

// Place a phone call, and respond with TwiML instructions from the given URL
twilioClient.makeCall(callConfig, function (error, response) { /* ... */ });



Telegram Bot

This service lets you send a Telegram message to a Telegram account through a Telegram Bot. The only condition is that the Telegram account that you want to send the message to must have texted the bot before.

In the following blog post you can find how to push the bot for the first time and obtain the chat_id.

Once you have obtained the chat_id of the Telegram account you can start sending messages. You just have to fill the parameters chat_id and text.

/**
 * @typedef         	TelegramBotOptions
 * @prop {number}   	chat_id          - Id of the chat between bot and user
 * @prop {string}   	text        	 - Text to send to the reciever
 * @prop {string}   	[custom_bot]     - Token of your own telegram custom bot
 */

/** @type {TelegramBotOptions} */
var params = {
    chat_id: 123345,
    text: 'You have reached the maximum water cosumption'
}

telegram.sendMessage(params, function (error, result) { /** ... */ });



Twitter

This service lets you send a Tweet to your Twitter account. You have to introduce your Twitter credentials.

/**
 * @typedef         TwitterClientConfig
 * @prop {string}   accessToken             - Access Token
 * @prop {string}   accessTokenSecret       - Access Token Secret
 * @prop {string}   consumerKey             - Consumer Key
 * @prop {string}   consumerSecret          - Consumer Secret
 */

/** @type {TwitterClientConfig} */
var twitterClientConfig = {
    accessToken: 'YOUR_ACCESS_TOKEN',
    accessTokenSecret: 'YOUR_ACCESS_TOKEN_SECRET',
    consumerKey: 'YOUR_CONSUMER_KEY',
    consumerSecret: 'YOUR_CONSUMER_SECRET'
};

// Create Twitter client
var twitterClient = new Twitter(twitterClientConfig);

// ...
/**
 * @typedef         TwitterPostTweetParameters
 * @prop {string}   status                  - Tweet message
 * 
 * In this example, only the parameters to be used have been added to the TwitterPostTweetParameters type. 
 * To see the complete list of parameters, visit the following link:
 * https://developer.twitter.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-update#parameters
 */

/** @type {TwitterPostTweetParameters} */
var tweetParams = {
    status: 'TWEET_TEXT'
};

// Post Tweet
twitterClient.postTweet(tweetParams, function(error, response) { /* ... */ });



ThethingsAPI

The thethingsAPI API allows you to perform read and write actions on data stored in thethings.io.


thethingsAPI.thingRead(thingToken, values, [filters], callback)

Get the stored values ​​of a specific resource and device.

/**
 * ===============================================
 * OPTION 1: Without filters
 * ===============================================
 */

/** @type {string} */
var thingToken = 'YOUR_THING_TOKEN';
/** @type {string} */
var resourceName = 'YOUR_RESOURCE_NAME';

thethingsAPI.thingRead(thingToken, resourceName, function (error, result) { /* ... */  })


/**
 * ===============================================
 * OPTION 2: With filters
 * ===============================================
 */

/** @type {string} */
var thingToken = 'YOUR_THING_TOKEN';
/** @type {string} */
var resourceName = 'YOUR_RESOURCE_NAME';
/** 
 * @typedef         ThingReadFilters 
 * @prop {Date}     [startDate]         - The default date is Jan 1st 1970.
 * @prop {Date}     [endDate]           - The default date is current date.
 * @prop {number}   [limit=1]           - Number of values to return. Available range between 1 and 1000. By default, the value is 1.
 * 
 * @type {ThingReadFilters}
 */
var filters = {
    startDate: new Date(0),
    endDarte: new Date(),
    limit: 1
};

thethingsAPI.thingRead(thingToken, resourceName, filters, function (error, result) { /* ... */  }) 

thethingsAPI.thingWrite(thingToken, values, [params], callback)

Write data into a device through its token

/**
 * ===============================================
 * OPTION 1: Without params
 * ===============================================
 */

/** @type {string} */
var thingToken = 'YOUR_THING_TOKEN';
/** 
 * @typedef           ThingValue 
 * @prop {string}     key             - Resource name.  
 * @prop {any}       	value           - Resource value.
 * @prop {object}     [geo]           - Thing location. 
 * @prop {number}     geo.lat         - Lattitude value. Available range between -90 and 90.
 * @prop {number}     geo.long        - Longitude value. Available range between -180 and 180.
 * 
 * @type {ThingValue[]}
 */
var values = [{
    key: 'temperature',
    value: 35,
    geo: {
        lat: 10,
        long: 25
    }
}];

thethingsAPI.thingWrite(thingToken, { values: values }, function (error, result) { /* ... */  }) 


/**
 * ===============================================
 * OPTION 2: With params
 * ===============================================
 */

/** @type {string} */
var thingToken = 'YOUR_THING_TOKEN';
/** 
 * @typedef           ThingValue 
 * @prop {string}     key             - Resource name.  
 * @prop {any}    		value           - Resource value.
 * @prop {object}     [geo]           - Thing location. 
 * @prop {number}     geo.lat         - Lattitude value. Available range between -90 and 90.
 * @prop {number}     geo.long        - Longitude value. Available range between -180 and 180.
 * 
 * @type {ThingValue[]}
 */
var values = [{
    key: 'temperature',
    value: 35,
    geo: {
        lat: 10,
        long: 25
    }
}];
/** 
 * @typedef          ManagmentOptions
 * @prop {boolean}   [broadcast=true]       - Define if the value need to be notified to the real-time channels (Like the widgets or in the devices subscribed to our Websockeet service)
 * @prop {boolean}   [store=true]           - Define if the value has to be stored in the database.
 * 
 * @type {ManagmentOptions}
 */
var params = {
    broadcast: true,
    store: true,
};

thethingsAPI.thingWrite(thingToken, values, params, function (error, result) { /* ... */  }) 

thethingsAPI.getProductThings(callback)

Returns an array with the configuration data of all the things in the device profile linked to the particular cloud code.

thethingsAPI.cloudFunction(fname, params, callback)

Calling a parser from a Cloud Code job, trigger or another parser through its name.

/** @type {string} */
var functionName = 'YOUR_CLOUD_CODE_FUNCTION_NAME';

/** @type {{ [key: string]: any }} */
var params = {
    // parameter1: 'hello',
    // parameter2: 2015,
    // parameter3: true,
    // ...
};

thethingsAPI.cloudFunction(functionName, params, function (error, result) { /* ... */  });

thethingsAPI.getGeofences(thingtoken,callback)

Retrieve the list of geofences from an organization.

/** @type {string} */
var thingtoken = 'YOUR_THING_TOKEN';

thethingsAPI.getGeofences(thingtoken, function (error, result) { /* ... */  });