kwh-cost/src/main.c

96 lines
2.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"
int main(int argc, char **argv) {
arguments_t * args = parse_arguments(argc, argv);
printf("%.2Lf\n", (args->price * args->wattage) * args->interval);
free(args);
return 0;
}
arguments_t * parse_arguments(int argc, char **argv) {
if (argc == 1) {
print_usage();
exit(0);
}
arguments_t *args = (arguments_t *)calloc(1, sizeof(arguments_t));
int pos_args_pos = 0;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
if (argv[i][1] == 'h' || argv[i][2] == 'h') {
print_usage();
exit(0);
} else if (argv[i][1] == 'v' || argv[i][2] == 'v') {
print_version();
exit(0);
}
} else if (pos_args_pos == 0) {
args->price = to_wattpersecond((price_t)atof(argv[i]));
pos_args_pos++;
} else if (pos_args_pos == 1) {
args->wattage = atof(argv[i]);
pos_args_pos++;
} else if (pos_args_pos > 1) {
args->interval += to_seconds(argv[i]);
pos_args_pos++;
}
}
if (pos_args_pos < 3) {
print_usage();
exit(1);
}
return args;
}
interval_t to_seconds(char *interval) {
interval_t intrvl = (interval_t)atol(interval);
char unit = interval[strlen(interval) - 1];
if (!(unit >= '0' && unit <= '9'))
switch (unit) {
case 'm':
case 'M':
return intrvl * 60;
case 'h':
case 'H':
return intrvl * 60 * 60;
case 'd':
case 'D':
return intrvl * 60 * 60 * 24;
}
return intrvl;
}
inline price_t to_wattpersecond(price_t price) {
return price / 1000.f / 3600.f;
}
void print_version() {
printf("kwh-calc Ver. " VERSION "\n"
"Copyright (C) 2021 Alexander \"Arav\" Andreev <me@arav.top>. All rights reserved.\n"
"License for this program is stored in /usr/share/licenses/kwh-calc/LICENSE.");
}
void print_usage() {
printf("Usage: kwh-calc [options] price wattage interval [interval ...]\n"
"Options:\n"
" --help, -h Display this usage information.\n"
" --version, -v Display program version.\n"
"Arguments:\n"
" price Price per kWh.\n"
" wattage Specify power usage in Watts.\n"
" interval Time interval in seconds total cost to be calculated for.\n"
" You may specify other time units such as:\n"
" m'imute, h'our, d'ay. Example: 5d 3h.\n"
" All given intervals will be summed up.\n");
}