Share via


PowerGridForecast Clase

Definición

Contiene información sobre la red eléctrica a la que está conectado el dispositivo. Los datos están diseñados para usarse en una previsión para cambiar el tiempo en el que se producen las cargas de trabajo o reducir el consumo de energía durante momentos intensos.

public ref class PowerGridForecast sealed
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Devices.Power.PowerGridApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class PowerGridForecast final
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Devices.Power.PowerGridApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class PowerGridForecast
Public NotInheritable Class PowerGridForecast
Herencia
Object Platform::Object IInspectable PowerGridForecast
Atributos

Requisitos de Windows

Familia de dispositivos
Windows Desktop Extension SDK (se introdujo en la versión 10.0.26100.0)
API contract
Windows.Devices.Power.PowerGridApiContract (se introdujo en la versión v1.0)

Ejemplos

using Windows.Devices.Power;

void PrintBestTimes(PowerGridForecast forecast)
{
    double bestSeverity = double.MaxValue;
    double bestLowImpactSeverity = double.MaxValue;
    DateTime bestTime = DateTime.MaxValue;
    DateTime bestLowImpactTime = DateTime.MaxValue;
    TimeSpan blockDuration = forecast.BlockDuration;
    DateTime startTime = forecast.StartTime;
    IList<PowerGridData> forecastSignals = forecast.Forecast;

    if (forecastSignals.Count == 0)
    {
        Console.WriteLine("Error encountered with getting forecast; try again later.");
        return;
    }

    foreach (PowerGridData data in forecastSignals)
    {
        if (data.Severity < bestSeverity)
        {
            bestSeverity = data.Severity;
            bestTime = startTime;
        }

        if (data.IsLowUserExperienceImpact && data.Severity < bestLowImpactSeverity)
        {
            bestLowImpactSeverity = data.Severity;
            bestLowImpactTime = startTime;
        }

        startTime = startTime + blockDuration;
    }

    if (bestLowImpactTime != DateTime.MaxValue)
    {
        DateTime endBestLowImpactTime = bestLowImpactTime + blockDuration;
        Console.WriteLine($"Lowest severity during low impact is {bestLowImpactSeverity}, which starts at {bestLowImpactTime.ToString()}, and ends at {endBestLowImpactTime}.");
    }
    else
    {
        Console.WriteLine("There's no low-user-impact time in which to do work.");
    }

    if (bestTime != DateTime.MaxValue)
    {
        DateTime endBestSeverity = bestTime + blockDuration;
        Console.WriteLine($"Lowest severity is {bestSeverity}, which starts at {bestTime.ToString()}, and ends at {endBestSeverity.ToString()}.");
    }
}

PowerGridForecast forecast = PowerGridForecast.GetForecast();
PrintBestTimes(forecast);
#include "pch.h"
#include <iostream>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Devices.Power.h>

using namespace winrt::Windows::Devices::Power;
using namespace winrt::Windows::Foundation::Collections;
using namespace winrt::Windows::Foundation;

void PrintFullForecast(PowerGridForecast const& forecast)
{
    IVectorView<PowerGridData> forecastSignals = forecast.Forecast();
    DateTime forecastStartTime = forecast.StartTime();
    TimeSpan forecastBlockDuration = forecast.BlockDuration();
    DateTime blockStartTime = forecastStartTime;

    // On failure the forecast will be empty.
    if (forecastSignals.Size() == 0)
    {
        std::wcout << L"Error encountered while reading the forecast; try again later." << std::endl;
        return;
    }

    // Iterate through the forecast printing all the data.
    for (auto const& block : forecastSignals)
    {
        auto severity = block.Severity();
        auto isLowImpact = block.IsLowUserExperienceImpact();

        std::wcout << L"Start time - ";
        PrintDateTime(blockStartTime, true);
        std::wcout << L" | End time - ";
        PrintDateTime(blockStartTime + forecastBlockDuration, true);
        std::wcout << L" | Intensity - " << severity << L" | IsLowImpactTime - " << (isLowImpact ? L"TRUE" : L"FALSE") << std::endl;

        blockStartTime = blockStartTime + forecastBlockDuration;
    }
}

