// To run analysis on your machine (external)
// module.exports = new Analysis(myAnalysis, { token: "YOUR-TOKEN" });
const TagoDevice = require('tago/device');
const TagoAccount = require('tago/account');
const TagoUtils = require('tago/utils');
const TagoAnalysis = require('tago/analysis');
const moment = require('moment-timezone');
async function checkIn(context) {
const env_var = TagoUtils.env_to_obj(context.environment);
if (!env_var.account_token) return context.log('Missing account_token environment var');
const account = new TagoAccount(env_var.account_token);
// Here are some othe example of filter you can use:
// Get all devices with tag key = lt-10 and value = gps
const devices = await account.devices.list(1, ['id', 'name'], { tags: [{ key: 'lt-10', value: 'gps' }] }, 2000);
if (!devices.length) return;
const now = moment.utc().format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
const serie = Date.now();
// If min_time = 10, you will receive an alert for
// every device that does not send data for more than 10 minutes
const min_time = 1;
await Promise.all(devices.map(async (dev) => {
const token = await TagoUtils.getTokenByName(account, dev.id);
const deviceToBeChecked = new TagoDevice(token);
const [lastData] = await deviceToBeChecked.find({ variable: 'location', qty: 1, query: 'last_item'});
const minutes = moment(now).diff(lastData.time, 'minutes');
if (minutes > Number(min_time)) {
await deviceToBeChecked.insert({ variable: 'alarm_errors', value: 'Offline', serie }).then(context.log);
};
}));
context.log('checkin succesfully finished');
}
module.exports = new TagoAnalysis(checkIn, 'ANALYSIS TOKEN HERE')