thethings.iO Developer Center

Here you'll find everything you need to get started or go deep on developing IoT Products, Applications and Services with the thethings.iO IoT Platform.

Cloud Code Exposed APIs

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

email

Sends an email. You have to introduce your service provider credentials.

email(credentials, options)

  • credentials: object
    • service: one of 'SendGrid' | 'Mandrill' | 'SES' | 'Gmail'
    • auth: object
      • SendGrid: {api_user: string, api_key: string} // user and password account
      • Mandrill: {apiKey: string}
      • SES: {accessKeyId: string, secretAccessKey: string, region: string (ex: 'us-west-2')}
  • options: object
    • from : string (sender email)
    • to: string (receiver email)
    • subject: string
    • text: string (plain text)

In case you want to send HTML content in instead of plain text, you just have to substitute the property name "text" by "html".

SMS and voice calls with twilio

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

function trigger(params, callback){

  var telf = '+01666884107'
  var message = 'Warning: Temperature too high'

  var twilio = new Twilio(
    'AccountSid',
    'AuthToken'
  )

  twilio.sendMessage({
    to: telf, // Any number Twilio can deliver to
    from: '+01000000000', // A number you bought from Twilio and can use for outbound communication
    body: message // body of the SMS message
  },
    callback
  )
}
function trigger(params, callback){

  var telf = '+01666884107'

  var twilio = new Twilio(
    'AccountSid',
    'AuthToken'
  )

  twilio.makeCall({
    to: telf, // Any number Twilio can deliver to
    from: '+01000000000', // A number you bought from Twilio and can use for outbound communication
    url: message // A URL that produces an XML document (TwiML) which contains instructions for the call
  },
    callback
  )
}

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 message.

telegram.sendMessage(options, callback)

  • options: object
    • chat_id: number
    • message: string
    • custom_bot (optional): string
  • callback: function(error, result) (optional)
    • error: tells if the request has some bad argument
    • result: object
      • status: 'success' if the message was correctly sent, 'failed' if the request got any error.
      • description: If the status is true, it contains an object with the parameters used for the request. If it is failed, the description contains the response from the HTTP request.
function main(params, callback){
    var chat_id = 12345;
    var message = 'Hello world';
    var options = {chat_id : chat_id, text: message};
    telegram.sendMessage(options, function(err,result){
      if(err) return callback(err)
      callback(null, result)
    })
}

In case you want to use your own bot, you just have to add the bot token to the object options:

var chat_id = 12345;
var message = 'Hello world'
var custom_bot = '1a2b3c4f5e'
var options = {chat_id : chat_id, text: message, custom_bot: custom_bot};

Twitter

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

function trigger(params, callback){

   // Message to post
   var inputTwitter = {
     'status': 'A 140 character message :P'
   }

   // Your twitter API credentials
   var twitter = new Twitter({
      accessToken: '',
      accessTokenSecret: '',
      consumerKey: '',
      consumerSecret: ''
   });

   twitter.postTweet(inputTwitter, callback)
}

httpRequest

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

httpRequest(request, body, callback)

  • request: object
    • host: string
    • path: string
    • port: number || 80
    • method: string || 'GET'
    • secure: boolean || false
    • headers: object {'header-name': 'header-value'}
  • body: string
  • callback: function(error, result) (optional)
    • error: Tells if the request is invalid, e.g: There is an invalid chat_id or message.
    • result: object
      • status: 'success' if the message was sent correctly and 'failed' if not
      • result

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

console

Sends the parameter data to the developers console.

console.log(arg1, arg2, ..., argN)

console.error(arg1, arg2, ..., argN)

console.log(arg1, arg2, ..., argN)

  • argX: (string|number|object)

analytics.events

Allows to create and retrieve events.

analytics.events.create(event)

  • event: object
    • name: string
    • value: string

analytics.events.getByName(name, callback)

  • name: string
  • callback: function(error, data)
    • error: (null|string) if something has gone wrong
    • data: DataSet

The last hour/day events with eventName = name will be retrieved. Each element of the DataSet will have createdAt and value elements.

analytics.events.getValuesByName(name, callback)

  • name: string
  • callback: function(error, data)
    • error: (null|string) if something has gone wrong
    • data: DataSet

The last hour/day events with eventName = name will be retrieved. Each element of DataSet will be the value of the event with that name.

analytics.kpis

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

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

  • name: string
  • value: (string|number|object)
  • tags: [string]

Tags should be an array of Strings, containing only alphanumeric characters and "-" or "_".

thethingsAPI

Allows to Read and Write on a device resource, call functions from triggers and jobs and get the things of a product.

thethingsAPI.thingRead(thingToken, resourceName, callback)

  • thingToken: string
  • resourceName: string
  • callback: function(error, result)
    • error: tells if the request has got some error
    • result: response data

