File: apctest.c

package info (click to toggle)
apcupsd 3.8.5-1.1.1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 7,012 kB
  • ctags: 2,783
  • sloc: ansic: 26,374; sh: 3,012; makefile: 1,860; cpp: 1,713; perl: 191; sed: 93
file content (1440 lines) | stat: -rwxr-xr-x 38,712 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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
/*
 *  apctest.c -- a cable tester program for apcupsd
 *	 Hacked from apcupsd.c by Kern Sibbald, Sept 2000
 *
 */

/*
 *		       GNU GENERAL PUBLIC LICENSE
 *			  Version 2, June 1991
 *
 *  Copyright (C) 1989, 1991 Free Software Foundation, Inc.
 *			     675 Mass Ave, Cambridge, MA 02139, USA
 *  Everyone is permitted to copy and distribute verbatim copies
 *  of this license document, but changing it is not allowed.
 *
 *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include "apc.h"

/*
 * myUPS is a structure that need to be defined in _all_ the forked processes.
 * The syncronization of data into this structure is done with the shared
 * memory area so this is made reentrant by the shm mechanics.
 */
UPSINFO myUPS;
UPSINFO *core_ups = &myUPS;
char argvalue[MAXSTRING];


int le_bit   = TIOCM_LE;
int st_bit   = TIOCM_ST;
int sr_bit   = TIOCM_SR;
int dtr_bit  = TIOCM_DTR;
int rts_bit  = TIOCM_RTS;
int cts_bit  = TIOCM_CTS;
int cd_bit   = TIOCM_CD;
int rng_bit  = TIOCM_RNG;
int dsr_bit  = TIOCM_DSR;

struct termios oldtio;
struct termios newtio;

/* Forward referenced functions */
static void do_dumb_testing();
static void test1();
static void test2();
static void test3();
static void test4();
static void test5();
static void test6();
static void guess();

static void do_smart_testing();
static void smart_test1();
static void smart_calibration();
static void monitor_calibration_progress();
static void terminate_calibration(int ask);

static void strip_trailing_junk(char *cmd);
static char *get_cmd(char *prompt);
static int write_file(char *buf);
void parse_eprom_cmds(char *eprom, char locale);
void print_valid_eprom_values(char *model);


/* Static variables */
static int normal, no_cable, no_power, low_batt;
static int test1_done = 0;
static int test2_done = 0;
static int test3_done = 0;
static int test4_done = 0;
static int test5_done = 0;


int shm_OK = 0;

/*
 * Print a message, and also write it to an output file
 */
static void pmsg(char *fmt,...)
{
    char      buf[3000];
    va_list   arg_ptr;

    va_start(arg_ptr, fmt);
    vsprintf(buf, (char *) fmt, arg_ptr);
    va_end(arg_ptr);
    printf(buf);
    write_file(buf);
}

/*
 * Write output into "log" file 
 */
static int write_file(char *buf)
{
    static int out_fd = -1;
    if (out_fd == -1) {
       out_fd = open("apctest.output", O_WRONLY|O_CREAT|O_APPEND, 0644);
       if (out_fd < 0) {
          printf("Could not create apctest.output: %s\n", strerror(errno));
	  return -1;
       }
    }	   
    return write(out_fd, buf, strlen(buf));
}

/*
 * Print out current time 
 */
static void ptime()
{
   char dt[MAXSTRING];
   time_t now = time(NULL);
   strftime(dt, MAXSTRING, "%Y-%m-%d %T ", localtime(&now));
   pmsg(dt);
}


/**********************************************************************
 * the terminate function and trapping signals allows apcupsd
 * to exit and cleanly close logfiles, and reset the tty back
 * to its original settings. You may want to add this
 * to all configurations.  Of course, the file descriptors
 * must be global for this to work, I also set them to
 * NULL initially to allow terminate to determine whether
 * it should close them.
 *********************************************************************/
void terminate (int sig)
{

    restore_signals();

    if (sig != 0) {
	 ptime();
         pmsg("apctest exiting, signal %u\n", sig);
    }

    clear_files();

    if (myUPS.fd != -1) {
	/*
	 * If the ups device is opened:
	 * 1 - Close it
	 * 2 - Delete lock file
	 *
	 * -RF
	 */
	/* Note, if the tcsetattr() code is executed,
	 * it can cause the serial port line statuses to be
         * reset, which for a "dumb" UPS is the signal to
	 * kill the power. This caused premature powerkills.
	 */
	if (myUPS.mode.type > SHAREBASIC) {
		tcflush(myUPS.fd, TCIFLUSH);
		tcsetattr(myUPS.fd, TCSANOW, &oldtio);
	}
	close(myUPS.fd);
    }
    delete_lockfile(&myUPS);

    clean_threads();
    destroy_ipc(&myUPS);
    pmsg("apctest shutdown succeeded\n");
    closelog();
    _exit(0);
}

void error_cleanup(UPSINFO *ups)
{
    if (ups->fd != -1) {
	/* See important not in terminate() subroutine! */
	if (ups->mode.type > SHAREBASIC) {
	    tcflush(ups->fd, TCIFLUSH);
	    tcsetattr(ups->fd, TCSANOW, &oldtio);
	}
	close(ups->fd);
    }
    delete_lockfile(ups);
    clean_threads();
    destroy_ipc(ups);
    pmsg("apctest error shutdown completed\n");
    closelog();
    exit(1);
}

/*********************************************************************
 * subroutine error_out prints FATAL ERROR with file,
 *  line number, and the error message then cleans up 
 *  and exits. It is normally called from the Error_abort
 *  define, which inserts the file and line number.
 */
