diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e901168 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/.zig-cache +/zig-out diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..94c4e41 --- /dev/null +++ b/build.zig @@ -0,0 +1,29 @@ +const std = @import("std"); + +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + + const exe = b.addExecutable(.{ + .name = "powerbottom", + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + }); + + b.installArtifact(exe); + const run_cmd = b.addRunArtifact(exe); + run_cmd.step.dependOn(b.getInstallStep()); + + // This allows the user to pass arguments to the application in the build + // command itself, like this: `zig build run -- arg1 arg2 etc` + if (b.args) |args| { + run_cmd.addArgs(args); + } + + // This creates a build step. It will be visible in the `zig build --help` menu, + // and can be selected like this: `zig build run` + // This will evaluate the `run` step rather than the default, which is "install". + const run_step = b.step("run", "Run the app"); + run_step.dependOn(&run_cmd.step); +} diff --git a/build.zig.zon b/build.zig.zon new file mode 100644 index 0000000..16ab3b9 --- /dev/null +++ b/build.zig.zon @@ -0,0 +1,72 @@ +.{ + // This is the default name used by packages depending on this one. For + // example, when a user runs `zig fetch --save `, this field is used + // as the key in the `dependencies` table. Although the user can choose a + // different name, most users will stick with this provided value. + // + // It is redundant to include "zig" in this name because it is already + // within the Zig package namespace. + .name = "powerbottom", + + // This is a [Semantic Version](https://semver.org/). + // In a future version of Zig it will be used for package deduplication. + .version = "0.0.0", + + // This field is optional. + // This is currently advisory only; Zig does not yet do anything + // with this value. + //.minimum_zig_version = "0.11.0", + + // This field is optional. + // Each dependency must either provide a `url` and `hash`, or a `path`. + // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. + // Once all dependencies are fetched, `zig build` no longer requires + // internet connectivity. + .dependencies = .{ + // See `zig fetch --save ` for a command-line interface for adding dependencies. + //.example = .{ + // // When updating this field to a new URL, be sure to delete the corresponding + // // `hash`, otherwise you are communicating that you expect to find the old hash at + // // the new URL. + // .url = "https://example.com/foo.tar.gz", + // + // // This is computed from the file contents of the directory of files that is + // // obtained after fetching `url` and applying the inclusion rules given by + // // `paths`. + // // + // // This field is the source of truth; packages do not come from a `url`; they + // // come from a `hash`. `url` is just one of many possible mirrors for how to + // // obtain a package matching this `hash`. + // // + // // Uses the [multihash](https://multiformats.io/multihash/) format. + // .hash = "...", + // + // // When this is provided, the package is found in a directory relative to the + // // build root. In this case the package's hash is irrelevant and therefore not + // // computed. This field and `url` are mutually exclusive. + // .path = "foo", + + // // When this is set to `true`, a package is declared to be lazily + // // fetched. This makes the dependency only get fetched if it is + // // actually used. + // .lazy = false, + //}, + }, + + // Specifies the set of files and directories that are included in this package. + // Only files and directories listed here are included in the `hash` that + // is computed for this package. Only files listed here will remain on disk + // when using the zig package manager. As a rule of thumb, one should list + // files required for compilation plus any license(s). + // Paths are relative to the build root. Use the empty string (`""`) to refer to + // the build root itself. + // A directory listed here means that all files within, recursively, are included. + .paths = .{ + "build.zig", + "build.zig.zon", + "src", + // For example... + //"LICENSE", + //"README.md", + }, +} diff --git a/src/batteryinfo.zig b/src/batteryinfo.zig new file mode 100644 index 0000000..b2315b5 --- /dev/null +++ b/src/batteryinfo.zig @@ -0,0 +1,71 @@ +const std = @import("std"); + +const _maxRead = 4096; + +pub const BatteryInfo = struct { + Manufacturer: []u8, + Model: []u8, + Technology: []u8, + CellSeriesCount: u32 = 0, + Capacity: u32 = 0, + CapacityDesign: u32 = 0, + Vnow: f32 = 0, + Vmin: f32 = 0, + ChargeNow: u32 = 0, + ChargeFull: u32 = 0, + ChargeFullPercentageDesign: u32 = 0, + ChargeFullDesign: u32 = 0, + _allocator: std.mem.Allocator, + + pub fn deinit(self: *const BatteryInfo) void { + self._allocator.free(self.Manufacturer); + self._allocator.free(self.Model); + self._allocator.free(self.Technology); + } +}; + +fn _readInfo(allocator: std.mem.Allocator, dir: std.fs.Dir, path: []const u8) ![]u8 { + const start = try dir.readFileAlloc(allocator, path, _maxRead); + defer allocator.free(start); + const trimmed = std.mem.trim(u8, start, "\r\n\t "); + return allocator.dupe(u8, trimmed); +} + +fn _readInfoU32(allocator: std.mem.Allocator, dir: std.fs.Dir, path: []const u8) !u32 { + const info = try _readInfo(allocator, dir, path); + defer allocator.free(info); + return std.fmt.parseInt(u32, info, 10); +} + +pub fn GetBatteryInfoAlloc(allocator: std.mem.Allocator, dir: std.fs.Dir) !BatteryInfo { + const manufacturer = try _readInfo(allocator, dir, "manufacturer"); + const model = try _readInfo(allocator, dir, "model_name"); + const technology = try _readInfo(allocator, dir, "technology"); + + var info = BatteryInfo{ + .Manufacturer = manufacturer, + .Model = model, + .Technology = technology, + ._allocator = allocator, + }; + + info.Capacity = try _readInfoU32(allocator, dir, "capacity"); + info.ChargeNow = try _readInfoU32(allocator, dir, "energy_now") / 1000; + info.ChargeFull = try _readInfoU32(allocator, dir, "energy_full") / 1000; + info.ChargeFullDesign = try _readInfoU32(allocator, dir, "energy_full_design") / 1000; + + if(info.ChargeFullDesign != 0) { + info.ChargeFullPercentageDesign = 100 * info.ChargeFull / info.ChargeFullDesign; + info.CapacityDesign = 100 * info.ChargeNow / info.ChargeFullDesign; + } + + const Vnow = try _readInfoU32(allocator, dir, "voltage_now") / 1000; + const Vmin = try _readInfoU32(allocator, dir, "voltage_min_design") / 1000; + + info.Vnow = @as(f32, @floatFromInt(Vnow)) / 1000; + info.Vmin = @as(f32, @floatFromInt(Vmin)) / 1000; + + info.CellSeriesCount = @intFromFloat(@ceil(info.Vmin / 3.7)); + + return info; +} diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000..b333b61 --- /dev/null +++ b/src/main.zig @@ -0,0 +1,36 @@ +const std = @import("std"); +const batinfo = @import("batteryinfo.zig"); + +pub fn main() !void { + var buffer: [65535]u8 = undefined; + var fba = std.heap.FixedBufferAllocator.init(&buffer); + const allocator = fba.allocator(); + + const powerSupply = try std.fs.cwd().openDir("/sys/class/power_supply", .{}); + var i:u32 = 0; + while(true) : (i += 1) { + const name = try std.fmt.allocPrint(allocator, "BAT{}", .{i}); + defer allocator.free(name); + const batDir = powerSupply.openDir(name, .{}) catch |err| switch(err) { + error.FileNotFound => {return;}, + else => {return err;}, + }; + const battery = try batinfo.GetBatteryInfoAlloc(allocator, batDir); + defer battery.deinit(); + try printBattery(battery); + } +} + +fn printBattery(battery: batinfo.BatteryInfo) !void { + const stdout = std.io.getStdOut().writer(); + try stdout.print("Battery {s} {s}\n", .{battery.Manufacturer, battery.Model}); + try stdout.print("\tTechnology: {s}\n", .{battery.Technology}); + try stdout.print("\tCell series count: {}s\n\n", .{battery.CellSeriesCount}); + try stdout.print("\tCapacity: {}%\n", .{battery.Capacity}); + try stdout.print("\tCapacity (design): {}%\n", .{battery.CapacityDesign}); + try stdout.print("\tVmin: {d:.2}V Per cell: {d:.2}V\n", .{battery.Vmin, battery.Vmin/@as(f32, @floatFromInt(battery.CellSeriesCount))}); + try stdout.print("\tVnow: {d:.2}V Per cell: {d:.2}V\n", .{battery.Vnow, battery.Vnow/@as(f32, @floatFromInt(battery.CellSeriesCount))}); + try stdout.print("\tCharge now: {}mAh\n", .{battery.ChargeNow}); + try stdout.print("\tCharge full: {}mAh\n", .{battery.ChargeFull}); + try stdout.print("\tCharge full (design): {}mAh\n\n", .{battery.ChargeFullDesign}); +}