void PrintBestTimes(PowerGridForecast const& forecast)
{
    IVectorView<PowerGridData> forecastSignals = forecast.Forecast();
    DateTime forecastStartTime = forecast.StartTime();
    TimeSpan forecastBlockDuration = forecast.BlockDuration();
    DateTime blockStartTime = forecastStartTime;

    // On failure the forecast will be empty
    if (forecastSignals.Size() == 0)
    {
        std::wcout << L"Error encountered while reading the forecast; try again later." << std::endl;
        return;
    }

    DateTime bestSeverityTimeUTC = DateTime::max();
    DateTime bestSeverityTimeInLowUserImpactTimeUTC = DateTime::max();

    // 1.0 is maximum severity the API can return.
    double bestSeverity = 1.0;
    double bestSeverityInLowUserImpactTime = 1.0;

    // Iterate through the forecast looking for the best times.
    for (auto const& block : forecastSignals)
    {
        auto severity = block.Severity();
        auto isLowImpact = block.IsLowUserExperienceImpact();

        // Check if there is lower severity
        if (severity < bestSeverity)
        {
            bestSeverity = severity;
            bestSeverityTimeUTC = blockStartTime;
        }

        // Check whether there's a lower severity that's also at a time with low user impact.
        if (isLowImpact && severity < bestSeverityInLowUserImpactTime)
        {
            bestSeverityInLowUserImpactTime = severity;
            bestSeverityTimeInLowUserImpactTimeUTC = blockStartTime;
        }

        blockStartTime = blockStartTime + forecastBlockDuration;
    }

    // Print out the best times only if they've been set.
    if (bestSeverityTimeUTC != DateTime::max())
    {
        std::wcout << L"Best time to do work is ";
        PrintDateTime(bestSeverityTimeUTC, true);
        std::wcout << L" with a severity of " << bestSeverity;
        std::wcout << L" and ends at ";
        PrintDateTime(bestSeverityTimeUTC + forecastBlockDuration, true);
        std::wcout << std::endl;
    }

    if (bestSeverityTimeInLowUserImpactTimeUTC != DateTime::max())
    {
        std::wcout << L"Best time with low user impact is ";
        PrintDateTime(bestSeverityTimeInLowUserImpactTimeUTC, true);
        std::wcout << L" with a severity of " << bestSeverityInLowUserImpactTime;
        std::wcout << L" and ends at ";
        PrintDateTime(bestSeverityTimeInLowUserImpactTimeUTC + forecastBlockDuration, true);
        std::wcout << std::endl;
    }
    else
    {
        std::wcout << "There's no low-user-impact time in which to do work." << std::endl;
    }
}

int main() 
{
    std::wcout << L"Power Grid Forecast WinRT API sample app." << std::endl;

    // Register for the forecast notification.
    auto revoker = PowerGridForecast::ForecastUpdated(winrt::auto_revoke, [&](auto, winrt::Windows::Foundation::IInspectable const&) {
        std::wcout << L"Forecast updated..." << std::endl;

        // Forecast has been updated; find the next best times.
        PowerGridForecast forecast = PowerGridForecast::GetForecast();
        PrintBestTimes(forecast);
    });

    // Print out the full forecast.
    PowerGridForecast forecast = PowerGridForecast::GetForecast();
    PrintFullForecast(forecast);

    // Wait until the user presses a key to exit.
    std::cout << "Listening to the signal: a new forecast has been created."
                    "Leave this program open to see when a new forecast is created, otherwise press any key to exit this program..." << std::endl;
    std::cin.get();

    return 0;
}

Comentarios

Windows expone las previsiones de emisiones de carbono de la red eléctrica en función de la red eléctrica a la que está conectado el dispositivo. Estos datos ya se usan en Windows Update, por ejemplo, para cambiar el tiempo cuando se producen actualizaciones con el fin de reducir las emisiones de carbono. Esta API expone estas mismas previsiones para que pueda reducir las emisiones de carbono de algunas de las cargas de trabajo. Por ejemplo, podría cambiar el tiempo cuando se produzcan actualizaciones de las aplicaciones o juegos; o limita la velocidad de bits de la reproducción de audio o algún otro nivel de fidelidad de representación; o habilitar un modo de eficiencia, si tiene uno.

La API de previsión de la red eléctrica proporciona dos señales (para preguntar el cambio de tiempo). Una señal contiene un valor de gravedad normalizado (entre 0,0 y 1,0) de condiciones de cuadrícula para optimizar (intensidad del carbono). La otra señal, IsLowUserExperienceImpact, es un valor booleano que representa cuando Windows cree que el usuario estará fuera del dispositivo. Puede optar por usar solo una señal en lugar de ambas; las señales tienen un valor individual, así como juntos.

El cambio de tiempo significa usar la misma energía para realizar el trabajo, pero hacerlo en un momento diferente en función de una señal.

La gravedad es un valor normalizado entre 0,0 y 1,0, donde 0 se considera mejor y 1 es el peor. Esto corresponde a la gravedad del carbono de la red eléctrica en función de dónde se encuentra el dispositivo.

Impacto bajo en la experiencia del usuario. Valor booleano que representa cuando Windows cree que el usuario estará ausente o no usará muchos recursos. Esto puede considerarse como horas activas inversas. Cuando el valor es true, se considera un buen momento para desplazar las cargas de trabajo. Cuando es false, se considera un mal momento para desplazar las cargas de trabajo a, en términos de experiencia del usuario.

Propiedades

BlockDuration

Duración de cada elemento del vector Forecast .

Forecast

Obtiene un vector que contiene los datos de previsión. La previsión es contigua y comienza en StartTime. La hora de inicio de cada elemento se puede calcular con StartTime + (index * BlockDuration).

StartTime

Obtiene la hora de inicio del primer elemento de Forecast.

Métodos

GetForecast()

Método estático para recuperar la previsión. Tras un error, esto devolverá una previsión vacía.

Eventos

ForecastUpdated

Evento para notificar a los suscriptores cuando una nueva carga de previsión está lista. Se espera que, cuando la aplicación reciba esta notificación, llamará a GetForecast.

Se aplica a