Adding data that arrive from device

Hello everyone. I need an example of analysis that can sum up the data that arrives from a certain variable. The total amount has to be shown on the cylinder widget.

I have no experience with codes, thank you if you can give me a ready example.

Hi Leandro,

Sorry for the delay, I’ve just finished creating you an analysis example for your need. I will paste the code below.

const {Analysis, Utils, Services, Account, Device, Types} = require("@tago-io/sdk");
import getDevice from "./lib/getDevice";
import { parseTagoObject } from "./lib/data.logic";

async function handler(context, scope) {
  context.log(JSON.stringify(scope));
  context.log("Running Analysis");

  //must have the environment variables set at analysis -> environment variables
  const environment = Utils.envToJson(context.environment);
  if (!environment) {
    return;
  }

  if (!environment.config_token) { //blueprint device token
    throw "Missing config_token environment var";
  } else if (!environment.account_token) { //profile token
    throw "Missing account_token environment var";
  }

  //instanciating user device and account
  const config_dev = new Device({ token: environment.config_token });
  const account = new Account({ token: environment.account_token });

  const customer_dev = await getDevice(account, scope[0].origin);
  //choose the variable name to sum up here
  const result = await customer_dev.getData({ qty: 9999, variable: "temperature" });

  //data to be saved on bucket
  const data_to_bucket = {
    sum: 0,
  };

  //looping through each object found and summing up the values
  result.forEach((x) => (data_to_bucket.sum = data_to_bucket.sum + x.value));

  //parsing data to tagoIO structure to be saved on bucket
  await config_dev.sendData(parseTagoObject(data_to_bucket));

  //fetching the data saved on bucket -> e.g. you can use this information on a widget
  const finalSum = await customer_dev.getData({ query: "last_item", variable: "sum" });

  //console logging the final result
  console.log(finalSum[0].value);
}

async function startAnalysis(context, scope) {
  try {
    await handler(context, scope);
    context.log("Analysis finished");
  } catch (error) {
    console.log(error);
    context.log(error.message || JSON.stringify(error));
  }
}

//insert your token heres
export default new Analysis(startAnalysis, { token: "28cf6f8b-a9d7-4ed1-b328-353ddded62c9" });

Remmembering you that we provide further support if needed, please dont hesitate in contact us.

Thank you.
Guilherme Oliveira