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