summaryrefslogtreecommitdiff
path: root/main.c
blob: b57fe33a3452a728bf024c7afdf1453c6687db98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef DEBUG
#define DEBUG_LOG(e) printf("DEBUG: %s\n", e);
#else
#define DEBUG_LOG(e)
#endif

struct output_status {
    char value[4];
    float active_power;
    float current;
    float voltage;
    float power_factor;
    float energy_sum;
};

int parse_output(int id, struct output_status *ret);
void print_output(struct output_status *status);

int parse_output(int id, struct output_status *ret)
{
    int done;
    FILE *fp;
    char filename[13] = {0};

    if (id > 9 || id < 1) {
        DEBUG_LOG("Output identifier greater out of range");
        return 1;
    }

    snprintf(filename, 12, "/dev/power%d", id);

    fp = fopen(filename, "r");
    if (fp == NULL) {
        DEBUG_LOG("Error opening output device");
        return 1;
    }

    done = fscanf(fp, "%s %f\n %f\n %f\n %f\n %f",
                      ret->value, &ret->active_power,
                      &ret->current, &ret->voltage,
                      &ret->power_factor, &ret->energy_sum);
    fclose(fp);

    if (done != 6) {
        DEBUG_LOG("parse_output did not receive enough fields");
        return 1;
    }

    return 0;
}

void print_output(struct output_status *status)
{
    printf("Value: %s\n", status->value);
    printf("Active Power: %f\n", status->active_power);
    printf("Current: %f\n", status->current);
    printf("Voltage: %f\n", status->voltage);
    printf("Power Factor: %f\n", status->power_factor);
    printf("Energy Sum: %f\n", status->energy_sum);
}

int main(int argc, char **argv)
{
    int ret;
    int output;
    struct output_status status;

    memset(&status, 0, sizeof(status));

    if (argc != 2) {
        printf("Pass output number\n");
        return 1;
    }

    output = atoi(argv[1]);
    if (output > 9 || output <= 0) {
        printf("Output out of range\n");
        return 1;
    }

    if ((ret = parse_output(output, &status)) != 0) {
        printf("Failed to parse output\n");
        return 1;
    }

    print_output(&status);

    return 0;
}