kwh-cost/src/main.c

91 lines
2.7 KiB
C
Raw Normal View History

2021-12-23 23:59:00 +04:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"
int main(const int argc, const char * const * const argv) {
price_t price;
wattage_t wattage;
interval_t interval = 0;
2021-12-23 23:59:00 +04:00
int res = parse_arguments(argc, argv, &price, &wattage, &interval);
if (res != 0) {
if (res == 1)
print_usage();
else if (res == 2)
print_version();
exit(0);
}
printf("%.2Lf\n", (price * wattage) * interval);
2021-12-23 23:59:00 +04:00
return 0;
}
int parse_arguments(const int argc, const char * const * const argv,
price_t * const price, wattage_t * const wattage, interval_t * const interval) {
if (argc < 2) return 1;
2021-12-23 23:59:00 +04:00
for (int i = 1, pos = 0; i < argc; ++i)
2021-12-23 23:59:00 +04:00
if (argv[i][0] == '-') {
if (argv[i][1] == 'h' || argv[i][2] == 'h')
return 1;
else if (argv[i][1] == 'v' || argv[i][2] == 'v')
return 2;
} else if (argc < 4) {
return 1;
} else if (pos == 0) {
*price = to_wattspersecond((price_t)atof(argv[i]));
++pos;
} else if (pos == 1) {
*wattage = (wattage_t)atof(argv[2]);
++pos;
} else
*interval += (interval_t)interval_to_seconds(argv[i]);
2021-12-23 23:59:00 +04:00
return 0;
2021-12-23 23:59:00 +04:00
}
inline interval_t interval_to_seconds(const char * const interval) {
2021-12-23 23:59:00 +04:00
interval_t intrvl = (interval_t)atol(interval);
switch (interval[strlen(interval) - 1]) {
case 'm':
case 'M':
return intrvl * 60;
case 'h':
case 'H':
return intrvl * 60 * 60;
case 'd':
case 'D':
return intrvl * 60 * 60 * 24;
default:
return intrvl;
}
2021-12-23 23:59:00 +04:00
}
inline price_t to_wattspersecond(const price_t price) {
2021-12-23 23:59:00 +04:00
return price / 1000.f / 3600.f;
}
inline void print_version() {
puts("kwh-cost Ver. " VERSION "\n"
"Copyright (C) 2021 Alexander \"Arav\" Andreev <me@arav.top>. All rights reserved.\n"
"You can see a license for this program in /usr/share/licenses/kwh-cost/LICENSE.");
2021-12-23 23:59:00 +04:00
}
inline void print_usage() {
puts("Usage: kwh-cost [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'inute, h'our, d'ay. Example: 5d 3h.\n"
" All given intervals will be summed up.");
}