void error_out(char *file, int line, char *fmt,...)
{
    char      buf[256];
    va_list   arg_ptr;
    int       i;

    sprintf(buf, _("apctest FATAL ERROR in %s at line %d\n"), file, line);
    i = strlen(buf);
    va_start(arg_ptr, fmt);
    vsprintf((char *)&buf[i], (char *) fmt, arg_ptr);
    va_end(arg_ptr);
    fprintf(stderr, buf);
    pmsg(buf);
    error_cleanup(core_ups);	      /* finish the work */
}

/* subroutine error_exit simply prints the supplied error
 * message, cleans up, and exits
 */
void error_exit(char *fmt,...)
{
    char      buf[256];
    va_list   arg_ptr;

    va_start(arg_ptr, fmt);
    vsprintf(buf, (char *) fmt, arg_ptr);
    va_end(arg_ptr);
    pmsg(buf);
    error_cleanup(core_ups);	      /* finish the work */
}
	    

/*********************************************************************/
/*		       Main program.				     */
/*********************************************************************/

#define M_SMART 1 
#define M_DUMB	2
static int mode = M_DUMB;
static UPSINFO *ups = &myUPS;

#ifdef HAVE_CYGWIN
#undef main
#endif

int main(int argc, char *argv[]) {

	/*
	 * Default config file. If we set a config file in startup switches, it
	 * will be re-filled by parse_options()
	 */
	cfgfile = APCCONF;


#ifndef HAVE_SETPROCTITLE
        /* If there's not one in libc, then we have to use our own version
	 * which requires initialization.
	 */
	init_proctitle(argv[0]);
#endif
	init_ups_struct(&myUPS);

	/*
	 * parse_options is self messaging on errors, so we need only to exit()
	 */
	if (parse_options(argc, argv))
		exit(1);

        pmsg("\n\n");
	ptime();
        pmsg("apctest " APCUPSD_RELEASE " (" DATE ") " APCUPSD_HOST"\n");

        pmsg("Checking configuration ...\n");
	check_for_config(&myUPS, cfgfile);
	
	/* Print configuration */
	switch(myUPS.sharenet.type) {
		case DISABLE:
                        pmsg("sharenet.type = DISABLE\n");
			break;
		case SHARE:
                        pmsg("sharenet.type = SHARE\n");
			break;
		case NET:
                        pmsg("sharenet.type = NET\n");

			switch(myUPS.class.type) {
				case NO_CLASS:
                                    pmsg("class.type = NO_CLASS\n");
				    break;
				case STANDALONE:
                                    pmsg("class.type = STANDALONE\n");
				    break;
				case SHARESLAVE:
                                    pmsg("class.type = SHARESLAVE\n");
				    break;
				case SHAREMASTER:
                                    pmsg("class.type = SHAREMASTER\n");
				    break;
				case SHARENETMASTER:
                                    pmsg("class.type = SHARENETMASTER\n");
				    break;
				case NETSLAVE:
                                    pmsg("class.type = NETSLAVE\n");
				    break;
				case NETMASTER:
                                    pmsg("class.type = NETMASTER\n");
				    break;
				default:
                                    pmsg("class.type = DEFAULT\n");
				    break;

			}
#ifdef needed
                        pmsg("I cannot handle sharenet.type = NET\n");
			terminate(1);
#endif
			break;
		case SHARENET:
                        pmsg("sharenet.type = SHARENET\n");
                        pmsg("I cannot handle sharenet.type = SHARENET\n");
			terminate(1);
		default:
                        pmsg("sharenet.type = DEFAULT\n");
                        pmsg("I cannot handle sharenet.type = DEFAULT\n");
			terminate(1);
	}

	switch (myUPS.cable.type) {
	   case NO_CABLE:
              pmsg("cable.type = NO_CABLE\n");
	      break;
	   case CUSTOM_SIMPLE:
              pmsg("cable.type = CUSTOM_SIMPLE\n");
	      break;
	   case APC_940_0119A:
              pmsg("cable.type = APC_940_0119A (simple)\n");
	      break;
	   case APC_940_0127A:
              pmsg("cable.type = APC_940_0127A (simple)\n");
	      break;
	   case APC_940_0128A:
              pmsg("cable.type = APC_940_0128A (simple)\n");
	      break;

	   case APC_940_0020B:
              pmsg("cable.type = APC_940_0020B (simple)\n");
	      break;
	   case APC_940_0020C:
              pmsg("cable.type = APC_940_0020C (simple)\n");
	      break;
	   case APC_940_0023A:
              pmsg("cable.type = APC_940_0023A (simple)\n");
	      break;
	   case CUSTOM_SMART:
              pmsg("cable.type = CUSTOM_SMART\n");
	      break;
	   case APC_940_0024B:
              pmsg("cable.type = APC_940_0024B (smart)\n");
	      break;
	   case APC_940_0024C:
              pmsg("cable.type = APC_940_0024C (smart)\n");
	      break;
	   case APC_940_1524C:
              pmsg("cable.type = APC_940_1524C (smart)\n");
	      break;
	   case APC_940_0024G:
              pmsg("cable.type = APC_940_0024G (smart)\n");
	      break;
	   case APC_940_0095A:
              pmsg("cable.type = APC_940_0095A (smart)\n");
	      break;
	   case APC_940_0095B:
              pmsg("cable.type = APC_940_0095B (smart)\n");
	      break;
	   case APC_940_0095C:
              pmsg("cable.type = APC_940_0095C (smart)\n");
	      break;
	   case APC_NET:
              pmsg("cable.type = APC_NET\n");
	      break;
	   case APC_940_00XXX:
              pmsg("cable.type = APC_940_00XXX (unknown)\n");
	      break;
	   default:
              pmsg("Unknown cable type: %d\n", myUPS.cable.type);
	      break;

	}
	if (myUPS.cable.type >= CUSTOM_SMART) {
           pmsg("\nYou are using a SMART cable type, so I'm entering SMART test mode\n");
	   mode = M_SMART;
	}

	switch (myUPS.mode.type) {
	   case NO_UPS:
              pmsg("mode.type = NO_UPS\n");
	      break;
	   case BK:
              pmsg("mode.type = BK\n");
	      break;
	   case SHAREBASIC:
              pmsg("mode.type = SHAREBASIC\n");
	      break;
	   case NETUPS:
              pmsg("mode.type = NETUPS\n");
	      break;
	   case BKPRO:
              pmsg("mode.type = BKPRO\n");
	      break;
	   case VS:
              pmsg("mode.type = VS\n");
	      break;
	   case NBKPRO:
              pmsg("mode.type = NBKPRO\n");
	      break;
	   case SMART:
              pmsg("mode.type = SMART\n");
	      break;
	   case MATRIX:
              pmsg("mode.type = MATRIX\n");
	      break;
	   case SHARESMART:
              pmsg("mode.type = SHARESMART\n");
	      break;
	   default:
              pmsg("Unknown mode.type: %d\n", myUPS.mode.type);
	}
	if (myUPS.mode.type > SHAREBASIC) {
	   if (mode != M_SMART) {
              pmsg("You specified a DUMB mode cable, but a SMART UPS. I give up.\n");
	   }
	}


	delete_lockfile(&myUPS);


	switch(myUPS.sharenet.type) {
		case DISABLE:
		case SHARE:
                        pmsg("Setting up serial port ...\n");
			setup_serial(&myUPS);
			break;
		case NET:
			switch(myUPS.class.type) {
				case NO_CLASS:
				case STANDALONE:
				case SHARESLAVE:
				case SHAREMASTER:
				case SHARENETMASTER:
					break;
				case NETSLAVE:
					if (kill_ups_power)
                                                Error_abort0(_("Ignoring killpower for slave\n"));
					if (prepare_slave(&myUPS)) 
                                                Error_abort0(_("Error setting up slave\n"));
					break;
				case NETMASTER:
					setup_serial(&myUPS);
					if ((kill_ups_power == 0) && (prepare_master(&myUPS)))
                                                Error_abort0("Error setting up master\n");
					break;
				default:
                                        Error_abort1(_("NET Class Error %s\n\a"), strerror(errno));
			}
			break;
		case SHARENET:
			setup_serial(&myUPS);
			if ((kill_ups_power == 0) && (prepare_master(&myUPS)))
                                Error_abort0("Error setting up master.\n");
			break;
		default:
                        Error_abort0(_("Unknown share net type\n"));
	}

	if (kill_ups_power) {
                pmsg("apctest: bad option, I cannot do a killpower\n");
		terminate(0);
	}

	if (init_ipc(&myUPS) == FAILURE) {
                Error_abort1(_("%s: init_ipc failed.\n"), argv[0]);
	}

	/*
	 * Delete the lockfile just before fork. We will reacquire it just
	 * after.
	 */

	delete_lockfile(&myUPS);



	make_pid_file();

        pmsg("Creating serial port lock file ...\n");
	if (create_lockfile(&myUPS) == LCKERROR) {
                Error_abort1(_("failed to reacquire serial port lock file on device %s\n"), myUPS.device);
	}

	init_signals(terminate);

	if (myUPS.fd != -1) {
		if (mode == M_DUMB) {
                   pmsg("Doing prep_serial() ...\n");
		   prep_serial(&myUPS);
		}
                /* This isn't a documented option but can be used
		 * for testing dumb mode on a SmartUPS if you have
		 * the proper cable.
		 */
		if (dumb_mode_test) {
			char ans[20];
                        write(myUPS.fd, "R", 1);  /* enter dumb mode */
			*ans = 0;
			getline(ans, sizeof(ans), &myUPS);
                        pmsg("Going dumb: %s\n", ans);
			mode = M_DUMB; /* run in dumb mode */
		}
	}



	/*
	 * Now update the shared area with myUPS data.
	 */
	write_shmarea(&myUPS);
	shm_OK = 1;

	if (myUPS.fd != -1) {
	   if (mode == M_DUMB) {
	      do_dumb_testing();
	   } else {
	      do_smart_testing();
	   }

	} else {
           pmsg("apctest: there is a problem here.  We have no serial port.\n");
	}

	terminate(0);
	return -1;		      /* to keep compiler happy */
}

