operateData - device_token of device which received the last data

I would like to use the snippet operateData. This snippet requires as environment variables device_token to be set in advance.

I prefer not to set the device_token as a fixed variable because I want to use the code for multiple sensors. Is it possible to get the device_token of the device which was the last one in receiving data?

Actually I want to avoid setting up an Analysis for each single device.

Hi @Pauwel,
Yes, that is possible.

In order to do that, you need to use the Utils.getTokenByName function from TagoIO’s sdk.
Bellow is a quick code on how to do that. You will need to generate a Account-token and enter it in your environment variable instead.

** Steps to generate an account_token:
** 1 - Enter the following link: https://admin.tago.io/account/
** 2 - Select your Profile.
** 3 - Enter Tokens tab.
** 4 - Generate a new Token with Expires Never.
** 5 - Press the Copy Button and place at the Environment Variables tab of this analysis.

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

async function startAnalysis(context, scope) {
  if (!scope.length) return context.log('Analysis must be triggered by an action/widget');

  const env_vars = Utils.envToJson(context.environment);
  if (!env_vars.account_token) {
    return context.log('Missing account_token environment variable');

  const account = new Account({ token: env_vars.account_token });

  // Get the device id from the first variable available;
  const device_id = scope[0].origin;
  const device_token = await Utils.getTokenByName(account, device_id);
  const device = new Device({ token: device_token });

  const last_15_data = await device.getData({ qty: 15 });

module.exports = new Analysis(startAnalysis);

Great! Got that up and running. Thanks!