]> git.scottworley.com Git - batteryviewer/blobdiff - batteryviewer.c
Put filenames in State
[batteryviewer] / batteryviewer.c
index a525a729b56ca9cdee6002a67b5f8142fd6caae5..540db8e7c21c024ab0dabde05d6e5236eaa16c20 100644 (file)
@@ -1,11 +1,52 @@
 #include "chart.h"
+#include <ctype.h>
+#include <errno.h>
 #include <gtk/gtk.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
 
 struct State {
+  char *voltage_filename;
+  char *current_filename;
   BVChart *voltage;
   BVChart *current;
 };
 
+static float fatof(const char *filename) {
+  FILE *f = fopen(filename, "r");
+  if (f == NULL) {
+    return NAN;
+  }
+
+  const int bufsize = 1024;
+  char buf[bufsize];
+  const int read = fread(buf, sizeof(char), bufsize, f);
+  if (read == 0 || read == bufsize || ferror(f)) {
+    fclose(f);
+    return NAN;
+  }
+  fclose(f);
+
+  char *end;
+  errno = 0;
+  float val = strtof(buf, &end);
+  int parsed = end - buf;
+  gboolean parsed_all = parsed == read;
+  gboolean parsed_all_but_space = parsed == read - 1 && isspace(*end);
+  gboolean parse_ok = parsed_all || parsed_all_but_space;
+  if (errno != 0 || parsed == 0 || !parse_ok) {
+    return NAN;
+  }
+  return val;
+}
+
+static gboolean collect_data(struct State *state) {
+  fprintf(stderr, "Voltage: %f, current: %f\n", fatof(state->voltage_filename),
+          fatof(state->current_filename));
+  return TRUE;
+}
+
 static void activate(GtkApplication *app, gpointer user_data) {
 
   GtkWidget *window = gtk_application_window_new(app);
@@ -33,10 +74,15 @@ static void activate(GtkApplication *app, gpointer user_data) {
                    padding);
 
   gtk_widget_show_all(window);
+
+  g_timeout_add_seconds(1, (GSourceFunc)collect_data, user_data);
 }
 
 int main(int argc, char **argv) {
-  struct State state;
+  struct State state = {
+      .voltage_filename = "/sys/class/power_supply/BAT0/voltage_now",
+      .current_filename = "/sys/class/power_supply/BAT0/current_now",
+  };
 
   GtkApplication *app = gtk_application_new("com.scottworley.batteryviewer",
                                             G_APPLICATION_DEFAULT_FLAGS);