File: apcsmart.c

package info (click to toggle)
nut 0.45.5-rel-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,984 kB
  • ctags: 2,146
  • sloc: ansic: 22,216; sh: 1,138; makefile: 405
file content (789 lines) | stat: -rw-r--r-- 20,023 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
/* apcsmart.c - model specific routines for APC smart protocol units

   Copyright (C) 1999  Russell Kroll <rkroll@exploits.org>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include "main.h"
#include "apcsmart.h"

	extern	int	sddelay;
	int	cap_measureupsii = 0, upslevel = 0;
	int	shutdowncmdset = 0; /* The shutdown command set to use */

#define ALT_CABLE_1 "940-0095B"

/* try to find AMBTEMP, CONTACTS and AMBHUMID */
void test_measureupsii(void)
{
	char	temp[256];

	upssendchar(REQ_AMBTEMP);
	upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

	if (!strcmp(temp, "NA"))	/* not supported */
		return;

	/* we got something, so it must be supported */

	cap_measureupsii = 1;		/* log this fact */

	addinfo(INFO_AMBTEMP, temp, 0, 0);

	/* Now probe the contacts */

	upssendchar(REQ_CONTACTS);
	upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

	addinfo(INFO_CONTACTS, temp, 0, 0);

	/* now try for ambient humidity support */

	upssendchar(REQ_AMBHUMID);
	upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

	if (!strcmp(temp, "NA"))	/* not supported */
		return;

	addinfo(INFO_AMBHUMID, temp, 0, 0);
}

void addcap(char cmdchar, char *value)
{
	switch (cmdchar) {
		case 'u': addenum(INFO_HIGHXFER, value);
			  setflag(INFO_HIGHXFER, FLAG_RW | FLAG_ENUM);
			  break;

		case 'l': addenum(INFO_LOWXFER, value);
			  setflag(INFO_LOWXFER, FLAG_RW | FLAG_ENUM);
			  break;

		case 'e': addenum(INFO_RTHRESH, value);
			  setflag(INFO_RTHRESH, FLAG_RW | FLAG_ENUM);
			  break;

		case 'o': break;	/* output voltages, unused now	*/

		case 's': addenum(INFO_LINESENS, value);
			  setflag(INFO_LINESENS, FLAG_RW | FLAG_ENUM);
			  break;

		case 'q': break;	/* TODO: low batt warning	*/

		case 'p': addenum(INFO_GRACEDELAY, value);
			  setflag(INFO_GRACEDELAY, FLAG_RW | FLAG_ENUM);
			  break;

		case 'k': addenum(INFO_ALRMDEL, value);
			  setflag(INFO_ALRMDEL, FLAG_RW | FLAG_ENUM);
			  break;

		case 'r': addenum(INFO_WAKEDELAY, value);
			  setflag(INFO_WAKEDELAY, FLAG_RW | FLAG_ENUM);
			  break;

		case 'E': break;	/* TODO: selftest intervals	*/
		case 0x06: break;	/* TODO: find out what ^F is	*/
		case 0x0c: break;	/* TODO: front panel language	*/
		case 'w': break;	/* TODO: runtime conservation	*/
		default:
			printf("Unrecognized cmdchar %c, value %s\n",
			        cmdchar, value);
	}		
}	

