Passing Parameters to Analysis (ex. Device_token)

Hi!

I have multiple devices with miltiple buckets. I want to execute a script when this devices receive any packet and the script is equal except the paramenter “device_token” used to access device bucket. Is there any way to use the same script for all devices, just passing a parameter that contains the device_token? Otherwise, will I have to write a script for each device?

Thanks!

Hi Ricardo,
When an analysis is trigerred by a data, you will receive the data in the scope parameter of your analysis.
If this is your case, you can get the token using the parameter “scope[0].origin”, which is the Device ID.

Another way, if you’re not triggering your analysis with a data, is to get your device list, filtering by tags, and then get the device token for each device.
https://sdk.js.tago.io/en/latest/analysis.html#gettokenbyname

In order to get the token, TagoIO provides a help function through the tago/utils library.

Here is a few examples:

const TagoAnalysis = require('tago/analysis');
const TagoAccount = require('tago/account');
const TagoUtils = require('tago/utils');
const TagoDevice = require('tago/device');

async function myAnalysis(context, scope) {
  if (!scope) return;

  const environment = TagoUtils.env_to_obj(context.environment);
  if (!environment) return;
  else if (!environment.account_token) throw 'Missing account_token environment var';

  // Create all services objects needed.
  const account = new TagoAccount(environment.account_token);
  const { origin } = scope[0];

  const device_token = await TagoUtils.getTokenByName(account, origin);
  const device = new TagoDevice(device_token);

  device.insert({ variable: 'test', value: 1 }).then(context.log, context.log);
} 
module.exports = new TagoAnalysis(myAnalysis, 'YOUR-ANALYSIS-TOKEN');

If you need to get from a list:

const TagoAnalysis = require('tago/analysis');
const TagoAccount = require('tago/account');
const TagoUtils = require('tago/utils');
const TagoDevice = require('tago/device');

async function myAnalysis(context, scope) {
  const environment = TagoUtils.env_to_obj(context.environment);
  if (!environment) return;
  else if (!environment.account_token) throw 'Missing account_token environment var';

  // Create all services objects needed.
  const account = new TagoAccount(environment.account_token);
   const device_list = await account.devices.list(1, ['id', 'name', 'bucket'], { tags: [{ key: 'tagkey', value: 'tagvalue ' }] }, 100);

  for (const device_obj of device_list) {
    const device_token = await TagoUtils.getTokenByName(account, device_obj.id);
    const config_dev = new TagoDevice(device_token);
    config_dev.insert({ variable: 'test', value: 1 }).then(context.log, context.log);
  }
}

module.exports = new TagoAnalysis(myAnalysis, 'YOUR-ANALYSIS-TOKEN');
1 Like

It Works!

Thanks @vitor.