/**
* Logic:
* 1. Iterates through ALL entities in the platform using `executeWithAsyncPaging` (efficient pagination).
* 2. Calculates the average of the `device.powersupply.battery.charge` values across all entities.
* 3. Update "VentanaPrincipal" value with the global average.
* 4. If the floor of average is even, changes "VentanaPrincipal" status to Red (#FF0000).
* 5. If the floor of average is odd, changes "VentanaPrincipal" status to Green (#00FF00).
*/
var totalCharge = 0;
var count = 0;
// 1. Create the builder
var builder = $api.entitiesSearchBuilder()
.limit(2000) // Max limit per page
.flattened();
// 2. Execute with async paging
// executeWithAsyncPaging(resourceName) returns a Promise
return builder.build().executeWithAsyncPaging('entities').then(
// Success Callback (called when all pages are processed)
function() {
// 4. Calculate Average
var average = count > 0 ? totalCharge / count : 0;
// 5. Determine color based on parity of the floor of the average
var floorAvg = Math.floor(average);
var isEven = floorAvg % 2 === 0;
var color = isEven ? "#FF0000" : "#00FF00";
// 6. Set the item status and value
setItemStatus("VentanaPrincipal", color);
setValueToItem("VentanaPrincipal", "Battery Avg", average.toFixed(2));
},
// Error Callback
function(err) {
console.error("Error in paging:", err);
},
// Notify Callback (called for each page of results)
function(pageData) {
if (pageData && pageData.length > 0) {
pageData.forEach(function(entity) {
// Access the battery charge field
var batteryField = entity['device.powersupply.battery.charge'];
if (batteryField && batteryField._value && batteryField._value._current && batteryField._value._current.value) {
var val = parseFloat(batteryField._value._current.value);
if (!isNaN(val)) {
totalCharge += val;
count++;
}
}
});
}
}
);