갑자기 필요해서 UWP, 정확히는 내 윈폰에서 배터리 상태를 얻어올 필요가 생겨서 급히 찾아봤다.
Windows::Devices::Power 네임스페이스의 API를 사용하면 된다는 정보는 금방 찾았지만 C++로 구현하는 자료는 어디에도 없다. 아무리 뒤져봐도 없다.
C#이라면 이런 식으로 간단하게 구현할 수 있다.
private void RequestAggregateBatteryReport()
{
// Create aggregate battery object
var aggBattery = Battery.AggregateBattery;
// Get report
var report = aggBattery.GetReport();
// Update UI
AddReportUI(BatteryReportPanel, report, aggBattery.DeviceId);
}
이 스타일 그대로 C++로 바꿔서 코딩해보면 컴파일에 실패한다. Battery^ 객체를 직접 억세스하는건 불가능한것 같다.
그 다음 시도. 아래와같은 방법으로 배터리 정보를 얻어올수 있다.
async private void RequestIndividualBatteryReports()
{
// Find batteries
var deviceInfo = await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());
foreach(DeviceInformation device in deviceInfo)
{
try
{
// Create battery object
var battery = await Battery.FromIdAsync(device.Id);
// Get report
var report = battery.GetReport();
// Update UI
AddReportUI(BatteryReportPanel, report, battery.DeviceId);
}
catch { /* Add error handling, as applicable */ }
}
}
이걸 C++코드로 바꿔서 짜보면 다음과 같다.
auto DeviceID = Windows::Devices::Power::Battery::GetDeviceSelector();
create_task(Windows::Devices::Enumeration::DeviceInformation::FindAllAsync(DeviceID)).then([](Windows::Devices::Enumeration::DeviceInformationCollection^ devices)
{
for each (auto dev in devices)
{
create_task(Windows::Devices::Power::Battery::FromIdAsync(dev->Id)).then([](Windows::Devices::Power::Battery^ battery)
{
auto report = battery->GetReport();
int RemainingCapacityInMilliwattHours = report->RemainingCapacityInMilliwattHours->Value;
int FullChargeCapacityInMilliwattHours = report->FullChargeCapacityInMilliwattHours->Value;
int ChargeRateInMilliwatts = report->ChargeRateInMilliwatts->Value;
int DesignCapacityInMilliwattHours = report->DesignCapacityInMilliwattHours->Value;
int remained_power = (int)( (float)RemainingCapacityInMilliwattHours / (float)FullChargeCapacityInMilliwattHours * 100.0f );
WCHAR wchTxt[128] = {};
swprintf_s(wchTxt, L"Battery Remained Power : %d, Capacity : %d / %d \n", remained_power, FullChargeCapacityInMilliwattHours, DesignCapacityInMilliwattHours);
OutputDebugString(wchTxt);
});
}
});
OK. 이쪽은 빌드도 되고 작동도 잘 된다. 아이 쉬바…이게 뭔 지랄이야.
정말 짜증난다. C++ 쓰지 말라는거지.
다행히도 Windows 10 15063빌드부터 UWP에서 win32의 GetSystemPowerStatus()를 사용할 수 있다. 물론 이 자료도 MSDN에 갱신되어있지 않다. MSDN에선 데스크탑환경에서만 사용할 수 있다고 나온다. 하지만 15063빌드 이상이면 UWP에서도 사용할 수 있다.