static void
print_bits(int bits)
{
      char buf[200];

      sprintf(buf, "IOCTL GET: %x ", bits);
      if (bits & le_bit)
         strcat(buf, "LE ");
      if (bits & st_bit)
         strcat(buf, "ST ");
      if (bits & sr_bit)
         strcat(buf, "SR ");
      if (bits & dtr_bit)
         strcat(buf, "DTR ");
      if (bits & rts_bit)
         strcat(buf, "RTS ");
      if (bits & cts_bit)
         strcat(buf, "CTS ");
      if (bits & cd_bit)
         strcat(buf, "CD ");
      if (bits & rng_bit)
         strcat(buf, "RNG ");
      if (bits & dsr_bit)
         strcat(buf, "DSR ");
      strcat(buf, "\n");
      pmsg(buf);
}

static void
do_dumb_testing()
{
   int quit = FALSE;
   char *cmd;

   pmsg("Hello, this is the apcupsd Cable Test program.\n\
This part of apctest is for testing dumb UPSes (ones that use\
signalling rather than commands.\n\
Most tests enter a loop polling every second for 10 seconds.\n");

   while (!quit) {
      pmsg( "\n\
1) Test 1 - normal mode\n\
2) Test 2 - no cable\n\
3) Test 3 - no power\n\
4) Test 4 - low battery (requires test 3 first)\n\
5) Test 5 - battery exhausted\n\
6) Test 6 - kill UPS power\n\
7) Test 7 - run tests 1 through 5\n\
8) Guess which is the appropriate cable\n\
9) Quit\n\n");

      cmd = get_cmd("Select test number: ");
      if (cmd) {
	 int item = atoi(cmd);
	 switch (item) {
	    case 1:
	       test1();
	       break;
	    case 2:
	       test2();
	       break;
	    case 3:
	       test3();
	       break;
	    case 4:
	       test4();
	       break;
	    case 5:
	       test5();
	       break;
	    case 6:
	       test6();
	       break;
	    case 7:
	       test1();
	       test2();
	       test3();
	       test4();
	       test5();
	       break;
	    case 8:
	       guess();
	       break;
	    case 9:
	       quit = TRUE;
	       break;
	    default:
               pmsg("Illegal response. Please enter 1-9\n");
	       break;
	 }
      } else {
         pmsg("Illegal response. Please enter 1-9\n");
      }
   }
   ptime();
   pmsg("End apctest.\n");
}