thethingsAPI.thingWrite(thingToken, values, callback)

  • thingToken: string
  • values: array(Object,...)
    • Object: {key:'resourceName', value:(string|number|object)}
  • callback: function(error, result)
    • error: tells if the request has got some error
    • result: response data

thethingsAPI.getProductThings(callback)

  • callback: function(error, things)
    • error: tells if the request has got some error
    • things: response data. Array of objects containing thing data
{
  "_id": "thingID",
  "lastSeen": "2019-03-13T09:33:25.915Z",
  "lastRead": "2019-03-13T09:33:25.915Z",
  "lastWrite": "2019-03-13T09:31:35.569Z",
  "thingToken": "thingToken",
  "description": {
    "geo": {
      "lat": 41.41221147518526,
      "long": 2.2204078443313624
    },
    "name": "Barcelona"
  },
  "createdAt": "2019-01-28T12:20:26.796Z",
  "users": [],
  "tags": [
    {
      "_id": "bcn",
      "name": "BCN"
    }
  ],
  "billType": "Yearly"
}

thethingsAPI.cloudFunction(fname, params, callback)

  • fname: string. The function name.
  • params: Any type. The input.
  • callback: function(error, result)
    • error: tells if the request has some error
    • result: response data
function trigger(params, callback){
  var thingToken = params.thingToken

  thethingsAPI.thingRead(thingToken, 'temperature', function (err, result) {

  var values = {values : [{key: 'avg-temperature', value: result[0].value}]}
    thethingsAPI.thingWrite(thingToken, values, function () { callback() })
  })
}

DataSet

This class represents an abstraction of data returned from analytics.events.getByName This class allows chaining.

📘

Tip

  • means any type of element.

DataSet DataSet.prototype.map(fn)
Applies fn to each value in the DataSet. i.e. ResultDataSet[i] = fn(DataSet[i])

  • fn: * function(value)
    • value: * one element from the DataSet

DataSet DataSet.prototype.filter(fn)
Returns a new DataSet where its elements are the ones where fn(oldDataSet[i]) == true

  • fn: boolean function(value)
    • value: *

Any DataSet.prototype.reduce(fn, init)
Returns fn(...fn(fn(fn(init, DataSet[0]), DataSet[1]), DataSet[2]),...) but the execution order is undefined. i.e. fn should be commutative and associative.

  • fn: * function(prev, cur)
    • prev: * previous aggregated value
    • cur: current value
  • init: * initialization value
// the product of all the elements of the dataset would be
var product = ds.reduce(function(prev, cur){return prev*cur},1)

DataSet DataSet.prototype.sort(fn)
Returns a new DataSet with the first n elements (and skiping s) from the old.

  • fn: number function(a,b) (optional) comparing function returns < 0 if a goes before b

DataSet DataSet.prototype.take(n, s)

  • n: num elements to take
  • s: num elements to skip (optional)

DataSet DataSet.prototype.deltaR(fn, last)
Applies fn to each pair of consecutive elements in the DataSet.

  • fn: * function(cur,next) (optional) function that is applied to each pair of consecutive elements and stored in cur
  • last: * (opitional) a virtual element to add temporary in the last element of the DataSet
function(cur, next){
  if(cur.value){
    return next.value - cur.value
  }else{
    return next - cur
  }
}

DataSet DataSet.prototype.deltaL(fn, first)
Applies fn to each pair of consecutive elements in the DataSet.

  • fn: * function(prev,cur) (optional) function that is applied to each pair of consecutive elements and stored in cur
  • first: * (opitional) a virtual element to add temporarily in the first element of the DataSet
function(prev, cur){
  if(cur.value){
    return next.value - cur.value
  }else{
    return next - cur
  }
}

Number DataSet.prototype.count()
Returns the number of elements in the DataSet

Number DataSet.prototype.sum()
Returns the sum of all elements in the DataSet

Number DataSet.prototype.prod()
Returns the product of all elements in the DataSet

Number DataSet.prototype.avg()
Returns the average of all elements in the DataSet

Number DataSet.prototype.wavg()
Returns the weighted average of all elements in the DataSet.

That is, weight each value with the time it was active. For example, if there have been 20 degrees during 2 hours and 15 degrees during 1 hour. Then wavg() will be 2/3 20 + 1/3 15 = 18.3.

Number DataSet.prototype.max()
Returns the max element of the DataSet

Number DataSet.prototype.min()
Returns the min element of the DataSet

DataSet DataSet.prototype.sample(p)
Returns a new DataSet where each element has probability p to be in the new DataSet

  • p: number 0 <= p <= 1

Array DataSet.prototype.percentiles(splits, fn)
Splits the data in splits parts, gets the median (if were previously sorted) of each one and returns fn(median)

  • splits: number
  • fn: * function(value)

Array DataSet.prototype.collect()
Returns the data in form of an array

Updated 2 years ago

Cloud Code Exposed APIs


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.