void do_capabilities(void)
{
	char	upsloc, temp[512], *ptr, cmd, loc, *entptr, etmp[16], *endtemp;
	int	nument, entlen, i, matrix, recvret;

	/* just in case ... */
	usleep(50000);

	/* get location byte for later comparisons */
	upssendchar('V');
	upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);
	upsloc = temp[strlen(temp) - 1];

	/* add base entries for these variables */

	/* create them as normal variables for now - enum and rw flags    *
	 * get added later if the model actually supports such operations */

	addinfo(INFO_LOWXFER, "", 0, 0);
	addinfo(INFO_HIGHXFER, "", 0, 0);
	addinfo(INFO_WAKEDELAY, "", 0, 0);
	addinfo(INFO_LINESENS, "", 0, 0);
	addinfo(INFO_GRACEDELAY, "", 0, 0);
	addinfo(INFO_RTHRESH, "", 0, 0);
	addinfo(INFO_ALRMDEL, "", 0, 0);
	installinfo(INFO_LOWXFER, REQ_LOWXFER, ENDCHAR, IGNCHARS);
	installinfo(INFO_HIGHXFER, REQ_HIGHXFER, ENDCHAR, IGNCHARS);
	installinfo(INFO_WAKEDELAY, REQ_WAKEDELAY, ENDCHAR, IGNCHARS);
	installinfo(INFO_LINESENS, REQ_LINESENS, ENDCHAR, IGNCHARS);
	installinfo(INFO_GRACEDELAY, REQ_GRACEDELAY, ENDCHAR, IGNCHARS);
	installinfo(INFO_RTHRESH, REQ_RTHRESH, ENDCHAR, IGNCHARS);
	installinfo(INFO_ALRMDEL, REQ_ALRMDEL, ENDCHAR, IGNCHARS);

	/* battery change date */
	addinfo(INFO_BATTDATE, "", FLAG_RW | FLAG_STRING, 8);
	installinfo(INFO_BATTDATE, REQ_BATTDATE, ENDCHAR, IGNCHARS);

	/* get capability string */
	upssendchar(REQ_CAPABILITIES);	/* ^Z */
	strcpy(temp, "NA");
	recvret = upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

	if ((recvret == -1) || (!strcmp(temp, "NA"))) {
		/* Early Smart-UPS, not as smart as later ones */
		return;
	}

	/* recv always puts a \0 at the end, so this is safe */
	/* however it assumes a zero byte cannot be embedded */
	endtemp = &temp[0] + strlen(temp);

	if (temp[0] != '#') {
		printf("Unrecognized capability start char %c\n", temp[0]);
		printf("Please report this error [%s]\n", temp);
		return;
	}

	if (temp[1] == '#') {		/* Matrix-UPS */
		matrix = 1;
		ptr = &temp[0];
	}
	else {
		ptr = &temp[1];
		matrix = 0;
	}

	/* command char, location, # of entries, entry length */

	while (ptr[0] != '\0') {
		if (matrix)
			ptr += 2;	/* jump over repeating ## */

		/* check for idiocy */
		if (ptr >= endtemp) {
			printf("Capability string has overflowed\n");
			printf("Please report this error\n");
			fatalx("ERROR: capability overflow!");
		}

		cmd = ptr[0];
		loc = ptr[1];
		nument = ptr[2] - 48;
		entlen = ptr[3] - 48;
		entptr = &ptr[4];

		for (i = 0; i < nument; i++) {
			snprintf(etmp, entlen + 1, "%s", entptr);
			if ((loc == upsloc) || (loc == '4'))
				addcap (cmd, etmp);
			entptr += entlen;
		}
		ptr = entptr;
	}
}

void do_status(void)
{
	char	temp[256], itemp[256];
	int	tval;
	int cal = 0;

	/* parse the status */
	upssendchar(REQ_STATUS);
	upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

	/* APC SU600 models return this when the FPTEST is still active */
	if (!strncmp(temp, "BC", 2))
		return;			/* bogus, we don't want to parse it */

	tval = strtol(temp, 0, 16);

	strcpy(itemp, "");
	if (tval & 1) {
		strcat(itemp, "CAL ");		/* calibration */
		cal = 1;
	}
	if (tval & 2)
		strcat(itemp, "TRIM ");	/* SmartTrim */
	if (tval & 4)
		strcat(itemp, "BOOST ");	/* SmartBoost */
	if (tval & 8)
		strcat(itemp, "OL ");		/* on line */
	if (tval & 16)
		strcat(itemp, "OB ");		/* on battery */
	if (tval & 32)
		strcat(itemp, "OVER ");	/* overload */
	if (tval & 64)
		strcat(itemp, cal ? "OB" : "LB ");	/* low battery */
	if (tval & 128)
		strcat(itemp, "RB ");		/* replace batt */

	if (!strcmp(temp, "00"))
		strcpy(itemp, "OFF");

	/* lose trailing space if present */
	if (itemp[strlen(itemp)-1] == ' ')
		itemp[strlen(itemp)-1] = 0;

	setinfo(INFO_STATUS, "%s", itemp);
}

