kwh-cost/main.c

105 lines
3.3 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define VERSION "1.1.2"
typedef long double price_t;
typedef long double wattage_t;
typedef unsigned long interval_t;
int parse_arguments(const int argc, const char *const *const argv,
price_t *const price, wattage_t *const wattage, interval_t *const interval);
inline interval_t interval_to_seconds(const char *const interval);
inline price_t price_kwh_to_wattsecond(const price_t price);
inline void print_version();
inline void print_usage();
int main(const int argc, const char *const *const argv) {
price_t price;
wattage_t wattage;
interval_t interval = 0;
switch (parse_arguments(argc, argv, &price, &wattage, &interval)) {
case 1: print_usage(); exit(0);
case 2: print_version(); exit(0);
case 99: fputs("Unknown flag provided.\n", stderr); print_usage(); exit(1);
}
printf("%.2Lf\n", (price * wattage) * interval);
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;
for (int i = 1, pos = 0; i < argc; ++i)
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
return 99;
} else if (argc < 4) {
return 1;
} else if (pos == 0) {
*price = price_kwh_to_wattsecond((price_t)atof(argv[i]));
++pos;
} else if (pos == 1) {
*wattage = (wattage_t)atof(argv[2]);
++pos;
} else
*interval += interval_to_seconds(argv[i]);
return 0;
}
inline interval_t interval_to_seconds(const char *const interval) {
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;
}
}
inline price_t price_kwh_to_wattsecond(const price_t price) {
return price / 1000.f / 3600.f;
}
inline void print_version() {
fputs("kwh-cost Ver. " VERSION "\n"
"Copyright (C) 2021-2024 Alexander \"Arav\" Andreev <me@arav.su>. All rights reserved.\n"
"This program is distributed under the terms of MIT+NIGGER licence.\n"
"You can see a license for this program in /usr/share/licenses/kwh-cost/LICENSE.\n", stderr);
}
inline void print_usage() {
fputs("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 power usage in Watts.\n"
" interval time interval in seconds during which\n"
" this much power to be constantly used.\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.\n", stderr);
}