-
Notifications
You must be signed in to change notification settings - Fork 0
/
readmeter.c
91 lines (73 loc) · 1.67 KB
/
readmeter.c
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
#include <stdio.h>
#include <sys/io.h>
#include <sys/time.h>
/* Adam's uber-hacky electricity usage monitor */
/* Base address of parallel port */
#define BASE 0x378
/* Flashes per kilowatt hour */
#define PER_KWH 1000.0
/* Number of readings to average */
#define AVG 3
int status = BASE + 1;
int laston = 0;
void wait_change() {
int on;
unsigned char v;
do {
v = inb(status);
on = !!(v & 0x20);
usleep(1000);
} while (on == laston);
laston = on;
}
int main(int argc, char **argv) {
int i;
long long lasttime = 0;
double oldvals[AVG];
if (argc < 2) {
fprintf(stderr, "usage: readmeter outputfile tempfile\n");
return 20;
}
if (ioperm(BASE, 3, 1) < 0) {
fprintf(stderr, "ioperm failed\n");
return 20;
}
for (i = 0; i < AVG; i++) oldvals[i] = 0.0;
wait_change();
while (1) {
struct timeval tv;
long long this, diff;
double kw;
int w;
FILE *f;
wait_change();
wait_change();
gettimeofday(&tv, NULL);
this = tv.tv_usec + (1000000 * tv.tv_sec);
diff = this - lasttime;
lasttime = this;
if (diff < 250000 || diff > 10000000) continue;
kw = (3600000000.0 / diff) / PER_KWH;
for (i = 1; i < AVG; i++) oldvals[i - 1] = oldvals[i];
oldvals[AVG - 1] = kw;
kw = 0;
for (i = 0; i < AVG; i++) kw += oldvals[i];
kw /= AVG;
w = kw * 1000;
f = fopen(argv[2], "w");
if (f == NULL) {
fprintf(stderr, "couldn't open %s\n", argv[2]);
return 20;
}
//fprintf(f, "<draw>:<%d>\n", w);
fprintf(f, "%d\n", w);
//printf("%d\n", w);
fclose(f);
// printf("arguments to rename are: %s %s\n", argv[1], argv[2]);
if (rename(argv[2], argv[1]) < 0) {
fprintf(stderr, "couldn't rename file\n");
return 20;
}
}
return 0;
}