void getbaseinfo(const char *port)
{
	char	temp[256];
	int	silentfail = 0, oldmatrix = 0;
	int	recvret = 0;

	upslevel = 1;

	/* really old models ignore REQ_MODEL, so find them first */
	upssendchar(REQ_MODEL);
	strcpy(temp, "NA");

	/* disable timeout complaints temporarily */
	flag_timeoutfailure = -1;
	recvret = upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);
	flag_timeoutfailure = 0;

	if ((recvret == -1) || (!strcmp(temp, "NA"))) {
		/* force the model name */
		addinfo(INFO_MODEL, "Smart-UPS", 0, 0);
		silentfail = 1;
	}
	else
		addinfo(INFO_MODEL, temp, 0, 0);

	/* see if this might be an old Matrix-UPS instead */
	upssendchar('/');
	flag_timeoutfailure = -1;
	strcpy(temp, "NA");
	recvret = upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);
	flag_timeoutfailure = 0;

	/* it returned a useful number, so it must be a Matrix-UPS */
	if ((recvret != -1) && (strcmp(temp, "NA")) != 0) {
		oldmatrix = 1;	/* doesn't do 'b' */
		setinfo(INFO_MODEL, "%s", "Matrix-UPS");
	}

	addinfo(INFO_SERIAL, "", 0, 0);
	installinfo(INFO_SERIAL, REQ_SERIAL, ENDCHAR, IGNCHARS);

	addinfo(INFO_STATUS, "", 0, 0);
	do_status();

	/* upslevel 1: Smart-UPS v/s, older Back-UPS Pros */
	upssendchar(REQ_UTILITY);
	strcpy(temp, "NA");
	recvret = upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);
	if ((!strcmp(temp, "NA")) || (recvret == -1)) {
		upslevel = 1;
		return;
	}

	/* upslevel 2: at least a modern Smart-UPS / Back-UPS Pro */
	upslevel = 2;

	/* add other things to monitor and prime them with values */

	addinfo(INFO_UTILITY, "", 0, 0);
	installinfo(INFO_UTILITY, REQ_UTILITY, ENDCHAR, IGNCHARS);

	addinfo(INFO_BATTPCT, "", 0, 0);
	installinfo(INFO_BATTPCT, REQ_BATTPCT, ENDCHAR, IGNCHARS);

	addinfo(INFO_ACFREQ, "", 0, 0);
	installinfo(INFO_ACFREQ, REQ_ACFREQ, ENDCHAR, IGNCHARS);

	addinfo(INFO_LOADPCT, "", 0, 0);
	installinfo(INFO_LOADPCT, REQ_LOADPCT, ENDCHAR, IGNCHARS);

	addinfo(INFO_BATTVOLT, "", 0, 0);
	installinfo(INFO_BATTVOLT, REQ_BATTVOLT, ENDCHAR, IGNCHARS);

	addinfo(INFO_OUTVOLT, "", 0, 0);
	installinfo(INFO_OUTVOLT, REQ_OUTVOLT, ENDCHAR, IGNCHARS);

	/* upslevel 3: at least a Smart-UPS (beyond the Back-UPS Pro) */

	/* test for UPSTEMP support */
	strcpy(temp, "NA");

	upssendchar(REQ_UPSTEMP);
	upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);
	if (strcmp(temp, "NA") != 0) {
		upslevel = 3;
		addinfo(INFO_UPSTEMP, temp, 0, 0);
	}

	addinfo(INFO_UPSIDENT, "", FLAG_RW | FLAG_STRING, 8);
	installinfo(INFO_UPSIDENT, REQ_UPSIDENT, ENDCHAR, IGNCHARS);

	/* now add the instant commands */
	addinfo(INFO_INSTCMD, "", 0, CMD_FPTEST);
	addinfo(INFO_INSTCMD, "", 0, CMD_BTEST1);
	addinfo(INFO_INSTCMD, "", 0, CMD_OFF);
	addinfo(INFO_INSTCMD, "", 0, CMD_ON);
	addinfo(INFO_INSTCMD, "", 0, CMD_CAL0);
	addinfo(INFO_INSTCMD, "", 0, CMD_CAL1);

	do_capabilities();

	/* that's all for 'silent failure' units */
	if (silentfail)
		return;

	/* see if we have a Measure-UPS II connected */
	test_measureupsii();
}

