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