/*
 * Poll 10 times once per second and report any 
 * change in serial port bits.
 */
static int test_bits(int inbits)
{
   int i, nbits;
   int bits = inbits;

   for (i=0; i < 10; i++) {
      if (ioctl(myUPS.fd, TIOCMGET, &nbits) < 0) {
         pmsg("ioctl error, big problem: %s\n", strerror(errno));
	 return 0;
      }
      if (i == 0 || nbits != bits) {
	 ptime();
	 print_bits(nbits);
	 bits = nbits;
      }
      sleep(1);
   }
   return bits;
}

static void test1()
{
   pmsg("\nFor the first test, everything should be normal.\n\
The UPS should be plugged in to the power, and the serial cable\n\
should be connected to the computer.\n\n\
Please enter any character when ready to continue: ");
   fgetc(stdin);
   pmsg("\n");
 
   normal = test_bits(0);

   ptime();
   pmsg("Test 1: normal condition, completed.\n");
   test1_done = TRUE;
}

static void test2()
{
   pmsg("\nFor the second test, the UPS should be plugged in to the power, \n\
but the serial port should be DISCONNECTED from the computer.\n\n\
Please enter any character when ready to continue: ");
   fgetc(stdin);
   pmsg("\n");

   no_cable = test_bits(0);
 
   ptime();
   pmsg("Test 2: no cable, completed. \n");
   test2_done = TRUE;
}

static void test3()
{
   pmsg("\nFor the third test, the serial cable should be plugged\n\
back into the UPS, but the AC power plug to the UPS should be DISCONNECTED.\n\n\
Please enter any character when ready to continue: ");
   fgetc(stdin);
   pmsg("\n");
 
   no_power = test_bits(0);

   ptime();
   pmsg("Test 3: no power, completed.\n");
   test3_done = TRUE;
}

static void test4()
{
   int i, bits;

   if (!test3_done) {
      pmsg("We need the output of test 3 to run this test.\n\
Please run test 3 first then this test.\n");
      return;
   }

   pmsg("\nThe fourth test is the same as the third test:\n\
the serial cable should be plugged in to the UPS, but the AC power\n\
plug to the UPS should be DISCONNECTED. In addition, you should\n\
continue this test until the batteries are exhausted.\n\
If apctest detects a state change, it will stop\n\
the test. If not, hit control-C to stop the program\n\n\
PLEASE DO NOT RUN THIS TEST WITH A COMPUTER CONNECTED TO YOUR UPS!!!\n\n\
Please enter any character when ready to continue: ");
   fgetc(stdin);
   pmsg("\n");

   low_batt = no_power;

   ptime();
   pmsg("Start test 4: ");
   pmsg("\n");

   /* Spin until we get a state change */
   for (i=0; ; i++) {
      if (ioctl(myUPS.fd, TIOCMGET, &bits) < 0) {
         pmsg("ioctl error, big problem: %s\n", strerror(errno));
	 return;
      }
      if (bits != low_batt) {
	 ptime();
	 print_bits(bits);
	 low_batt = bits;
	 break;
      } else if (i == 0) {
	 ptime();
	 print_bits(bits);
      }
      sleep(1);
   }

   ptime();
   pmsg("Test 4: low battery, completed.\n");
   test4_done = TRUE;
}

static void test5()
{
   int i, bits, last_bits = 0;

   pmsg("\nThe fifth test is the same as the third test:\n\
the serial cable should be plugged in to the UPS, but the AC power\n\
plug to the UPS should be DISCONNECTED. In addition, you should\n\
continue this test until the batteries are exhausted.\n\
If apctest detects a state change, contrary to test 4, it\n\
will not stop. The idea is to see ANY changed bits just up to\n\
the very moment that the UPS powers down.\n\n\
PLEASE DO NOT RUN THIS TEST WITH A COMPUTER CONNECTED TO YOUR UPS!!!\n\n\
Please enter any character when ready to continue: ");
   fgetc(stdin);
   pmsg("\n");

   pmsg("Start test 5:\n");

   /* Spin until we get a state change */
   for (i=0; ; i++) {
      if (ioctl(myUPS.fd, TIOCMGET, &bits) < 0) {
         pmsg("ioctl error, big problem: %s\n", strerror(errno));
	 return;
      }
      if (i == 60) {
	 i = 0; 		      /* force print once a minute */
      }
      if (i == 0 || bits != last_bits) {
	 ptime();
	 print_bits(bits);
	 last_bits = bits;
      }
      sleep(1);
   }

   /* Should never get here */
   /* NOTREACHED */
   ptime();
   pmsg("Test 5: battery exhausted, completed.\n");
   test5_done = TRUE;
}