/* normal idle loop - keep up with the current state of the UPS */
void upsdrv_updateinfo(void)
{
	char	temp[256];

	/* try to wake up a dead ups once in awhile */
	if (flag_timeoutfailure == 1) {
		upssendchar(GO_SMART);
		upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);
	}

	do_status();

	/* upslevel 1 only has a status readback */
	if (upslevel < 2) {
		writeinfo();
		return;
	}

	installinfo(INFO_UTILITY, REQ_UTILITY, ENDCHAR, IGNCHARS);
	installinfo(INFO_BATTPCT, REQ_BATTPCT, ENDCHAR, IGNCHARS);
	installinfo(INFO_ACFREQ, REQ_ACFREQ, ENDCHAR, IGNCHARS);
	installinfo(INFO_LOADPCT, REQ_LOADPCT, ENDCHAR, IGNCHARS);
	installinfo(INFO_BATTVOLT, REQ_BATTVOLT, ENDCHAR, IGNCHARS);
	installinfo(INFO_OUTVOLT, REQ_OUTVOLT, ENDCHAR, IGNCHARS);

	/* need at least 3 for ups temperature and Measure-UPS II */
	if (upslevel < 3) {
		writeinfo();
		return;
	}

	installinfo(INFO_UPSTEMP, REQ_UPSTEMP, ENDCHAR, IGNCHARS);

	if (cap_measureupsii) {
		installinfo(INFO_AMBHUMID, REQ_AMBHUMID, ENDCHAR, IGNCHARS);
		installinfo(INFO_AMBTEMP, REQ_AMBTEMP, ENDCHAR, IGNCHARS);
		installinfo(INFO_CONTACTS, REQ_CONTACTS, ENDCHAR, IGNCHARS);
	}

	writeinfo();
}

/* TODO: roll this into upscommon ala bestups */
void sendstring(char * string, int len, int delay)
{
	int	i;

	for (i=0; (i<len); i++) {
	        upssendchar(string[i]);
		usleep(delay);
	}
}

/* get the UPS talking to us in smart mode */
int smartmode(void)
{
	int	tries;
	char	temp[256];

	tries = 0;
	for (;;) {
		tries++;

		upssendchar(GO_SMART);
		upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

		if (!strcmp(temp, "SM"))
			return 1;	/* success */

		if (tries > 5)
			return 0;	/* failure */

		sleep(1);	/* wait before trying again */
	}

	return 0;	/* notreached */
}

/* 940-0095B support: set DTR, lower RTS */
void init_serial_0095B(void)
{
	int	dtr_bit = TIOCM_DTR;
	int	rts_bit = TIOCM_RTS;

	ioctl(upsfd, TIOCMBIS, &dtr_bit);
	ioctl(upsfd, TIOCMBIC, &rts_bit);
}

/* set a value in the hardware using the <cmdchar> '-' (repeat) approach */
void hw_set (char cmdchar, char *newval)
{
	char	temp[256], orig[256];
	int	tries;

	upssendchar(cmdchar);
	upsrecv(orig, sizeof(orig), ENDCHAR, IGNCHARS);

	/* don't change it if already set - save wear and tear on the eeprom */
	if (!strcmp(orig, newval))
		return;

	tries = 0;
	while (tries < 6) {
		upssendchar(NEXT_VAL);
		upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

		/* TODO: test for "OK", bail out on "NO", etc */
		upssendchar(cmdchar);
		upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

		if (!strcmp(temp, newval)) 		/* got it */
			return;

		if (!strcmp(temp, orig)) {		/* wrapped around */
			upslogx(LOG_ERR, "setvar: variable %c wrapped!\n",
			        cmdchar);
			return;
		}

		tries++;
	}

	upslogx(LOG_ERR, "setvar: gave up after 6 tries\n");
}

/* set string values in the UPS EEPROM (battery date, local identity) */
void setstring (char *data, char reqchar)
{
	char	temp[256];
	int	i;

	upssendchar(reqchar);
	upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

	upssendchar(NEXT_VAL);
	usleep(50000);

	for (i = 0; i < strlen(data); i++) {
		upssendchar(data[i]);
		usleep(50000);
	}

	/* pad to 8 chars with CRs */
	for (i = strlen(data); i < 8; i++) {
		upssendchar(13);
		usleep(50000);
	}

	usleep(50000);
	upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);
	usleep(50000);

	/* TODO: check for "OK" or "NO" or similar */
}

