const { Analysis, Device } = require("@tago-io/sdk");
const { Utils } = require("@tago-io/sdk");
async function monitorAndDelete(context) {
// Load environment variables
const envVars = Utils.envToJson(context.environment);
context.log("Environment variables loaded:", JSON.stringify(envVars));
const deviceToken = envVars.device_token;
// Check if device token is set
if (!deviceToken) {
context.log("Error: Device token not found in environment variables.");
return;
}
const device = new Device({ token: deviceToken });
// Check if data is available in the context
if (!context.data) {
context.log("No data received in context.");
return;
}
if (!Array.isArray(context.data)) {
context.log("Data received but not in array format.");
return;
}
// Iterate through all incoming data
const groupsToDelete = new Set();
for (const dataPoint of context.data) {
if (!dataPoint.value || !dataPoint.group) {
context.log(`Skipping data point without value or group: ${JSON.stringify(dataPoint)}`);
continue;
}
try {
const buffer = Buffer.from(dataPoint.value, "hex");
const fPort = buffer[1]; // Adjust based on your payload structure
if (fPort === 4) {
context.log(`Marking group for deletion with Group ID: ${dataPoint.group}`);
groupsToDelete.add(dataPoint.group);
} else {
context.log(`Data received on fPort ${fPort}, no action taken.`);
}
} catch (error) {
context.log(`Error processing data point: ${error.message}`);
}
}
// Delete all data points for marked groups
if (groupsToDelete.size > 0) {
try {
for (const group of groupsToDelete) {
context.log(`Deleting all data for Group ID: ${group}`);
await device.deleteData({ groups: [group] });
context.log(`Successfully deleted data for Group ID: ${group}`);
}
} catch (error) {
context.log(`Error deleting data for groups: ${error.message}`);
}
} else {
context.log("No groups marked for deletion.");
}
}
module.exports = new Analysis(monitorAndDelete);