static void test6()
{
   pmsg("\nThis test will attempt to power down the UPS.\n\
The serial cable should be plugged in to the UPS, but the\n\
AC power plug to the UPS should be DISCONNECTED.\n\n\
PLEASE DO NOT RUN THIS TEST WITH A COMPUTER CONNECTED TO YOUR UPS!!!\n\n\
Please enter any character when ready to continue: ");
   fgetc(stdin);
   pmsg("\n");
   make_file(ups, PWRFAIL);
   kill_power(&myUPS);
   unlink(PWRFAIL);
   ptime();
   pmsg("Kill_power function called.\n");
}

/*
 * Make a wild guess at the cable type 
 *
 *  If I had more data on each of the cable types, this could
 *  be much improved.
 */
static void guess()
{
   int found = 0;

   if (!(test1_done && test3_done)) {
      pmsg("Test 1 and test 3 must be performed before I can make a guess.\n");
      return;
   }
   if (!(normal & (cd_bit|cts_bit)) && (no_power & cd_bit) && (low_batt & cts_bit)) {
      pmsg("This looks like a CUSTOM_SIMPLE cable\n");
      found = 1;
   }

   if (!(normal & (cd_bit|cts_bit)) && (no_power & cts_bit) && (low_batt & cd_bit)) {
      pmsg("This looks like a 940-0020A\n");                   
      found = 1;
   }

   if (!(normal & (cd_bit|sr_bit)) && (no_power & cd_bit) && (low_batt & sr_bit)) {
      pmsg("This looks like a 940-0023A cable\n");
      found = 1;
   }

   if (!(normal & (rng_bit|cd_bit)) && (no_power & rng_bit) && (low_batt & cd_bit)) {
      pmsg("This looks like a 940-0095A cable\n");
      found = 1;
   }

   if (!found) {
      pmsg("Hmmm. I don't quite know what you have. Sorry.\n"); 
   }
}

static void do_smart_testing()
{
   char *cmd;
   int quit = FALSE;

   pmsg("Hello, this is the apcupsd Cable Test program.\n\
This part of apctest is for testing Smart UPSes.\n\
Please select the function you want to perform.\n");

   while (!quit) {
      pmsg( "\n\
1) Query the UPS for all known values\n\
2) Perform a Battery Runtime Calibration\n\
3) Abort Battery Calibration\n\
4) Monitor Battery Calibration progress\n\
5) Quit\n\n");

      cmd = get_cmd("Select function number: ");
      if (cmd) {
	 int item = atoi(cmd);
	 switch (item) {
	    case 1:
	       smart_test1();
	       break;
	    case 2:
	       smart_calibration();
	       break;
	    case 3:
	       terminate_calibration(1);
	       break;
	    case 4:
	       monitor_calibration_progress();
	       break;
	    case 5:
	       quit = TRUE;
	       break;
	    default:
               pmsg("Illegal response. Please enter 1-5\n");
	       break;
	 }
      } else {
         pmsg("Illegal response. Please enter 1-5\n");
      }
   }
   ptime();
   pmsg("End apctest.\n");
}

static void smart_calibration()
{
   char *ans, cmd;
   char answer[2000];
   int stat;

   pmsg("First ensure that we have a good link and \n\
that the UPS is functionning normally.\n");
   pmsg("Simulating UPSlinkCheck ...\n");
   tcflush(ups->fd, TCIOFLUSH);
   /* Start really simply */
   cmd = 'Y';
   stat = write(ups->fd, &cmd, 1);
   if (stat < 0) {
     pmsg("Bad status from write: %s\n", strerror(errno));
   }
   stat = getline(answer, sizeof(answer), ups);
   pmsg("Wrote: Y Got: %s\n", answer);
   if (stat == FAILURE) {
      pmsg("getline failed. Apparently the link is not up.\n\
Giving up.\n");
      return;
   }
   pmsg("Attempting to use smart_poll() ...\n");
   ans = smart_poll('Y', ups);
   pmsg("Sent: Y Got: %s  ", ans);
   if (strcmp(ans, "SM") == 0) {
      pmsg("Good -- smart_poll() works!.\n\n");
   } else {
      pmsg("Not good.\nGiving up.\n");
      return;
   }
   pmsg("Checking estimated runtime ...\n");
   ans = smart_poll('j', ups);
   if (*ans >= '0' && *ans <= '9') {
      int rt = atoi(ans);
      pmsg("Current runtime is %d minutes\n", rt);
   } else {
      pmsg("Unexpected response from UPS: %s\n", ans);
      return;
   }
   pmsg("Checking for battery level ...\n");
   ans = smart_poll('f', ups);
   if (strncmp(ans, "100.0", 5) == 0) {
      pmsg("Battery level is 100.0 -- OK\n");
   } else {
      pmsg("Battery level %s insufficient to run test.\n", ans);
      return;
   }
   pmsg("\nSending Battery Calibration command. The calibration\n\
should automatically end when the battery level\n\
drops below 35-25 depending on your UPS. In any\n\
case, I will stop the calibration if it reaches\n\
20. If you wish to stop the calibration, enter a return.\n\n");

   ans = smart_poll('D', ups);
   if (*ans == '!' || strcmp(ans, "OK") == 0) {
      pmsg("UPS has initiated battery calibration.\n");
   } else {
      pmsg("Unexpected response from UPS: %s\n", ans);
      return;
   }
   monitor_calibration_progress();
}