void setvar (int auxcmd, int dlen, char *data)
{
	/* TODO: look this up from a table? */
	switch (auxcmd) {
		case INFO_WAKEDELAY:
			hw_set(REQ_WAKEDELAY, data);
			installinfo(INFO_WAKEDELAY, REQ_WAKEDELAY, ENDCHAR, IGNCHARS);
			break;
		case INFO_LOWXFER:
			hw_set(REQ_LOWXFER, data);
			installinfo(INFO_LOWXFER, REQ_LOWXFER, ENDCHAR, IGNCHARS);
			break;
		case INFO_HIGHXFER:
			hw_set(REQ_HIGHXFER, data);
			installinfo(INFO_HIGHXFER, REQ_HIGHXFER, ENDCHAR, IGNCHARS);
			break;
		case INFO_LINESENS:
			hw_set(REQ_LINESENS, data);
			installinfo(INFO_LINESENS, REQ_LINESENS, ENDCHAR, IGNCHARS);
			break;
		case INFO_GRACEDELAY:
			hw_set(REQ_GRACEDELAY, data);
			installinfo(INFO_GRACEDELAY, REQ_GRACEDELAY, ENDCHAR, IGNCHARS);
			break;
		case INFO_RTHRESH:
			hw_set(REQ_RTHRESH, data);
			installinfo(INFO_RTHRESH, REQ_RTHRESH, ENDCHAR, IGNCHARS);
			break;
		case INFO_ALRMDEL:
			hw_set(REQ_ALRMDEL, data);
			installinfo(INFO_ALRMDEL, REQ_ALRMDEL, ENDCHAR, IGNCHARS);
			break;
		case INFO_UPSIDENT:
			setstring(data, REQ_UPSIDENT);
			installinfo(INFO_UPSIDENT, REQ_UPSIDENT, ENDCHAR, IGNCHARS);
			break;
		case INFO_BATTDATE:
			setstring(data, REQ_BATTDATE);
			installinfo(INFO_BATTDATE, REQ_BATTDATE, ENDCHAR, IGNCHARS);
			break;
		default:
			upslogx(LOG_ERR, "setvar: unknown type 0x%04x\n",
			        auxcmd);
	}
}

/* check for calibration status and either start or stop */
void do_cal(int start)
{
	char	temp[256];
	int	tval, ret;

	upssendchar(REQ_STATUS);
	ret = upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);

	if (!ret)		/* didn't get status, bail out */
		return;

	tval = strtol(temp, 0, 16);

	if (tval & 1) {		/* calibration currently happening */
		if (start == 0)	{		/* stop requested */
			upslogx(LOG_INFO, "Stopping runtime calibration");
			upssendchar(REQ_CAL);
			return;
		}

		/* requested start while calibration still running */
		upslogx(LOG_INFO, "Runtime calibration already in progress");
		return;
	}

	/* calibration not happening */

	if (start == 0) {		/* stop requested */
		upslogx(LOG_INFO, "Runtime calibration not occurring");
		return;
	}

	upslogx(LOG_INFO, "Starting runtime calibration");
	upssendchar(REQ_CAL);
}

/* handle the CMD_OFF with some paranoia */
void do_off (void)
{
	static	time_t lastcmd = 0;
	time_t	now, elapsed;

#ifdef CONFIRM_DANGEROUS_COMMANDS
	time(&now);
	elapsed = now - lastcmd;

	/* reset the timer every call - this means if you call it too      *
	 * early, then you have to wait MINCMDTIME again before sending #2 */
	lastcmd = now;

	if ((elapsed < MINCMDTIME) || (elapsed > MAXCMDTIME)) {

		/* FUTURE: tell the user (via upsd) to try it again */
		/* msgreply (UPSMSG_REPAGAIN); */
		return;
	}
#endif

	upslogx(LOG_INFO, "Sending powerdown command to UPS\n");
	upssendchar(REQ_OFF);
	usleep(1500000);
	upssendchar(REQ_OFF);
}

void instcmd(int auxcmd, int dlen, char *data)
{
	char	temp[256];

	/* TODO: reply to upsd? */

	switch(auxcmd) {
		case CMD_FPTEST:	/* front panel test */
			upssendchar(REQ_FPTEST);
			upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);
			break;
		case CMD_BTEST1:	/* start battery test */
			upssendchar(REQ_BTEST);
			break;
		case CMD_OFF:		/* power off the load */
			do_off();
			break;
		case CMD_ON:		/* power on the load */
			upssendchar(REQ_ON);
			usleep(500000);
			upssendchar(REQ_ON);
			break;
		case CMD_CAL0:		/* stop runtime calibration */
			do_cal(0);
			break;
		case CMD_CAL1:		/* start runtime calibration */
			do_cal(1);
			break;
		default:
			upslogx(LOG_INFO, "instcmd: unknown type 0x%04x\n",
			        auxcmd);
	}
}

