diff --git a/src/battery.c b/src/battery.c index f4ec1d6..b965708 100644 --- a/src/battery.c +++ b/src/battery.c @@ -5,19 +5,54 @@ #include #include +#define RAZER_REPORT_ID_BATTERY 0x03 +#define RAZER_BATTERY_REPORT_SIZE 64 +#define RAZER_BATTERY_LEVEL_INDEX 3 +#define RAZER_CHARGING_STATUS_INDEX 4 + +/***************************************************************************** + * + * This code doesn't work. + * + *************************************************************************** */ + int get_battery_level(const char *device_path, bool *is_charging) { - HANDLE hDevice = - CreateFile(device_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, 0, NULL); + HANDLE hDevice = CreateFile(device_path, GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, + OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (hDevice == INVALID_HANDLE_VALUE) { fprintf_s(stderr, "Failed to open device.\n"); return -1; } - int batteryLevel; + unsigned char report[RAZER_BATTERY_REPORT_SIZE] = {0}; + DWORD bytesReturned; - // TODO + // Prepare the report to request battery information + report[0] = RAZER_REPORT_ID_BATTERY; + + // Send the report + if (!HidD_SetFeature(hDevice, report, RAZER_BATTERY_REPORT_SIZE)) { + fprintf_s(stderr, "Failed to send report to device.\n"); + + CloseHandle(hDevice); + return -1; + } + + // Read the response + if (!HidD_GetFeature(hDevice, report, RAZER_BATTERY_REPORT_SIZE)) { + fprintf_s(stderr, "Failed to read report from device.\n"); + + CloseHandle(hDevice); + return -1; + } + + // Extract battery level + int batteryLevel = report[RAZER_BATTERY_LEVEL_INDEX]; + + // Extract charging status + *is_charging = (report[RAZER_CHARGING_STATUS_INDEX] != 0); CloseHandle(hDevice); return batteryLevel;