static void terminate_calibration(int ask)
{
   char *ans, *cmd;

   if (ask) {
      pmsg("\nCAUTION! Don't use this command unless the UPS\n\
is already doing a calibration.\n");
      cmd = get_cmd("Are you sure? (yes/no): ");
      if (strcmp(cmd, "yes") != 0) {
	 return;
      }
   }
   pmsg("\nAttempting to abort calibration ...\n");
   ans = smart_poll('D', ups);  /* abort calibration */
   if (*ans == '$' || strcmp(ans, "NO") == 0) {
      pmsg("Battery Runtime Calibration terminated.\n");
      pmsg("Checking estimated runtime ...\n");
      ans = smart_poll('j', ups);
      if (*ans >= '0' && *ans <= '9') {
	 int rt = atoi(ans);
         pmsg("Updated runtime is %d\n", rt);
      } else {
         pmsg("Unexpected response from UPS: %s\n", ans);
      }
   } else {
      pmsg("Response to abort request: %s\n", ans);
   }
}


static void monitor_calibration_progress()
{
   char *ans;
   int count = 0;
   int max_count = 10;
   char period = '.';

   pmsg("Monitoring the calibration progress ...\n\
To stop the calibration, enter a return.\n");
   for ( ;; ) {
      fd_set rfds;
      struct timeval tv;
      int retval, percent;
      char cmd;

      FD_ZERO(&rfds);
      FD_SET(ups->fd, &rfds);
      FD_SET(STDIN_FILENO, &rfds);
      tv.tv_sec = 12;
      tv.tv_usec = 0;
      errno = 0;
      retval = select((ups->fd)+1, &rfds, NULL, NULL, &tv);
      switch (retval) {
      case 0:
	 write(STDOUT_FILENO, &period, 1);
	 if (++count >= max_count) {
            ans = smart_poll('f', ups);   /* Get battery charge */
	    percent = (int)strtod(ans, NULL);
            pmsg("\nBattery charge %d\n", percent);
	    if (percent > 0) {
	       if (percent <= 20) {
		  terminate_calibration(0);
		  return;
	       }
	       if (percent < 40) {
		  max_count = 3;      /* report faster */
	       }
	    }
            ans = smart_poll('j', ups);  /* Get runtime */
            if (*ans >= '0' && *ans <= '9') {
	       int rt = atoi(ans);
               pmsg("Remaining runtime is %d minutes\n", rt);
	       if (rt > 0 && rt < 4) {
		  terminate_calibration(0);
		  return;
	       }
	    }
	    count = 0;
	 }
	 continue;
      case -1:
	 if (errno == EINTR || errno == EAGAIN) {
	    continue;
	 }
         pmsg("Select error. ERR=%s\n", strerror(errno));
	 return;
      default:
	 break;
      }
      if (FD_ISSET(STDIN_FILENO, &rfds)) {
	 read(STDIN_FILENO, &cmd, 1);
	 terminate_calibration(0);
	 return;
      }
      if (FD_ISSET(ups->fd, &rfds)) {
	 read(ups->fd, &cmd, 1);
         if (cmd == '$') {
            pmsg("Battery Runtime Calibration terminated.\n");
            pmsg("Checking estimated runtime ...\n");
            ans = smart_poll('j', ups);
            if (*ans >= '0' && *ans <= '9') {
	       int rt = atoi(ans);
               pmsg("Remaining runtime is %d minutes\n", rt);
	    } else {
               pmsg("Unexpected response from UPS: %s\n", ans);
	    }
	    return;
	 }
      }
   }
}

