46 lines
1.8 KiB
Zig
46 lines
1.8 KiB
Zig
|
const std = @import("std");
|
||
|
const Module = @import("../module.zig");
|
||
|
const Self = @This();
|
||
|
|
||
|
module: Module,
|
||
|
|
||
|
pub fn init(allocator: std.mem.Allocator) Self {
|
||
|
return .{
|
||
|
.module = .{
|
||
|
.allocator = allocator,
|
||
|
.getJsonFn = getJson,
|
||
|
},
|
||
|
};
|
||
|
}
|
||
|
|
||
|
pub fn getJson(module: *const Module) !Module.JSON {
|
||
|
const self = @fieldParentPtr(Self, "module", module);
|
||
|
|
||
|
var energy_full_file = try std.fs.openFileAbsolute("/sys/class/power_supply/BAT0/energy_full", .{});
|
||
|
defer energy_full_file.close();
|
||
|
var energy_now_file = try std.fs.openFileAbsolute("/sys/class/power_supply/BAT0/energy_now", .{});
|
||
|
defer energy_now_file.close();
|
||
|
var status_file = try std.fs.openFileAbsolute("/sys/class/power_supply/BAT0/status", .{});
|
||
|
defer status_file.close();
|
||
|
|
||
|
const energy_full_string = try energy_full_file.reader().readAllAlloc(self.module.allocator, 32);
|
||
|
const energy_now_string = try energy_now_file.reader().readAllAlloc(self.module.allocator, 32);
|
||
|
const status_string = try status_file.reader().readAllAlloc(self.module.allocator, 32);
|
||
|
const energy_full = try std.fmt.parseInt(u32, energy_full_string[0 .. energy_full_string.len - 1], 10);
|
||
|
const energy_now = try std.fmt.parseInt(u32, energy_now_string[0 .. energy_now_string.len - 1], 10);
|
||
|
|
||
|
const status = if (std.mem.eql(u8, status_string[0 .. status_string.len - 1], "Full"))
|
||
|
"="
|
||
|
else if (std.mem.eql(u8, status_string[0 .. status_string.len - 1], "Discharging"))
|
||
|
"v"
|
||
|
else if (std.mem.eql(u8, status_string[0 .. status_string.len - 1], "Charging"))
|
||
|
"^"
|
||
|
else
|
||
|
"?";
|
||
|
const percent_left = @as(f32, @floatFromInt(energy_now)) / @as(f32, @floatFromInt(energy_full)) * 100;
|
||
|
|
||
|
return .{
|
||
|
.full_text = try std.fmt.allocPrint(self.module.allocator, "{s} {d:.2}%", .{ status, percent_left }),
|
||
|
};
|
||
|
}
|