/**
* Logic:
* 1. Queries a sample of maximum 50 entities.
* 2. Calculates the average of the `device.powersupply.battery.charge` values.
* 3. Update "VentanaPrincipal" value with the 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).
*/// 1. Create the builder to search for entities, limiting to 50
varbuilder=$api.entitiesSearchBuilder()
.limit(50)
.flattened();
// 2. Execute the query
varresponse=awaitbuilder.build().execute();
vartotalCharge=0;
varcount=0;
// 3. Iterate through the results and sum the battery charge
if (response&&response.data&&response.data.entities) {
response.data.entities.forEach(function(entity) {
// Access the battery charge field
// Field: device.powersupply.battery.charge
varbatteryField=entity['device.powersupply.battery.charge'];
if (batteryField&&batteryField._value&&batteryField._value._current&&batteryField._value._current.value) {
varval= parseFloat(batteryField._value._current.value);
if (!isNaN(val)) {
totalCharge+=val;
count++;
}
}
});
}
// 4. Calculate Average
varaverage=count>0?totalCharge/count:0;
// 5. Determine color based on parity of the floor of the average
// Even -> Red "#FF0000"
// Odd -> Green "#00FF00"
varfloorAvg= Math.floor(average);
varisEven=floorAvg%2===0;
varcolor=isEven?"#FF0000":"#00FF00";
// 6. Set the item status and value
// setItemStatus(itemID, [rgbColor(string format)|null])
setItemStatus("VentanaPrincipal", color);
// setValueToItem(itemID, alias, value)
setValueToItem("VentanaPrincipal", "Battery Avg", average.toFixed(2));
// Use return as the function is async
return;