void upsdrv_banner(void)
{
	printf ("Network UPS Tools - APC Smart protocol driver 0.60 (%s)\n", UPS_VERSION);
}

/* prep the serial port */
void upsdrv_initups(void)
{
	char	*cable;

	open_serial(device_path, B2400);

	cable = getval("cable");

	if (cable)
		if (!strcasecmp(cable, ALT_CABLE_1))
			init_serial_0095B();
}

/* set up the variables we intend to monitor */
void upsdrv_initinfo(void)
{
	if (smartmode() == 0) {
		printf("Unable to detect an APC Smart protocol UPS on port %s\n", 
			device_path);
		printf("Check the cabling, port name or model name and try again\n");
		exit (1);
	}

	getbaseinfo(device_name);

	/* hardcode the manufacturer - it's pretty obvious here */
        addinfo (INFO_MFR, "APC", 0, 0);

	printf("Detected %s [%s] on %s (level %i)\n", getdata(INFO_MODEL), 
		getdata(INFO_SERIAL), device_path, upslevel);

	if (cap_measureupsii)
		printf("Measure-UPS II detected!\n");

	/* install handlers */
	upsh.instcmd = instcmd;
	upsh.setvar = setvar;
}

/* power down the attached load immediately */
void upsdrv_shutdown(void)
{
	char	temp[32];
	int	tval;

	if (smartmode() == 0)
		upslogx(LOG_WARNING, "Warning: unable to contact the UPS, but trying the shutdown anyway.");
	
	/* check the line status */

	upssendchar(REQ_STATUS);
	upsrecv(temp, sizeof(temp), ENDCHAR, IGNCHARS);
	tval = strtol(temp, 0, 16);

	switch (shutdowncmdset) {
		case 3:		/* shutdown with grace period */
			printf("Sending delayed power off command to UPS\n");
			upssendchar(REQ_SHUTDOWN);
			usleep(1500000);
			upssendchar(REQ_SHUTDOWN);
			break;

		case 2:		/* instant shutdown */
			printf("Sending power off command to UPS\n");
			upssendchar(REQ_OFF);
			usleep(1500000);
			upssendchar(REQ_OFF);
			break;

		case 1:

	/* Send a combined set of shutdown commands which can work better */
	/* if the UPS gets power during shutdown process */
	/* Specifically it sends both the soft shutdown 'S' */
	/* and the powerdown after grace period - '@000' commands */
			printf("UPS - currently %s - sending shutdown/powerdown\n",
			       (tval & 8) ? "on-line" : "on battery");
			sendstring("S@000", 5, 50000);
			break;

		default:

		/* @000 - shutdown after 'p' grace period             */
		/*      - returns after 000 minutes (i.e. right away) */

		/* S    - shutdown after 'p' grace period, only on battery */
		/*        returns after 'e' charge % plus 'r' seconds      */

			if (tval & 8) {                 /* on line */
				printf("On line, sending shutdown+return command...\n");
				sendstring("@000", 4, 50000);
			}
			else {
				printf("On battery, sending normal shutdown command...\n");
				upssendchar('S');
			}
	}
}

/* throw in our two cents when someone calls for -h from main */
void upsdrv_help(void)
{
	printf("\nShutdown types:\n");
	printf("  0: soft shutdown or powerdown, depending on battery status\n");
	printf("  1: soft shutdown followed by powerdown\n");
	printf("  2: instant power off\n");
	printf("  3: power off with grace period\n");
	printf("Modes 0-1 will make the UPS come back when power returns\n");
	printf("Modes 2-3 will make the UPS stay turned off when power returns\n");
}

/* list flags and values that you want to receive via -x */
void upsdrv_makevartable(void)
{
	addvar(VAR_VALUE, "cable", "Specify alternate cable (940-0095B)");
	addvar(VAR_VALUE, "sdtype", "Specify shutdown type (1-3)");
}

/* tell main how many entries we need */
int upsdrv_infomax(void)
{
	return 128;
}