/**
* Update the value of a Tag without affecting others
*/
const { Account, Analysis, Device, Utils, Services } = require("@tago-io/sdk");
async function updateTag(context, scope) {
// Requires scope to know what device and what widget called it
if (!scope[0]) throw "Scope is missing";
// Read the stored account_token and make an account object
const env_vars = Utils.envToJson(context.environment);
const account = new Account({ token: env_vars.account_token });
// Get the device id of the caller
const {origin} = scope[0];
// Get the new tag value from the widget. Change "VARIABLE_NAME" to match that within the input form.
const new_tag = scope.find(x => x.variable === 'constant_a');
console.debug(`Device: ${scope[0].device}`);
// Get the device's info using its ID, then isolate the tags
const device_info = await account.devices.info(origin);
var tags = device_info.tags;
//A
//B1
// Search for the Tag Key you want to edit "KEY_NAME"
let i
for(i = 0; i < tags.length; i++){
// Find the Key/Value pair you want to edit
// C
if(tags[i].key == "device_constant_a"){
//B2
// Set the VALUE of the pair you want to edit to the one provided by the input form
tags[i].value = new_tag.value;
break;
}
}
// Push the new set of tags to the device. You're done!
account.devices.edit(origin, { tags });
//C
}
module.exports = new Analysis(updateTag);