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