const { Account, Device, Analysis, Utils } = require('@tago-io/sdk');
async function myAnalysis(context, scope) {
if (!scope[0]) return context.log('scope is required');
// location is the name of the device variable. Feel free to change this name.
const location_device = scope.find(x => x.variable === 'location');
if (!location_device && !location_device.location) return context.log('the location variable is required');
const battery = scope.find((x) => x.variable === "batv"); // BATTERY VARIABLE
if (!battery && !battery.location) return context.log('the batv variable is required');
const env = Utils.envToJson(context.environment);
if (!env.account_token) return context.log('Missing "account_token" environment variable');
// your general device token
if (!env.general_token) return context.log('Missing "general_token" environment variable');
const account = new Account({ token: env.account_token });
const sensor_info = await account.devices.info(location_device.device);
// Uncomment below to add links to metadata
var tags = sensor_info.tags;
let i;
var link;
for(i = 0; i < tags.length; i++){
// Find the tracker KEY from device tags
if(tags[i].key == "tracker"){
// Assing tracker dashboard links depending on KEY value
if (tags[i].value == "oyster") {
}
else if (tags[i].value == "g62") {
}
break;
}
}
const data = [{
variable: 'Tracker',
value: sensor_info.name,
location: location_device.location,
// Add link to tracker metadata so it can be displayed as link in infobox
metadata: {
url_pin: {
url: link,
alias: "View tracker"}},
group: sensor_info.id
},
{
variable: 'Battery',
unit: 'V',
value: battery.value,
location: location_device.location,
group: sensor_info.id,
}
];
const general_dev = new Device({ token: env.general_token });
await general_dev.deleteData({ groups: sensor_info.id });
await general_dev.sendData(data);
}
module.exports = new Analysis(myAnalysis, { token: 'analysis-token' });