Home | History | Annotate | Line # | Download | only in envstat
envstat.c revision 1.70
      1 /* $NetBSD: envstat.c,v 1.70 2008/08/22 11:27:50 pgoyette Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2007, 2008 Juan Romero Pardines.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 #include <sys/cdefs.h>
     29 #ifndef lint
     30 __RCSID("$NetBSD: envstat.c,v 1.70 2008/08/22 11:27:50 pgoyette Exp $");
     31 #endif /* not lint */
     32 
     33 #include <stdio.h>
     34 #include <stdlib.h>
     35 #include <stdbool.h>
     36 #include <string.h>
     37 #include <unistd.h>
     38 #include <fcntl.h>
     39 #include <err.h>
     40 #include <errno.h>
     41 #include <syslog.h>
     42 #include <sys/envsys.h>
     43 #include <sys/types.h>
     44 #include <sys/queue.h>
     45 #include <prop/proplib.h>
     46 
     47 #include "envstat.h"
     48 
     49 #define _PATH_DEV_SYSMON	"/dev/sysmon"
     50 
     51 #define ENVSYS_DFLAG	0x00000001	/* list registered devices */
     52 #define ENVSYS_FFLAG	0x00000002	/* show temp in farenheit */
     53 #define ENVSYS_LFLAG	0x00000004	/* list sensors */
     54 #define ENVSYS_XFLAG	0x00000008	/* externalize dictionary */
     55 #define ENVSYS_IFLAG 	0x00000010	/* skip invalid sensors */
     56 #define ENVSYS_SFLAG	0x00000020	/* remove all properties set */
     57 #define ENVSYS_TFLAG	0x00000040	/* make statistics */
     58 #define ENVSYS_WFLAG	0x00000080	/* print warn{min,max} values */
     59 
     60 /* Sensors */
     61 typedef struct envsys_sensor {
     62 	SIMPLEQ_ENTRY(envsys_sensor) entries;
     63 	int32_t	cur_value;
     64 	int32_t	max_value;
     65 	int32_t	min_value;
     66 	int32_t	avg_value;
     67 	int32_t critcap_value;
     68 	int32_t	critmin_value;
     69 	int32_t	critmax_value;
     70 	int32_t warncap_value;
     71 	int32_t	warnmin_value;
     72 	int32_t	warnmax_value;
     73 	char	desc[ENVSYS_DESCLEN];
     74 	char	type[ENVSYS_DESCLEN];
     75 	char	drvstate[ENVSYS_DESCLEN];
     76 	char	battcap[ENVSYS_DESCLEN];
     77 	char 	dvname[ENVSYS_DESCLEN];
     78 	bool	invalid;
     79 	bool	visible;
     80 	bool	percentage;
     81 } *sensor_t;
     82 
     83 /* Sensor statistics */
     84 typedef struct envsys_sensor_stats {
     85 	SIMPLEQ_ENTRY(envsys_sensor_stats) entries;
     86 	int32_t	max;
     87 	int32_t	min;
     88 	int32_t avg;
     89 	char	desc[ENVSYS_DESCLEN];
     90 } *sensor_stats_t;
     91 
     92 /* Device properties */
     93 typedef struct envsys_dvprops {
     94 	uint64_t	refresh_timo;
     95 	/* more members could be added in the future */
     96 } *dvprops_t;
     97 
     98 /* A simple queue to manage all sensors */
     99 static SIMPLEQ_HEAD(, envsys_sensor) sensors_list =
    100     SIMPLEQ_HEAD_INITIALIZER(sensors_list);
    101 
    102 /* A simple queue to manage statistics for all sensors */
    103 static SIMPLEQ_HEAD(, envsys_sensor_stats) sensor_stats_list =
    104     SIMPLEQ_HEAD_INITIALIZER(sensor_stats_list);
    105 
    106 static unsigned int 	interval, flags, width;
    107 static char 		*mydevname, *sensors;
    108 static bool 		statistics;
    109 static u_int		header_passes;
    110 
    111 static int 		parse_dictionary(int);
    112 static int 		send_dictionary(FILE *, int);
    113 static int 		find_sensors(prop_array_t, const char *, dvprops_t);
    114 static void 		print_sensors(void);
    115 static int 		check_sensors(char *);
    116 static int 		usage(void);
    117 
    118 
    119 int main(int argc, char **argv)
    120 {
    121 	prop_dictionary_t dict;
    122 	int c, fd, rval = 0;
    123 	char *endptr, *configfile = NULL;
    124 	FILE *cf;
    125 
    126 	setprogname(argv[0]);
    127 
    128 	while ((c = getopt(argc, argv, "c:Dd:fIi:lrSs:Tw:Wx")) != -1) {
    129 		switch (c) {
    130 		case 'c':	/* configuration file */
    131 			configfile = strdup(optarg);
    132 			if (configfile == NULL)
    133 				err(EXIT_FAILURE, "strdup");
    134 			break;
    135 		case 'D':	/* list registered devices */
    136 			flags |= ENVSYS_DFLAG;
    137 			break;
    138 		case 'd':	/* show sensors of a specific device */
    139 			mydevname = strdup(optarg);
    140 			if (mydevname == NULL)
    141 				err(EXIT_FAILURE, "strdup");
    142 			break;
    143 		case 'f':	/* display temperature in Farenheit */
    144 			flags |= ENVSYS_FFLAG;
    145 			break;
    146 		case 'I':	/* Skips invalid sensors */
    147 			flags |= ENVSYS_IFLAG;
    148 			break;
    149 		case 'i':	/* wait time between intervals */
    150 			interval = (unsigned int)strtoul(optarg, &endptr, 10);
    151 			if (*endptr != '\0')
    152 				errx(EXIT_FAILURE, "bad interval '%s'", optarg);
    153 			break;
    154 		case 'l':	/* list sensors */
    155 			flags |= ENVSYS_LFLAG;
    156 			break;
    157 		case 'r':
    158 			/*
    159 			 * This flag is noop.. it's only here for
    160 			 * compatibility with the old implementation.
    161 			 */
    162 			break;
    163 		case 'S':
    164 			flags |= ENVSYS_SFLAG;
    165 			break;
    166 		case 's':	/* only show specified sensors */
    167 			sensors = strdup(optarg);
    168 			if (sensors == NULL)
    169 				err(EXIT_FAILURE, "strdup");
    170 			break;
    171 		case 'T':	/* make statistics */
    172 			flags |= ENVSYS_TFLAG;
    173 			break;
    174 		case 'W':	/* print warn{max,min} vs crit{max,min} */
    175 			flags |= ENVSYS_WFLAG;
    176 			break;
    177 		case 'w':	/* width value for the lines */
    178 			width = (unsigned int)strtoul(optarg, &endptr, 10);
    179 			if (*endptr != '\0')
    180 				errx(EXIT_FAILURE, "bad width '%s'", optarg);
    181 			break;
    182 		case 'x':	/* print the dictionary in raw format */
    183 			flags |= ENVSYS_XFLAG;
    184 			break;
    185 		case '?':
    186 		default:
    187 			usage();
    188 			/* NOTREACHED */
    189 		}
    190 	}
    191 
    192 	argc -= optind;
    193 	argv += optind;
    194 
    195 	if (argc > 0)
    196 		usage();
    197 
    198 	/* Check if we want to make statistics */
    199 	if (flags & ENVSYS_TFLAG) {
    200 		if (!interval)
    201 			errx(EXIT_FAILURE,
    202 		    	    "-T cannot be used without an interval (-i)");
    203 		if (flags & ENVSYS_WFLAG)
    204 			errx(EXIT_FAILURE,
    205 			    "-T cannot be used with -W");
    206 		else
    207 			statistics = true;
    208 	}
    209 
    210 	if (mydevname && sensors)
    211 		errx(EXIT_FAILURE, "-d flag cannot be used with -s");
    212 
    213 	/* Open the device in ro mode */
    214 	if ((fd = open(_PATH_DEV_SYSMON, O_RDONLY)) == -1)
    215 		err(EXIT_FAILURE, "%s", _PATH_DEV_SYSMON);
    216 
    217 	/* Print dictionary in raw mode */
    218 	if (flags & ENVSYS_XFLAG) {
    219 		rval = prop_dictionary_recv_ioctl(fd,
    220 						  ENVSYS_GETDICTIONARY,
    221 						  &dict);
    222 		if (rval)
    223 			errx(EXIT_FAILURE, "%s", strerror(rval));
    224 
    225 		config_dict_dump(dict);
    226 
    227 	/* Remove all properties set in dictionary */
    228 	} else if (flags & ENVSYS_SFLAG) {
    229 		/* Close the ro descriptor */
    230 		(void)close(fd);
    231 
    232 		/* open the fd in rw mode */
    233 		if ((fd = open(_PATH_DEV_SYSMON, O_RDWR)) == -1)
    234 			err(EXIT_FAILURE, "%s", _PATH_DEV_SYSMON);
    235 
    236 		dict = prop_dictionary_create();
    237 		if (!dict)
    238 			err(EXIT_FAILURE, "prop_dictionary_create");
    239 
    240 		rval = prop_dictionary_set_bool(dict,
    241 						"envsys-remove-props",
    242 					        true);
    243 		if (!rval)
    244 			err(EXIT_FAILURE, "prop_dict_set_bool");
    245 
    246 		/* send the dictionary to the kernel now */
    247 		rval = prop_dictionary_send_ioctl(dict, fd, ENVSYS_REMOVEPROPS);
    248 		if (rval)
    249 			warnx("%s", strerror(rval));
    250 
    251 	/* Set properties in dictionary */
    252 	} else if (configfile) {
    253 		/*
    254 		 * Parse the configuration file.
    255 		 */
    256 		if ((cf = fopen(configfile, "r")) == NULL) {
    257 			syslog(LOG_ERR, "fopen failed: %s", strerror(errno));
    258 			errx(EXIT_FAILURE, "%s", strerror(errno));
    259 		}
    260 
    261 		rval = send_dictionary(cf, fd);
    262 		(void)fclose(cf);
    263 
    264 	/* Show sensors with interval */
    265 	} else if (interval) {
    266 		for (;;) {
    267 			rval = parse_dictionary(fd);
    268 			if (rval)
    269 				break;
    270 
    271 			(void)fflush(stdout);
    272 			(void)sleep(interval);
    273 		}
    274 	/* Show sensors without interval */
    275 	} else {
    276 		rval = parse_dictionary(fd);
    277 	}
    278 
    279 	if (sensors)
    280 		free(sensors);
    281 	if (mydevname)
    282 		free(mydevname);
    283 	(void)close(fd);
    284 
    285 	return rval ? EXIT_FAILURE : EXIT_SUCCESS;
    286 }
    287 
    288 static int
    289 send_dictionary(FILE *cf, int fd)
    290 {
    291 	prop_dictionary_t kdict, udict;
    292 	int error = 0;
    293 
    294 	/* Retrieve dictionary from kernel */
    295 	error = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &kdict);
    296       	if (error)
    297 		return error;
    298 
    299 	config_parse(cf, kdict);
    300 
    301 	/*
    302 	 * Dictionary built by the parser from the configuration file.
    303 	 */
    304 	udict = config_dict_parsed();
    305 
    306 	/*
    307 	 * Close the read only descriptor and open a new one read write.
    308 	 */
    309 	(void)close(fd);
    310 	if ((fd = open(_PATH_DEV_SYSMON, O_RDWR)) == -1) {
    311 		error = errno;
    312 		warn("%s", _PATH_DEV_SYSMON);
    313 		return error;
    314 	}
    315 
    316 	/*
    317 	 * Send our sensor properties dictionary to the kernel then.
    318 	 */
    319 	error = prop_dictionary_send_ioctl(udict, fd, ENVSYS_SETDICTIONARY);
    320 	if (error)
    321 		warnx("%s", strerror(error));
    322 
    323 	prop_object_release(udict);
    324 	return error;
    325 }
    326 
    327 static sensor_stats_t
    328 find_stats_sensor(const char *desc)
    329 {
    330 	sensor_stats_t stats;
    331 
    332 	/*
    333 	 * If we matched a sensor by its description return it, otherwise
    334 	 * allocate a new one.
    335 	 */
    336 	SIMPLEQ_FOREACH(stats, &sensor_stats_list, entries)
    337 		if (strcmp(stats->desc, desc) == 0)
    338 			return stats;
    339 
    340 	stats = calloc(1, sizeof(*stats));
    341 	if (stats == NULL)
    342 		return NULL;
    343 
    344 	(void)strlcpy(stats->desc, desc, sizeof(stats->desc));
    345 	SIMPLEQ_INSERT_TAIL(&sensor_stats_list, stats, entries);
    346 
    347 	return stats;
    348 }
    349 
    350 static int
    351 parse_dictionary(int fd)
    352 {
    353 	sensor_t sensor = NULL;
    354 	dvprops_t edp = NULL;
    355 	prop_array_t array;
    356 	prop_dictionary_t dict;
    357 	prop_object_iterator_t iter;
    358 	prop_object_t obj;
    359 	const char *dnp = NULL;
    360 	int rval = 0;
    361 
    362 	/* receive dictionary from kernel */
    363 	rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
    364 	if (rval)
    365 		return rval;
    366 
    367 	/* No drivers registered? */
    368 	if (prop_dictionary_count(dict) == 0) {
    369 		warnx("no drivers registered");
    370 		goto out;
    371 	}
    372 
    373 	if (mydevname) {
    374 		/* -d flag specified, print sensors only for this device */
    375 		obj = prop_dictionary_get(dict, mydevname);
    376 		if (prop_object_type(obj) != PROP_TYPE_ARRAY) {
    377 			warnx("unknown device `%s'", mydevname);
    378 			rval = EINVAL;
    379 			goto out;
    380 		}
    381 
    382 		rval = find_sensors(obj, mydevname, NULL);
    383 		if (rval)
    384 			goto out;
    385 
    386 	} else {
    387 		/* print sensors for all devices registered */
    388 		iter = prop_dictionary_iterator(dict);
    389 		if (iter == NULL) {
    390 			rval = EINVAL;
    391 			goto out;
    392 		}
    393 
    394 		/* iterate over the dictionary returned by the kernel */
    395 		while ((obj = prop_object_iterator_next(iter)) != NULL) {
    396 			array = prop_dictionary_get_keysym(dict, obj);
    397 			if (prop_object_type(array) != PROP_TYPE_ARRAY) {
    398 				warnx("no sensors found");
    399 				rval = EINVAL;
    400 				goto out;
    401 			}
    402 
    403 			edp = calloc(1, sizeof(*edp));
    404 			if (!edp) {
    405 				rval = ENOMEM;
    406 				goto out;
    407 			}
    408 
    409 			dnp = prop_dictionary_keysym_cstring_nocopy(obj);
    410 			rval = find_sensors(array, dnp, edp);
    411 			if (rval)
    412 				goto out;
    413 
    414 			if (((flags & ENVSYS_LFLAG) == 0) &&
    415 			    (flags & ENVSYS_DFLAG)) {
    416 				(void)printf("%s (checking events every ",
    417 				    dnp);
    418 				if (edp->refresh_timo == 1)
    419 					(void)printf("second)\n");
    420 				else
    421 					(void)printf("%d seconds)\n",
    422 					    (int)edp->refresh_timo);
    423 			}
    424 
    425 			free(edp);
    426 			edp = NULL;
    427 		}
    428 		prop_object_iterator_release(iter);
    429 	}
    430 
    431 	/* print sensors now */
    432 	if (sensors) {
    433 		char *str = strdup(sensors);
    434 		if (!str) {
    435 			rval = ENOMEM;
    436 			goto out;
    437 		}
    438 		rval = check_sensors(str);
    439 		if (rval) {
    440 			free(str);
    441 			goto out;
    442 		}
    443 		free(str);
    444 	}
    445 	if ((flags & ENVSYS_LFLAG) == 0 && (flags & ENVSYS_DFLAG) == 0)
    446 		print_sensors();
    447 	if (interval)
    448 		(void)printf("\n");
    449 
    450 out:
    451 	while ((sensor = SIMPLEQ_FIRST(&sensors_list))) {
    452 		SIMPLEQ_REMOVE_HEAD(&sensors_list, entries);
    453 		free(sensor);
    454 	}
    455 	if (edp)
    456 		free(edp);
    457 	prop_object_release(dict);
    458 	return rval;
    459 }
    460 
    461 static int
    462 find_sensors(prop_array_t array, const char *dvname, dvprops_t edp)
    463 {
    464 	prop_object_iterator_t iter;
    465 	prop_object_t obj, obj1, obj2;
    466 	prop_string_t state, desc = NULL;
    467 	sensor_t sensor = NULL;
    468 	sensor_stats_t stats = NULL;
    469 
    470 	iter = prop_array_iterator(array);
    471 	if (!iter)
    472 		return ENOMEM;
    473 
    474 	/* iterate over the array of dictionaries */
    475 	while ((obj = prop_object_iterator_next(iter)) != NULL) {
    476 		/* get the refresh-timeout property */
    477 		obj2 = prop_dictionary_get(obj, "device-properties");
    478 		if (obj2) {
    479 			if (!edp)
    480 				continue;
    481 			if (!prop_dictionary_get_uint64(obj2,
    482 							"refresh-timeout",
    483 							&edp->refresh_timo))
    484 				continue;
    485 		}
    486 
    487 		/* new sensor coming */
    488 		sensor = calloc(1, sizeof(*sensor));
    489 		if (sensor == NULL) {
    490 			prop_object_iterator_release(iter);
    491 			return ENOMEM;
    492 		}
    493 
    494 		/* copy device name */
    495 		(void)strlcpy(sensor->dvname, dvname, sizeof(sensor->dvname));
    496 
    497 		/* description string */
    498 		desc = prop_dictionary_get(obj, "description");
    499 		if (desc) {
    500 			/* copy description */
    501 			(void)strlcpy(sensor->desc,
    502 			    prop_string_cstring_nocopy(desc),
    503 		    	    sizeof(sensor->desc));
    504 		} else {
    505 			free(sensor);
    506 			continue;
    507 		}
    508 
    509 		/* type string */
    510 		obj1  = prop_dictionary_get(obj, "type");
    511 		if (obj1) {
    512 			/* copy type */
    513 			(void)strlcpy(sensor->type,
    514 		    	    prop_string_cstring_nocopy(obj1),
    515 		    	    sizeof(sensor->type));
    516 		} else {
    517 			free(sensor);
    518 			continue;
    519 		}
    520 
    521 		/* check sensor's state */
    522 		state = prop_dictionary_get(obj, "state");
    523 
    524 		/* mark sensors with invalid/unknown state */
    525 		if ((prop_string_equals_cstring(state, "invalid") ||
    526 		     prop_string_equals_cstring(state, "unknown")))
    527 			sensor->invalid = true;
    528 
    529 		/* get current drive state string */
    530 		obj1 = prop_dictionary_get(obj, "drive-state");
    531 		if (obj1) {
    532 			(void)strlcpy(sensor->drvstate,
    533 			    prop_string_cstring_nocopy(obj1),
    534 			    sizeof(sensor->drvstate));
    535 		}
    536 
    537 		/* get current battery capacity string */
    538 		obj1 = prop_dictionary_get(obj, "battery-capacity");
    539 		if (obj1) {
    540 			(void)strlcpy(sensor->battcap,
    541 			    prop_string_cstring_nocopy(obj1),
    542 			    sizeof(sensor->battcap));
    543 		}
    544 
    545 		/* get current value */
    546 		obj1 = prop_dictionary_get(obj, "cur-value");
    547 		if (obj1)
    548 			sensor->cur_value = prop_number_integer_value(obj1);
    549 
    550 		/* get max value */
    551 		obj1 = prop_dictionary_get(obj, "max-value");
    552 		if (obj1)
    553 			sensor->max_value = prop_number_integer_value(obj1);
    554 
    555 		/* get min value */
    556 		obj1 = prop_dictionary_get(obj, "min-value");
    557 		if (obj1)
    558 			sensor->min_value = prop_number_integer_value(obj1);
    559 
    560 		/* get avg value */
    561 		obj1 = prop_dictionary_get(obj, "avg-value");
    562 		if (obj1)
    563 			sensor->avg_value = prop_number_integer_value(obj1);
    564 
    565 		/* get percentage flag */
    566 		obj1 = prop_dictionary_get(obj, "want-percentage");
    567 		if (obj1)
    568 			sensor->percentage = prop_bool_true(obj1);
    569 
    570 		/* get critical max value if available */
    571 		obj1 = prop_dictionary_get(obj, "critical-max");
    572 		if (obj1)
    573 			sensor->critmax_value = prop_number_integer_value(obj1);
    574 
    575 		/* get critical min value if available */
    576 		obj1 = prop_dictionary_get(obj, "critical-min");
    577 		if (obj1)
    578 			sensor->critmin_value = prop_number_integer_value(obj1);
    579 
    580 		/* get critical capacity value if available */
    581 		obj1 = prop_dictionary_get(obj, "critical-capacity");
    582 		if (obj1)
    583 			sensor->critcap_value = prop_number_integer_value(obj1);
    584 
    585 		/* get warning max value if available */
    586 		obj1 = prop_dictionary_get(obj, "warning-max");
    587 		if (obj1)
    588 			sensor->warnmax_value = prop_number_integer_value(obj1);
    589 
    590 		/* get warning min value if available */
    591 		obj1 = prop_dictionary_get(obj, "warning-min");
    592 		if (obj1)
    593 			sensor->warnmin_value = prop_number_integer_value(obj1);
    594 
    595 		/* get warning capacity value if available */
    596 		obj1 = prop_dictionary_get(obj, "warning-capacity");
    597 		if (obj1)
    598 			sensor->warncap_value = prop_number_integer_value(obj1);
    599 
    600 		/* print sensor names if -l was given */
    601 		if (flags & ENVSYS_LFLAG) {
    602 			if (width)
    603 				(void)printf("%*s\n", width,
    604 				    prop_string_cstring_nocopy(desc));
    605 			else
    606 				(void)printf("%s\n",
    607 				    prop_string_cstring_nocopy(desc));
    608 		}
    609 
    610 		/* Add the sensor into the list */
    611 		SIMPLEQ_INSERT_TAIL(&sensors_list, sensor, entries);
    612 
    613 		/* Collect statistics if flag enabled */
    614 		if (statistics) {
    615 			/* ignore sensors not relevant for statistics */
    616 			if ((strcmp(sensor->type, "Indicator") == 0) ||
    617 			    (strcmp(sensor->type, "Battery charge") == 0) ||
    618 			    (strcmp(sensor->type, "Drive") == 0))
    619 				continue;
    620 
    621 			/* ignore invalid data */
    622 			if (sensor->invalid || !sensor->cur_value)
    623 				continue;
    624 
    625 			/* find or allocate a new statistics sensor */
    626 			stats = find_stats_sensor(sensor->desc);
    627 			if (stats == NULL) {
    628 				free(sensor);
    629 				prop_object_iterator_release(iter);
    630 				return ENOMEM;
    631 			}
    632 
    633 			/* collect data */
    634 			if (!stats->max)
    635 				stats->max = sensor->cur_value;
    636 			if (!stats->min)
    637 				stats->min = sensor->cur_value;
    638 
    639 			if (sensor->cur_value > stats->max)
    640 				stats->max = sensor->cur_value;
    641 
    642 			if (sensor->cur_value < stats->min)
    643 				stats->min = sensor->cur_value;
    644 
    645 			/* compute avg value */
    646 			if (stats->max && stats->min)
    647 				stats->avg =
    648 				    (sensor->cur_value + stats->max +
    649 				    stats->min) / 3;
    650 		}
    651 	}
    652 
    653 	/* free memory */
    654 	prop_object_iterator_release(iter);
    655 	return 0;
    656 }
    657 
    658 static int
    659 check_sensors(char *str)
    660 {
    661 	sensor_t sensor = NULL;
    662 	char *dvstring, *sstring, *p, *last;
    663 	bool sensor_found = false;
    664 
    665 	/*
    666 	 * Parse device name and sensor description and find out
    667 	 * if the sensor is valid.
    668 	 */
    669 	for ((p = strtok_r(str, ",", &last)); p;
    670 	     (p = strtok_r(NULL, ",", &last))) {
    671 		/* get device name */
    672 		dvstring = strtok(p, ":");
    673 		if (dvstring == NULL) {
    674 			warnx("missing device name");
    675 			return EINVAL;
    676 		}
    677 
    678 		/* get sensor description */
    679 		sstring = strtok(NULL, ":");
    680 		if (sstring == NULL) {
    681 			warnx("missing sensor description");
    682 			return EINVAL;
    683 		}
    684 
    685 		SIMPLEQ_FOREACH(sensor, &sensors_list, entries) {
    686 			/* skip until we match device */
    687 			if (strcmp(dvstring, sensor->dvname))
    688 				continue;
    689 			if (strcmp(sstring, sensor->desc) == 0) {
    690 				sensor->visible = true;
    691 				sensor_found = true;
    692 				break;
    693 			}
    694 		}
    695 		if (sensor_found == false) {
    696 			warnx("unknown sensor `%s' for device `%s'",
    697 		       	    sstring, dvstring);
    698 			return EINVAL;
    699 		}
    700 		sensor_found = false;
    701 	}
    702 
    703 	/* check if all sensors were ok, and error out if not */
    704 	SIMPLEQ_FOREACH(sensor, &sensors_list, entries)
    705 		if (sensor->visible)
    706 			return 0;
    707 
    708 	warnx("no sensors selected to display");
    709 	return EINVAL;
    710 }
    711 
    712 static void
    713 print_sensors(void)
    714 {
    715 	sensor_t sensor;
    716 	sensor_stats_t stats = NULL;
    717 	size_t maxlen = 0, ilen = 32 + 3;
    718 	double temp = 0;
    719 	const char *invalid = "N/A", *degrees, *tmpstr, *stype;
    720 	const char *a, *b, *c, *d, *units;
    721 
    722 	tmpstr = stype = d = NULL;
    723 
    724 	/* find the longest description */
    725 	SIMPLEQ_FOREACH(sensor, &sensors_list, entries)
    726 		if (strlen(sensor->desc) > maxlen)
    727 			maxlen = strlen(sensor->desc);
    728 
    729 	if (width)
    730 		maxlen = width;
    731 
    732 	/*
    733 	 * Print a header at the bottom only once showing different
    734 	 * members if the statistics flag is set or not.
    735 	 *
    736 	 * As bonus if -s is set, only print this header every 10 iterations
    737 	 * to avoid redundancy... like vmstat(1).
    738 	 */
    739 
    740 	a = "Current";
    741 	units = "Unit";
    742 	if (statistics) {
    743 		b = "Max";
    744 		c = "Min";
    745 		d = "Avg";
    746 	} else if (flags & ENVSYS_WFLAG) {
    747 		b = "WarnMax";
    748 		c = "WarnMin";
    749 		d = "WarnCap";
    750 	} else {
    751 		b = "CritMax";
    752 		c = "CritMin";
    753 		d = "CritCap";
    754 	}
    755 
    756 	if (!sensors || (!header_passes && sensors) ||
    757 	    (header_passes == 10 && sensors)) {
    758 		(void)printf("%s%*s  %10s %8s %8s %8s %8s\n",
    759 		    mydevname ? "" : "  ", (int)maxlen,
    760 		    "", a, b, c, d, units);
    761 		if (sensors && header_passes == 10)
    762 			header_passes = 0;
    763 	}
    764 	if (sensors)
    765 		header_passes++;
    766 
    767 	/* print the sensors */
    768 	SIMPLEQ_FOREACH(sensor, &sensors_list, entries) {
    769 		/* skip sensors that were not marked as visible */
    770 		if (sensors && !sensor->visible)
    771 			continue;
    772 
    773 		/* skip invalid sensors if -I is set */
    774 		if ((flags & ENVSYS_IFLAG) && sensor->invalid)
    775 			continue;
    776 
    777 		/* print device name */
    778 		if (!mydevname) {
    779 			if (tmpstr == NULL || strcmp(tmpstr, sensor->dvname))
    780 				printf("[%s]\n", sensor->dvname);
    781 
    782 			tmpstr = sensor->dvname;
    783 		}
    784 
    785 		/* find out the statistics sensor */
    786 		if (statistics) {
    787 			stats = find_stats_sensor(sensor->desc);
    788 			if (stats == NULL) {
    789 				/* No statistics for this sensor */
    790 				continue;
    791 			}
    792 		}
    793 
    794 		/* print sensor description */
    795 		(void)printf("%s%*.*s", mydevname ? "" : "  ", (int)maxlen,
    796 		    (int)maxlen, sensor->desc);
    797 
    798 		/* print invalid string */
    799 		if (sensor->invalid) {
    800 			(void)printf(": %10s\n", invalid);
    801 			continue;
    802 		}
    803 
    804 		/*
    805 		 * Indicator and Battery charge sensors.
    806 		 */
    807 		if ((strcmp(sensor->type, "Indicator") == 0) ||
    808 		    (strcmp(sensor->type, "Battery charge") == 0)) {
    809 
    810 			(void)printf(": %10s", sensor->cur_value ? "ON" : "OFF");
    811 
    812 /* converts the value to degC or degF */
    813 #define CONVERTTEMP(a, b, c)					\
    814 do {								\
    815 	if (b) 							\
    816 		(a) = ((b) / 1000000.0) - 273.15;		\
    817 	if (flags & ENVSYS_FFLAG) {				\
    818 		if (b)						\
    819 			(a) = (9.0 / 5.0) * (a) + 32.0;		\
    820 		(c) = "degF";					\
    821 	} else							\
    822 		(c) = "degC";					\
    823 } while (/* CONSTCOND */ 0)
    824 
    825 
    826 		/* temperatures */
    827 		} else if (strcmp(sensor->type, "Temperature") == 0) {
    828 
    829 			CONVERTTEMP(temp, sensor->cur_value, degrees);
    830 			stype = degrees;
    831 			(void)printf(": %10.3f ", temp);
    832 
    833 			if (statistics) {
    834 				/* show statistics if flag set */
    835 				CONVERTTEMP(temp, stats->max, degrees);
    836 				(void)printf("%8.3f ", temp);
    837 				CONVERTTEMP(temp, stats->min, degrees);
    838 				(void)printf("%8.3f ", temp);
    839 				CONVERTTEMP(temp, stats->avg, degrees);
    840 				(void)printf("%8.3f ", temp);
    841 				ilen = 8;
    842 			} else if (flags & ENVSYS_WFLAG) {
    843 				if (sensor->warnmax_value) {
    844 					CONVERTTEMP(temp,
    845 					    sensor->warnmax_value, degrees);
    846 					(void)printf( "%8.3f ", temp);
    847 					ilen = 24 + 2;
    848 				}
    849 
    850 				if (sensor->warnmin_value) {
    851 					CONVERTTEMP(temp,
    852 					    sensor->warnmin_value, degrees);
    853 					if (sensor->warnmax_value)
    854 						ilen = 8;
    855 					else
    856 						ilen = 16 + 1;
    857 
    858 					(void)printf("%*.3f ", (int)ilen, temp);
    859 					ilen = 16 + 1;
    860 				}
    861 			} else {
    862 				if (sensor->critmax_value) {
    863 					CONVERTTEMP(temp,
    864 					    sensor->critmax_value, degrees);
    865 					(void)printf( "%8.3f ", temp);
    866 					ilen = 24 + 2;
    867 				}
    868 
    869 				if (sensor->critmin_value) {
    870 					CONVERTTEMP(temp,
    871 					    sensor->critmin_value, degrees);
    872 					if (sensor->critmax_value)
    873 						ilen = 8;
    874 					else
    875 						ilen = 16 + 1;
    876 
    877 					(void)printf("%*.3f ", (int)ilen, temp);
    878 					ilen = 16 + 1;
    879 				}
    880 			}
    881 
    882 			(void)printf("%*s", (int)ilen, stype);
    883 #undef CONVERTTEMP
    884 
    885 		/* fans */
    886 		} else if (strcmp(sensor->type, "Fan") == 0) {
    887 			stype = "RPM";
    888 
    889 			(void)printf(": %10u ", sensor->cur_value);
    890 			if (statistics) {
    891 				/* show statistics if flag set */
    892 				(void)printf("%8u %8u %8u ",
    893 				    stats->max, stats->min, stats->avg);
    894 				ilen = 8;
    895 			} else if (flags & ENVSYS_WFLAG) {
    896 				if (sensor->warnmax_value) {
    897 					(void)printf("%8u ",
    898 					    sensor->warnmax_value);
    899 					ilen = 24 + 2;
    900 				}
    901 
    902 				if (sensor->warnmin_value) {
    903 					if (sensor->warnmax_value)
    904 						ilen = 8;
    905 					else
    906 						ilen = 16 + 1;
    907 					(void)printf("%*u ", (int)ilen,
    908 					    sensor->warnmin_value);
    909 					ilen = 16 + 1;
    910 				}
    911 			} else {
    912 				if (sensor->critmax_value) {
    913 					(void)printf("%8u ",
    914 					    sensor->critmax_value);
    915 					ilen = 24 + 2;
    916 				}
    917 
    918 				if (sensor->critmin_value) {
    919 					if (sensor->critmax_value)
    920 						ilen = 8;
    921 					else
    922 						ilen = 16 + 1;
    923 					(void)printf("%*u ", (int)ilen,
    924 					    sensor->critmin_value);
    925 					ilen = 16 + 1;
    926 				}
    927 			}
    928 
    929 			(void)printf("%*s", (int)ilen, stype);
    930 
    931 		/* integers */
    932 		} else if (strcmp(sensor->type, "Integer") == 0) {
    933 
    934 			(void)printf(": %10d", sensor->cur_value);
    935 
    936 		/* drives  */
    937 		} else if (strcmp(sensor->type, "Drive") == 0) {
    938 
    939 			(void)printf(": %10s", sensor->drvstate);
    940 
    941 		/* Battery capacity */
    942 		} else if (strcmp(sensor->type, "Battery capacity") == 0) {
    943 
    944 			(void)printf(": %10s", sensor->battcap);
    945 
    946 		/* everything else */
    947 		} else {
    948 			if (strcmp(sensor->type, "Voltage DC") == 0)
    949 				stype = "V";
    950 			else if (strcmp(sensor->type, "Voltage AC") == 0)
    951 				stype = "VAC";
    952 			else if (strcmp(sensor->type, "Ampere") == 0)
    953 				stype = "A";
    954 			else if (strcmp(sensor->type, "Watts") == 0)
    955 				stype = "W";
    956 			else if (strcmp(sensor->type, "Ohms") == 0)
    957 				stype = "Ohms";
    958 			else if (strcmp(sensor->type, "Watt hour") == 0)
    959 				stype = "Wh";
    960 			else if (strcmp(sensor->type, "Ampere hour") == 0)
    961 				stype = "Ah";
    962 
    963 			(void)printf(": %10.3f ",
    964 			    sensor->cur_value / 1000000.0);
    965 
    966 			if (!statistics) {
    967 				if (flags & ENVSYS_WFLAG) {
    968 					if (sensor->warnmax_value) {
    969 						(void)printf("%8.3f ",
    970 						    sensor->warnmax_value / 1000000.0);
    971 						ilen = 24 + 2;
    972 					}
    973 
    974 					if (sensor->warnmin_value) {
    975 						if (sensor->warnmax_value)
    976 							ilen = 8;
    977 						else
    978 							ilen = 16 + 1;
    979 						(void)printf("%*.3f ", (int)ilen,
    980 						    sensor->warnmin_value / 1000000.0);
    981 						ilen = 16 + 1;
    982 					}
    983 					if (sensor->warncap_value) {
    984 						ilen = 24 + 2;
    985 						(void)printf("%*.2f%% ", (int)ilen,
    986 						    (sensor->critcap_value * 100.0) /
    987 						    sensor->max_value);
    988 						ilen = 8;
    989 					}
    990 				} else {
    991 					if (sensor->critmax_value) {
    992 						(void)printf("%8.3f ",
    993 						    sensor->critmax_value / 1000000.0);
    994 						ilen = 24 + 2;
    995 					}
    996 
    997 					if (sensor->critmin_value) {
    998 						if (sensor->critmax_value)
    999 							ilen = 8;
   1000 						else
   1001 							ilen = 16 + 1;
   1002 						(void)printf("%*.3f ", (int)ilen,
   1003 						    sensor->critmin_value / 1000000.0);
   1004 						ilen = 16 + 1;
   1005 
   1006 					}
   1007 
   1008 					if (sensor->critcap_value) {
   1009 						ilen = 24 + 2;
   1010 						(void)printf("%*.2f%% ", (int)ilen,
   1011 						    (sensor->critcap_value * 100.0) /
   1012 						    sensor->max_value);
   1013 						ilen = 8;
   1014 					}
   1015 				}
   1016 			}
   1017 
   1018 			if (statistics && !sensor->percentage) {
   1019 				/* show statistics if flag set */
   1020 				(void)printf("%8.3f %8.3f %8.3f ",
   1021 				    stats->max / 1000000.0,
   1022 				    stats->min / 1000000.0,
   1023 				    stats->avg / 1000000.0);
   1024 				ilen = 8;
   1025 			}
   1026 
   1027 			(void)printf("%*s", (int)ilen, stype);
   1028 			if (sensor->percentage && sensor->max_value) {
   1029 				(void)printf("  (%5.2f%%)",
   1030 				    (sensor->cur_value * 100.0) /
   1031 				    sensor->max_value);
   1032 			}
   1033 		}
   1034 		(void)printf("\n");
   1035 		ilen = 32 + 3;
   1036 	}
   1037 }
   1038 
   1039 static int
   1040 usage(void)
   1041 {
   1042 	(void)fprintf(stderr, "Usage: %s [-DfIlrSTx] ", getprogname());
   1043 	(void)fprintf(stderr, "[-c file] [-d device] [-i interval] ");
   1044 	(void)fprintf(stderr, "[-s device:sensor,...] [-w width]\n");
   1045 	exit(EXIT_FAILURE);
   1046 	/* NOTREACHED */
   1047 }
   1048