static void smart_test1()
{
   char *ans, *p, *o, cmd;
   char answer[2000];
   char parts[2000];
   int stat, i;
#ifdef working
   char locale, locale1, locale2;
#endif

   pmsg("I am going to run through the series of queries of the UPS\n\
that are used in initializing apcupsd.\n\n");

   pmsg("Simulating UPSlinkCheck ...\n");
   tcflush(ups->fd, TCIOFLUSH);
   /* Start really simply */
   cmd = 'Y';
   stat = write(ups->fd, &cmd, 1);
   if (stat < 0) {
     pmsg("Bad status from write: %s\n", strerror(errno));
   }
   stat = getline(answer, sizeof(answer), ups);
   pmsg("Wrote: Y Got: %s\n", answer);
   if (stat == FAILURE) {
      pmsg("getline failed. Apparently the link is not up.\n\
Giving up.\n");
      return;
   }
   pmsg("Attempting to use smart_poll() ...\n");
   ans = smart_poll('Y', ups);
   pmsg("Sent: Y Got: %s  ", ans);
   if (strcmp(ans, "SM") == 0) {
      pmsg("Good -- smart_poll() works!.\n\n");
   } else {
      pmsg("Not good.\nGiving up.\n");
      return;
   }
   pmsg("Going to ask for valid commands...\n");
   cmd = 'a';
   stat = write(ups->fd, &cmd, 1);
   if (stat != 1) {
      pmsg("Bad response from write: %d %s\n", stat, strerror(errno));
   }
   *answer = 0;
   for (i=0; i < sizeof(answer); i++) {
      stat = read(ups->fd, &cmd, 1);
      if (stat < 0) {
         pmsg("Bad response from read: %s\n", strerror(errno));
      }
      if (cmd == '\n') {
	 answer[i] = 0;
	 break;
      }
      answer[i] = cmd;
   }
   /* Get protocol version */
   for (p=answer, o=parts; *p && *p != '.'; p++) {
      *o++ = *p;     
   }
   *o = 0;
   pmsg("Protocol version is: %s\n", parts);
   if (*p == '.') {
      p++;
   }
   /* Get alert characters */
   for (o=parts; *p && *p != '.'; p++) {
      if (*p < 0x20) {
         *o++ = '^';
         *o++ = *p + 'A' - 1;
      } else {
	 *o++ = *p;
      }
   }
   *o = 0;
   pmsg("Alert characters are: %s\n", parts);
   if (*p == '.') {
      p++;
   }
   /* Get command characters */
   for (o=parts; *p; p++) {
      if (*p < 0x20) {
         *o++ = '^';
         *o++ = *p + 'A' - 1;
      } else {
	 *o++ = *p;
      }
   }
   *o = 0;
   pmsg("Command characters are: %s\n", parts);
   pmsg("\nNow running through apcupsd get_UPS capabilities().\n\
NA  indicates that the feature is Not Available\n\n");

   pmsg("UPS Status: %s\n", smart_poll(ups->UPS_Cmd[CI_STATUS], ups));

   pmsg("Line quality: %s\n", smart_poll(ups->UPS_Cmd[CI_LQUAL], ups));

   pmsg("Reason for last transfer to batteries: %s\n", 
	smart_poll(ups->UPS_Cmd[CI_WHY_BATT], ups));

   pmsg("Self-Test Status: %s\n", smart_poll(ups->UPS_Cmd[CI_ST_STAT], ups));

   pmsg("Line Voltage: %s\n", smart_poll(ups->UPS_Cmd[CI_VLINE], ups));

   pmsg("Line Voltage Max: %s\n", smart_poll(ups->UPS_Cmd[CI_VMAX], ups));

   pmsg("Line Voltage Min: %s\n", smart_poll(ups->UPS_Cmd[CI_VMIN], ups));

   pmsg("Output Voltage: %s\n", smart_poll(ups->UPS_Cmd[CI_VOUT], ups));

   pmsg("Batt level percent: %s\n", smart_poll(ups->UPS_Cmd[CI_BATTLEV], ups));

   pmsg("Batt voltage: %s\n", smart_poll(ups->UPS_Cmd[CI_VBATT], ups));

   pmsg("UPS Load: %s\n", smart_poll(ups->UPS_Cmd[CI_LOAD], ups));

   pmsg("Line freq: %s\n", smart_poll(ups->UPS_Cmd[CI_FREQ], ups));

   pmsg("Runtime left: %s\n", smart_poll(ups->UPS_Cmd[CI_RUNTIM], ups));

   pmsg("UPS Internal temp: %s\n", smart_poll(ups->UPS_Cmd[CI_ITEMP], ups));

   pmsg("Dip switch settings: %s\n", smart_poll(ups->UPS_Cmd[CI_DIPSW], ups));

   pmsg("Register 1: %s\n", smart_poll(ups->UPS_Cmd[CI_REG1], ups));

   pmsg("Register 2: %s\n", smart_poll(ups->UPS_Cmd[CI_REG2], ups));

   pmsg("Register 3: %s\n", smart_poll('8', ups));

   pmsg("Sensitivity: %s\n", smart_poll(ups->UPS_Cmd[CI_SENS], ups));

   pmsg("Wakeup delay: %s\n", smart_poll(ups->UPS_Cmd[CI_DWAKE], ups));

   pmsg("Sleep delay: %s\n", smart_poll(ups->UPS_Cmd[CI_DSHUTD], ups));

   pmsg("Low transfer voltage: %s\n", smart_poll(ups->UPS_Cmd[CI_LTRANS], ups));

   pmsg("High transfer voltage: %s\n", smart_poll(ups->UPS_Cmd[CI_HTRANS], ups));

   pmsg("Batt charge for return: %s\n", smart_poll(ups->UPS_Cmd[CI_RETPCT], ups));

   pmsg("Alarm status: %s\n", smart_poll(ups->UPS_Cmd[CI_DALARM], ups));

   pmsg("Low battery shutdown level: %s\n", smart_poll(ups->UPS_Cmd[CI_DLBATT], ups));

   pmsg("UPS Name: %s\n", smart_poll(ups->UPS_Cmd[CI_IDEN], ups));

   pmsg("UPS Self test interval: %s\n", smart_poll(ups->UPS_Cmd[CI_STESTI], ups));

   pmsg("UPS manufacture date: %s\n", smart_poll(ups->UPS_Cmd[CI_MANDAT], ups));
	
   pmsg("UPS serial number: %s\n", smart_poll(ups->UPS_Cmd[CI_SERNO], ups));

   pmsg("Date battery replaced: %s\n", smart_poll(ups->UPS_Cmd[CI_BATTDAT], ups));

   pmsg("Output voltage when on batteries: %s\n", smart_poll(ups->UPS_Cmd[CI_NOMOUTV], ups)); 

   pmsg("Nominal battery voltage: %s\n", smart_poll(ups->UPS_Cmd[CI_NOMBATTV], ups)); 

   pmsg("Percent humidity: %s\n", smart_poll(ups->UPS_Cmd[CI_HUMID], ups));

   pmsg("Ambient temperature: %s\n", smart_poll(ups->UPS_Cmd[CI_ATEMP], ups));

   pmsg("Firmware revision: %s\n", smart_poll(ups->UPS_Cmd[CI_REVNO], ups));

   pmsg("Number of external batteries installed: %s\n", smart_poll(ups->UPS_Cmd[CI_EXTBATTS], ups));

   pmsg("Number of bad batteries installed: %s\n", smart_poll(ups->UPS_Cmd[CI_BADBATTS], ups));
	
   pmsg("UPS model as defined by UPS: %s\n", smart_poll(ups->UPS_Cmd[CI_UPSMODEL], ups));

   pmsg("UPS EPROM capabilities string: %s\n", (ans=smart_poll(ups->UPS_Cmd[CI_EPROM], ups)));
   pmsg("The EPROM string is %d characters long!\n", strlen(ans));

   pmsg("Hours since last self test: %s\n", smart_poll(ups->UPS_Cmd[CI_ST_TIME], ups));

#ifdef working
   pmsg("get_UPS_capabilities() simulation done. Now running it.\n\n");

   get_UPS_capabilities(&myUPS);
   fillUPS(&myUPS);

   pmsg("Analysis of EEPROM settings\n");

   if (!myUPS.UPS_Cap[CI_EPROM]) {
      pmsg("Sorry, your model does not support EPROM programming.\n");
      return;
   }
   if (myUPS.UPS_Cap[CI_REVNO])
      locale1 = *(myUPS.firmrev + strlen(myUPS.firmrev) - 1);
   else  
      locale1 = 0;
   if (myUPS.UPS_Cap[CI_UPSMODEL])
      locale2 = *(myUPS.upsmodel + strlen(myUPS.upsmodel) - 1);
   else
      locale2 = 0;
   if (locale1 == locale2 && locale1 == 0) {
      pmsg("Sorry, your model does not support EPROM programming.\n");
      return;
   }
   if (locale1 == locale2)
       locale = locale1;
   if (locale1 == 0)
       locale = locale2;
   else 
       locale = locale1;
   parse_eprom_cmds(myUPS.eprom, locale);
   print_valid_eprom_values(myUPS.mode.long_name);
#endif
       
   pmsg("\nThat is all for now.\n");
   return;
}

