Passing current device id from blueprint dashboard to analysis

Hi,

On a blueprint dashboard, I have a widget with a button “Generate report”. After clicking, it should grab X values from the currently selected device and send to some email address.
I’ve already found topics which explain how to create device token using its ID, but I don’t know how to pass the ID from the widget button click to the analysis script.
I know I can pass something with the scope, but those are hardcoded values, so that doesn’t really help here (or at least I don’t know how to use it).

hi @fssolution,

When you submit your form, all the variables submitted will be sent to the analysis scope. The scope is an array of variables object, like:

[
    {
      "id": "60e3f46e13d8a50018ec361e",
      "origin": "5fd0dbf10f3bce001c689744",
      "serie": "1625551982491",
      "time": "2021-07-06T02:42:00.000Z",
      "value": "field 1 content",
      "variable": "field_1"
    },
    {
      "id": "60e3f46ee77a40001857e1f9",
      "origin": "5fd0dbf10f3bce001c689744",
      "serie": "1625551982720",
      "time": "2021-07-06T02:42:00.000Z",
      "value": "field 2 content",
      "variable": "field_2"
    }]

Where the key ORIGIN is the device ID.

Here is an example of analysis managing data submitted from the form widget.

const { Analysis, Account, Utils } = require('@tago-io/sdk');

async function init(context, scope) {
  if (!scope[0]) return context.log('This analysis must be triggered by a widget.');

  context.log('your analysis started');
  // Get the environment variables.
  const env = Utils.envToJson(context.environment);
  if (!env.account_token) return context.log('Missing "account_token" environment variable');
  else if (env.account_token.length !== 36) return context.log('Invalid "account_token" in the environment variable');

  // Instance the Account class
  const account = new Account({ token: env.account_token });

  // getting a variable submitted from FORM Widget
  const your_form_field = scope.find(x => x.variable === "your_form_field");

  // getting device token using account and origin (device id)
  const device_token = await Utils.getTokenByName(account, your_form_field.origin); // using origin (device id) to get the device token
  const your_device = new Device({ token: device_token });
  // work with your device...
}

module.exports = new Analysis(init);

NOTE: To resolve tokens from all devices you need to use your ACCOUNT TOKEN, here is all details about it.

1 Like