add memory module

This commit is contained in:
Jeeves 2024-03-15 20:15:29 -06:00
parent 576bafc350
commit 25cd2dcfe8
2 changed files with 42 additions and 0 deletions

View file

@ -8,6 +8,7 @@ const calendar = @import("modules/calendar.zig");
const display = @import("modules/display.zig");
const uptime = @import("modules/uptime.zig");
const volume = @import("modules/volume.zig");
const memory = @import("modules/memory.zig");
const Module = @import("module.zig");
pub fn main() !void {
@ -23,6 +24,7 @@ pub fn main() !void {
var modules = [_]Module{
uptime.init(arena.allocator()).module,
memory.init(arena.allocator()).module,
volume.init(arena.allocator()).module,
display.init(arena.allocator()).module,
battery.init(arena.allocator()).module,

40
src/modules/memory.zig Normal file
View file

@ -0,0 +1,40 @@
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 meminfo_file = try std.fs.openFileAbsolute("/proc/meminfo", .{});
defer meminfo_file.close();
const meminfo_string = try meminfo_file.reader().readAllAlloc(self.module.allocator, 4096);
const mem_total_idx = std.mem.indexOf(u8, meminfo_string, "MemTotal:");
const mem_available_idx = std.mem.indexOf(u8, meminfo_string, "MemAvailable:");
const mem_total_newline = std.mem.indexOfScalarPos(u8, meminfo_string, mem_total_idx.?, '\n');
const mem_available_newline = std.mem.indexOfScalarPos(u8, meminfo_string, mem_available_idx.?, '\n');
var mem_total_split = std.mem.splitBackwardsScalar(u8, meminfo_string[mem_total_idx.?..mem_total_newline.?], ' ');
var mem_available_split = std.mem.splitBackwardsScalar(u8, meminfo_string[mem_available_idx.?..mem_available_newline.?], ' ');
_ = mem_total_split.next();
_ = mem_available_split.next();
const mem_total = try std.fmt.parseInt(usize, mem_total_split.next().?, 10);
const mem_available = try std.fmt.parseInt(usize, mem_available_split.next().?, 10);
const mem = @as(f32, @floatFromInt(mem_total)) - @as(f32, @floatFromInt(mem_available));
return .{
.full_text = try std.fmt.allocPrint(self.module.allocator, "{d:.3} GB", .{mem / 1000 / 1000}),
};
}