Change Item Status by Battery Charge

Code

/**
 * 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
var builder = $api.entitiesSearchBuilder()
    .limit(50)
    .flattened();

// 2. Execute the query
var response = await builder.build().execute();

var totalCharge = 0;
var count = 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
        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++;
            }
        }
    });
}

// 4. Calculate Average
var average = count > 0 ? totalCharge / count : 0;

// 5. Determine color based on parity of the floor of the average
// Even -> Red "#FF0000"
// Odd -> Green "#00FF00"
var floorAvg = Math.floor(average);
var isEven = floorAvg % 2 === 0;
var color = 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;