/* EPROM commands and their values as parsed from the
 * ^Z eprom string returned by the UPS.
 */
static struct {
 char cmd;
 char size;
 char num;
 char cmdvals[50];
} cmd[15];

/* Total number of EPROM commands */
static int ncmd = 0;

/* Table of the UPS command, the apcupsd configuration directive,
 *  and an explanation of what the command sets in the EPROM.
 */
static struct {
 char cmd;
 char *config_directive;
 char *descript;
 char type;
 int *data;
} cmd_table[] = {
  {'u', "HITRANSFER",    "Upper transfer voltage", 'i', &myUPS.hitrans},
  {'l', "LOTRANSFER",    "Lower transfer voltage", 'i', &myUPS.lotrans},
  {'e', "RETURNCHARGE",  "Return threshold", 'i', &myUPS.rtnpct},
  {'o', "OUTPUTVOLTS",   "Output voltage on batts", 'i', &myUPS.NomOutputVoltage},
  {'s', "SENSITIVITY",   "Sensitivity", 'c', (int *)myUPS.sensitivity},
  {'q', "LOWBATT",       "Low battery warning", 'i', &myUPS.dlowbatt},
  {'p', "SLEEP",         "Shutdown grace delay", 'i', &myUPS.dshutd},
  {'k', "BEEPSTATE",     "Alarm delay", 'c', (int *)myUPS.beepstate},
  {'r', "WAKEUP",        "Wakeup delay", 'i', &myUPS.dwake},
  {'E', "SELFTEST",      "Self test interval", 'c', (int *)myUPS.selftest},
  {0, NULL, NULL}	/* Last entry */
  };

void print_valid_eprom_values(char *model)
{
    int i, j, k, l;
    char *p;
    char val[10];

    pmsg("\nValid EPROM values for the %s\n\n", model);

    pmsg("%-24s %-12s  %-6s  %s\n", "           ", "Config",   "Current", "Permitted");
    pmsg("%-24s %-12s  %-6s  %s\n", "Description", "Directive","Value  ", "Values");
    pmsg("===================================================================\n");
    for (i=0; i<ncmd; i++) {
       for (j=0; cmd_table[j].cmd; j++) {
	  if (cmd[i].cmd == cmd_table[j].cmd) {
             if (cmd_table[j].type == 'c') 
                sprintf(val, "%s", (char *)cmd_table[j].data);
	     else
                sprintf(val, "%d", *cmd_table[j].data);
             pmsg("%-24s %-12s  %-6s   ", cmd_table[j].descript, 
		     cmd_table[j].config_directive, val);
	     p = cmd[i].cmdvals;
	     for (k=cmd[i].num; k; k--) {
		for (l=cmd[i].size; l; l--)
                   pmsg("%c", *p++);
                pmsg(" ");
	     }
             pmsg("\n");
	     break;
	  }
       }
    }
    pmsg("\n");
}

/*
 * Parse EPROM command string returned by a ^Z command. We
 * pull out only entries that correspond to our UPS (locale).
 */
void parse_eprom_cmds(char *eprom, char locale)
{
    char *p = eprom;
    char c, l, n, s;

    for (;;) {
       c = *p++;
       if (c == 0)
	  break;
       if (c == '#')
	  continue;
       l = *p++;		  /* get locale */
       n = *p++ - '0';            /* get number of commands */
       s = *p++ - '0';            /* get character size */
       if (l != '4' && l != locale) {  /* skip this locale */
	  p += n * s;
	  continue;
       }
       cmd[ncmd].cmd = c;	  /* store command */
       cmd[ncmd].size = s;	  /* chare length of each value */
       cmd[ncmd].num = n;	  /* number of values */
       strncpy(cmd[ncmd].cmdvals, p, n*s); /* save values */
       p += n * s;
       ncmd++;
    }
#ifdef debuggggggg
        pmsg("\n");
	for (i=0; i<ncmd; i++) 
          pmsg("cmd=%c len=%d nvals=%d vals=%s\n", cmd[i].cmd,
	     cmd[i].size, cmd[i].num, cmd[i].cmdvals);
#endif
}
    

/*
 * Gen next input command from the terminal
 */
static char *get_cmd(char *prompt)
{
   static char cmd[1000];

   pmsg(prompt);
   cmd[0] = 0;
   if (fgets(cmd, sizeof(cmd), stdin) == NULL)
      return NULL;
   write_file(cmd);
   pmsg("\n");
   strip_trailing_junk(cmd);
   return cmd;
}

/* Strip any trailing junk from the command */
static void strip_trailing_junk(char *cmd)
{
   char *p;
   p = cmd + strlen(cmd) - 1;

   /* strip trailing junk from command */
   while ((p >= cmd) && (*p == '\n' || *p == '\r' || *p == ' '))
      *p-- = 0;
}