Sum of data for a selected time period?

@Andrew Sevil

Hi, is it possible to have a widget display the total of a variable over a time period specified by the widget?
So if I set the widget to show the last 7 days of a variable (lets say rainfall), the result is the total of the period displayed?

@Guilherme Costa

Hi @sevils,

Sorry for the answering delay. In order to accomplish that you’re going to need an analysis to run, get all the variables of your device and filter the ones which match the wanted period. I’ve coded that script for you with coments, you can run that script every time you want to display that sum or even increment it to do automatically, with actions or other approach.

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

const moment = require("moment-timezone");

async function handler(context) {
  context.log("Running Analysis");

  //enter the token of the wanted device 
  const device = await new Device({ token: "a9049d16-f528-4a39-9559-1232e21321312" });

  //choose the correct variable which you want to add
  const data = await device.getData({ variables: "temperature", qty: "9999" });

  //choose the number of days which will be the period
  const wanted_data = data.filter((x) => moment().diff(moment(x.time), "days") < 7);

  let sum = 0;

  wanted_data.forEach(x => sum = x.value + sum);

  //choose the variable which you want to store the result (it will be send to the same device which is being processed the sum, if you want to store in another device please instantiate other one)
  await device.sendData({variable: "sum", value: sum});

  context.log(sum);
}

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

module.exports = new Analysis(startAnalysis);

// export default new Analysis(startAnalysis, { token: "****************" });

Let me know if it have worked for you!

Thanks,
Guilherme Oliveira

Hi Digital Twin Services,

Currently, our Frontend doesn’t have any implementations to utilize the Aggregated Queries.

A way you could use them without Analysis is by creating a custom widget that uses those queries.

Hi Digital Twin Services,

Right, I have the following tutorial on how to create a custom widget which can help you out.

Correct, You can use the SDK to query the data similar to how the example uses the SDK to send data. Yes this will count towards your data output.

Hope this helps!