-
-
Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathapcsmart.c
2137 lines (1759 loc) · 49.6 KB
/
apcsmart.c
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
/*
* apcsmart.c - driver for APC smart protocol units (originally "newapc")
*
* Copyright (C) 1999 Russell Kroll <[email protected]>
* (C) 2000 Nigel Metheringham <[email protected]>
* (C) 2011+ Michal Soltys <[email protected]>
*
* 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 <sys/types.h>
#include <sys/file.h>
#include <regex.h>
#include <ctype.h>
#include <strings.h> /* strcasecmp() */
#include "main.h"
#include "serial.h"
#include "timehead.h"
#include "apcsmart.h"
#include "apcsmart_tabs.h"
/* driver description structure */
upsdrv_info_t upsdrv_info = {
DRIVER_NAME,
DRIVER_VERSION,
"Russell Kroll <[email protected]>\n"
"Nigel Metheringham <[email protected]>\n"
"Michal Soltys <[email protected]>",
DRV_STABLE,
{ &apc_tab_info, NULL }
};
static int ups_status = 0;
/* some forwards */
static int sdcmd_S(const void *);
static int sdcmd_AT(const void *);
static int sdcmd_K(const void *);
static int sdcmd_Z(const void *);
static int sdcmd_CS(const void *);
/*
* following table *must* match order defined in the man page, namely:
* 0:: soft hibernate (*S*)
* 1:: hard hibernate (*@*)
* 2:: delayed poweroff (*K*)
* 3:: instant poweroff (*Z*)
* 4:: "force OB hack" (*CS*)
*/
static int (*sdlist[])(const void *) = {
sdcmd_S,
sdcmd_AT,
sdcmd_K,
sdcmd_Z,
sdcmd_CS,
};
#define SDIDX_AT 1
/*
* note: both lookup functions MUST be used after variable detection is
* completed - that is after deprecate_vars() call; the general reason for this
* is 1:n and n:1 nut <-> apc mappings, which are not determined prior to the
* detection
*/
static apc_vartab_t *vt_lookup_char(char cmdchar)
{
int i;
for (i = 0; apc_vartab[i].name != NULL; i++)
if ((apc_vartab[i].flags & APC_PRESENT) &&
apc_vartab[i].cmd == cmdchar)
return &apc_vartab[i];
return NULL;
}
static apc_vartab_t *vt_lookup_name(const char *var)
{
int i;
for (i = 0; apc_vartab[i].name != NULL; i++)
if ((apc_vartab[i].flags & APC_PRESENT) &&
!strcasecmp(apc_vartab[i].name, var))
return &apc_vartab[i];
return NULL;
}
static const char *prtchr(char x)
{
static size_t curr = 24;
static char info[32];
curr = (curr + 8) & 0x1F;
snprintf(info + curr, 8, isprint(x) ? "%c" : "0x%02x", x);
return info + curr;
}
static int rexhlp(const char *rex, const char *val)
{
static const char *empty = "";
int ret;
regex_t mbuf;
if (!rex || !*rex)
return 1;
if (!val)
val = empty;
regcomp(&mbuf, rex, REG_EXTENDED|REG_NOSUB);
ret = regexec(&mbuf, val, 0, 0, 0);
regfree(&mbuf);
return !ret;
}
/* convert APC formatting to NUT formatting */
/* TODO: handle errors better */
static const char *convert_data(apc_vartab_t *vt, const char *upsval)
{
static char temp[APC_LBUF];
int tval;
/* this should never happen */
if (strlen(upsval) >= sizeof(temp)) {
logx(LOG_CRIT, "the length of [%s] is too big", vt->name);
memcpy(temp, upsval, sizeof(temp) - 1);
temp[sizeof(temp) - 1] = '\0';
return temp;
}
switch (vt->flags & APC_F_MASK) {
case APC_F_PERCENT:
case APC_F_VOLT:
case APC_F_AMP:
case APC_F_CELSIUS:
case APC_F_HEX:
case APC_F_DEC:
case APC_F_SECONDS:
case APC_F_LEAVE:
/* no conversion for any of these */
strcpy(temp, upsval);
return temp;
case APC_F_HOURS:
/* convert to seconds */
tval = 60 * 60 * strtol(upsval, NULL, 10);
snprintf(temp, sizeof(temp), "%d", tval);
return temp;
case APC_F_MINUTES:
/* Convert to seconds - NUT standard time measurement */
tval = 60 * strtol(upsval, NULL, 10);
/* Ignore errors - there's not much we can do */
snprintf(temp, sizeof(temp), "%d", tval);
return temp;
case APC_F_REASON:
switch (upsval[0]) {
case 'R': return "unacceptable utility voltage rate of change";
case 'H': return "high utility voltage";
case 'L': return "low utility voltage";
case 'T': return "line voltage notch or spike";
case 'O': return "no transfers yet since turnon";
case 'S': return "simulated power failure or UPS test";
default:
strcpy(temp, upsval);
return temp;
}
}
/* this should never happen */
logx(LOG_CRIT, "unable to convert [%s]", vt->name);
strcpy(temp, upsval);
return temp;
}
/* report differences if tcsetattr != tcgetattr, return otherwise */
/*
* Aix compatible names
*/
#if defined(VWERSE) && !defined(VWERASE)
#define VWERASE VWERSE
#endif /* VWERSE && !VWERASE */
#if defined(VDISCRD) && !defined(VDISCARD)
#define VDISCARD VDISCRD
#endif /* VDISCRD && !VDISCARD */
static void apc_ser_diff(struct termios *tioset, struct termios *tioget)
{
size_t i;
const char dir[] = { 's', 'g' };
struct termios *tio[] = { tioset, tioget };
struct cchar {
const char *name;
unsigned int sub;
};
const struct cchar cchars1[] = {
#ifdef VDISCARD
{ "discard", VDISCARD },
#endif
#ifdef VDSUSP
{ "dsusp", VDSUSP },
#endif
{ "eof", VEOF },
{ "eol", VEOL },
{ "eol2", VEOL2 },
{ "erase", VERASE },
#ifdef VINTR
{ "intr", VINTR },
#endif
{ "kill", VKILL },
{ "lnext", VLNEXT },
{ "min", VMIN },
{ "quit", VQUIT },
#ifdef VREPRINT
{ "reprint", VREPRINT },
#endif
{ "start", VSTART },
#ifdef VSTATUS
{ "status", VSTATUS },
#endif
{ "stop", VSTOP },
{ "susp", VSUSP },
{ "time", VTIME },
{ "werase", VWERASE },
{ NULL },
}, *cp;
/* clear status flags so that they don't affect our binary compare */
#if defined(PENDIN) || defined(FLUSHO)
for (i = 0; i < sizeof(tio)/sizeof(tio[0]); i++) {
#ifdef PENDIN
tio[i]->c_lflag &= ~PENDIN;
#endif
#ifdef FLUSHO
tio[i]->c_lflag &= ~FLUSHO;
#endif
}
#endif /* defined(PENDIN) || defined(FLUSHO) */
if (!memcmp(tio[0], tio[1], sizeof(*tio[0])))
return;
upslogx(LOG_NOTICE, "%s: device reports different attributes than requested", device_path);
/*
* According to the manual the most common problem is mis-matched
* combinations of input and output baud rates. If the combination is
* not supported then neither are changed. This should not be a
* problem here since we set them both to the same extremely common
* rate of 2400.
*/
for (i = 0; i < sizeof(tio)/sizeof(tio[0]); i++) {
upsdebugx(1, "tc%cetattr(): gfmt1:cflag=%x:iflag=%x:lflag=%x:oflag=%x:", dir[i],
(unsigned int) tio[i]->c_cflag, (unsigned int) tio[i]->c_iflag,
(unsigned int) tio[i]->c_lflag, (unsigned int) tio[i]->c_oflag);
for (cp = cchars1; cp->name; ++cp)
upsdebugx(1, "\t%s=%x:", cp->name, tio[i]->c_cc[cp->sub]);
upsdebugx(1, "\tispeed=%d:ospeed=%d", (int) cfgetispeed(tio[i]), (int) cfgetospeed(tio[i]));
}
}
static void apc_ser_set(void)
{
struct termios tio, tio_chk;
char *val;
/*
* this must be called before the rest, as ser_set_speed() performs
* early initialization of the port, apart from changing speed
*/
ser_set_speed(upsfd, device_path, B2400);
val = getval("cable");
if (val && !strcasecmp(val, ALT_CABLE_1)) {
if (ser_set_dtr(upsfd, 1) == -1)
fatx("ser_set_dtr(%s) failed", device_path);
if (ser_set_rts(upsfd, 0) == -1)
fatx("ser_set_rts(%s) failed", device_path);
}
/*
* that's all if we want simple non canonical mode; this is meant as a
* compatibility measure for windows systems and perhaps some
* problematic serial cards/converters
*/
if ((val = getval("ttymode")) && !strcmp(val, "raw"))
return;
memset(&tio, 0, sizeof(tio));
errno = 0;
if (tcgetattr(upsfd, &tio))
fate("tcgetattr(%s)", device_path);
/* set port mode: common stuff, canonical processing */
tio.c_cflag |= (CS8 | CLOCAL | CREAD);
tio.c_lflag |= ICANON;
#ifdef NOKERNINFO
tio.c_lflag |= NOKERNINFO;
#endif
tio.c_lflag &= ~(ISIG | IEXTEN);
tio.c_iflag |= (IGNCR | IGNPAR);
tio.c_iflag &= ~(IXON | IXOFF);
tio.c_cc[VEOL] = '*'; /* specially handled in apc_read() */
#ifdef _POSIX_VDISABLE
tio.c_cc[VERASE] = _POSIX_VDISABLE;
tio.c_cc[VKILL] = _POSIX_VDISABLE;
tio.c_cc[VEOF] = _POSIX_VDISABLE;
tio.c_cc[VEOL2] = _POSIX_VDISABLE;
#endif
if (tcflush(upsfd, TCIOFLUSH))
fate("tcflush(%s)", device_path);
/*
* warn:
* Note, that tcsetattr() returns success if /any/ of the requested
* changes could be successfully carried out. Thus the more complicated
* test.
*/
if (tcsetattr(upsfd, TCSANOW, &tio))
fate("tcsetattr(%s)", device_path);
memset(&tio_chk, 0, sizeof(tio_chk));
if (tcgetattr(upsfd, &tio_chk))
fate("tcgetattr(%s)", device_path);
apc_ser_diff(&tio, &tio_chk);
}
static void ups_status_set(void)
{
status_init();
if (ups_status & APC_STAT_CAL)
status_set("CAL"); /* calibration */
if (ups_status & APC_STAT_TRIM)
status_set("TRIM"); /* SmartTrim */
if (ups_status & APC_STAT_BOOST)
status_set("BOOST"); /* SmartBoost */
if (ups_status & APC_STAT_OL)
status_set("OL"); /* on line */
if (ups_status & APC_STAT_OB)
status_set("OB"); /* on battery */
if (ups_status & APC_STAT_OVER)
status_set("OVER"); /* overload */
if (ups_status & APC_STAT_LB)
status_set("LB"); /* low battery */
if (ups_status & APC_STAT_RB)
status_set("RB"); /* replace batt */
if (ups_status == 0)
status_set("OFF");
status_commit();
}
static void alert_handler(char ch)
{
switch (ch) {
case '!': /* clear OL, set OB */
debx(1, "OB");
ups_status &= ~APC_STAT_OL;
ups_status |= APC_STAT_OB;
break;
case '$': /* clear OB, set OL */
debx(1, "OL");
ups_status &= ~APC_STAT_OB;
ups_status |= APC_STAT_OL;
break;
case '%': /* set LB */
debx(1, "LB");
ups_status |= APC_STAT_LB;
break;
case '+': /* clear LB */
debx(1, "not LB");
ups_status &= ~APC_STAT_LB;
break;
case '#': /* set RB */
debx(1, "RB");
ups_status |= APC_STAT_RB;
break;
case '?': /* set OVER */
debx(1, "OVER");
ups_status |= APC_STAT_OVER;
break;
case '=': /* clear OVER */
debx(1, "not OVER");
ups_status &= ~APC_STAT_OVER;
break;
default:
debx(1, "got 0x%02x (unhandled)", ch);
break;
}
ups_status_set();
}
/*
* we need a tiny bit different processing due to '*' and canonical mode; the
* function is subtly different from generic ser_get_line_alert()
*/
#define apc_read(b, l, f) apc_read_i(b, l, f, __func__, __LINE__)
static int apc_read_i(char *buf, size_t buflen, int flags, const char *fn, unsigned int ln)
{
const char *iset = IGN_CHARS, *aset = "";
size_t count = 0;
int i, ret, sec = 3, usec = 0;
char temp[APC_LBUF];
if (upsfd == -1)
return 0;
if (flags & SER_D0) {
sec = 0; usec = 0;
}
if (flags & SER_DX) {
sec = 0; usec = 200000;
}
if (flags & SER_D1) {
sec = 1; usec = 500000;
}
if (flags & SER_D3) {
sec = 3; usec = 0;
}
if (flags & SER_AA) {
iset = IGN_AACHARS;
aset = ALERT_CHARS;
}
if (flags & SER_CC) {
iset = IGN_CCCHARS;
aset = "";
sec = 6; usec = 0;
}
if (flags & SER_CS) {
iset = IGN_CSCHARS;
aset = "";
sec = 6; usec = 0;
}
memset(buf, '\0', buflen);
while (count < buflen - 1) {
errno = 0;
ret = select_read(upsfd, temp, sizeof(temp), sec, usec);
/* partial timeout (non-canon only paranoid check) */
if (ret == 0 && count) {
ser_comm_fail("serial port partial timeout: %u(%s)", ln, fn);
return -1;
}
/* error or no timeout allowed */
if (ret < 0 || (ret == 0 && !(flags & SER_TO))) {
if (ret)
ser_comm_fail("serial port read error: %u(%s): %s", ln, fn, strerror(errno));
else
ser_comm_fail("serial port read timeout: %u(%s)", ln, fn);
return ret;
}
/* ok, timeout is acceptable */
if (ret == 0 && (flags & SER_TO)) {
/*
* but it doesn't imply ser_comm_good
*
* for example we might be in comm_fail condition,
* trying to "nudge" the UPS with some command
* obviously expecting timeout if the comm is still
* lost. This would result with filling logs with
* confusing comm lost/comm re-established pairs due to
* successful serial writes
*/
return 0;
}
/* parse input */
for (i = 0; i < ret; i++) {
/* overflow read */
if (count == buflen - 1) {
ser_comm_fail("serial port read overflow: %u(%s)", ln, fn);
tcflush(upsfd, TCIFLUSH);
return -1;
}
/* standard "line received" condition */
if (temp[i] == ENDCHAR) {
ser_comm_good();
return count;
}
/*
* '*' is set as a secondary EOL; convert to 'OK' only as a
* reply to shutdown command in sdok(); otherwise next
* select_read() will continue normally
*/
if ((flags & SER_HA) && temp[i] == '*') {
/*
* a bit paranoid, but remember '*' is not real EOL;
* there could be some firmware in existence, that
* would send both string: 'OK\n' and alert: '*'.
* Just in case, try to flush the input with small 1 sec.
* timeout
*/
memset(buf, '\0', buflen);
errno = 0;
ret = select_read(upsfd, temp, sizeof(temp), 1, 0);
if (ret < 0) {
ser_comm_fail("serial port read error: %u(%s): %s", ln, fn, strerror(errno));
return ret;
}
buf[0] = 'O';
buf[1] = 'K';
ser_comm_good();
return 2;
}
/* ignore set */
if (strchr(iset, temp[i]) || temp[i] == '*') {
continue;
}
/* alert set */
if (strchr(aset, temp[i])) {
alert_handler(temp[i]);
continue;
}
buf[count++] = temp[i];
}
}
ser_comm_good();
return count;
}
#define apc_write(code) apc_write_i(code, __func__, __LINE__)
static int apc_write_i(unsigned char code, const char *fn, unsigned int ln)
{
int ret;
errno = 0;
if (upsfd == -1)
return 0;
ret = ser_send_char(upsfd, code);
/*
* Formally any write() sould never return 0, if the count != 0. For
* the sake of handling any obscure nonsense, we consider such return
* as a failure - thus <= condition; either way, LE is pretty hard
* condition hardly ever happening;
*/
if (ret <= 0)
ser_comm_fail("serial port write error: %u(%s): %s", ln, fn, strerror(errno));
return ret;
}
/*
* We have to watch out for NA, here;
* This is generally safe, as otherwise we will just timeout. The reason we do
* it, is that under certain conditions an ups might respond with NA for
* something it would normally handle (e.g. calling @ while being in powered
* off or hibernated state. If we keep sending the "arguments" after getting
* NA, they will be interpreted as commands, which is quite a bug :)
* Furthermore later flushes might not work properly, if the reply to those
* commands are generated with some delay.
*
* We also set errno to something usable, so outside upslog calls don't output
* confusing "success".
*/
#define apc_write_long(code) apc_write_long_i(code, __func__, __LINE__)
static int apc_write_long_i(const char *code, const char *fn, unsigned int ln)
{
char temp[APC_LBUF];
int ret;
ret = apc_write_i(*code, fn, ln);
if (ret != 1)
return ret;
/* peek for the answer - anything at this point is failure */
ret = apc_read(temp, sizeof(temp), SER_DX|SER_TO);
if (ret) {
errno = ECANCELED;
return -1;
}
ret = ser_send_pace(upsfd, 50000, "%s", code + 1);
if (ret >= 0)
ret++;
/* see remark in plain apc_write() */
if (ret != (int)strlen(code))
ser_comm_fail("serial port write error: %u(%s): %s", ln, fn, strerror(errno));
return ret;
}
#define apc_write_rep(code) apc_write_rep_i(code, __func__, __LINE__)
static int apc_write_rep_i(unsigned char code, const char *fn, unsigned int ln)
{
char temp[APC_LBUF];
int ret;
ret = apc_write_i(code, fn, ln);
if (ret != 1)
return ret;
/* peek for the answer - anything at this point is failure */
ret = apc_read(temp, sizeof(temp), SER_DX|SER_TO);
if (ret) {
errno = ECANCELED;
return -1;
}
usleep(1300000);
ret = apc_write_i(code, fn, ln);
if (ret >= 0)
ret++;
return ret;
}
/* all flags other than SER_AA are ignored */
static void apc_flush(int flags)
{
char temp[APC_LBUF];
if (flags & SER_AA) {
tcflush(upsfd, TCOFLUSH);
/* TODO */
while(apc_read(temp, sizeof(temp), SER_D0|SER_TO|SER_AA) > 0);
} else {
tcflush(upsfd, TCIOFLUSH);
/* tcflush(upsfd, TCIFLUSH); */
/* while(apc_read(temp, sizeof(temp), SER_D0|SER_TO)); */
}
}
/* apc specific wrappers around set/del info - to handle "packed" variables */
void apc_dstate_delinfo(apc_vartab_t *vt, int skip)
{
char name[vt->nlen0], *nidx;
int c;
/* standard not packed var */
if (!(vt->flags & APC_PACK)) {
dstate_delinfo(vt->name);
return;
}
strcpy(name, vt->name);
nidx = strstr(name,".0.") + 1;
for (c = skip; c < vt->cnt; c++) {
*nidx = (char)('1' + c);
dstate_delinfo(name);
}
vt->cnt = 0;
}
void apc_dstate_setinfo(apc_vartab_t *vt, const char *upsval)
{
char name[vt->nlen0], *nidx;
char temp[strlen(upsval) + 1], *vidx[APC_PACK_MAX], *com, *curr;
int c;
/* standard not packed var */
if (!(vt->flags & APC_PACK)) {
dstate_setinfo(vt->name, "%s", convert_data(vt, upsval));
return;
}
/* we have to set proper name for dstate_setinfo() calls */
strcpy(name, vt->name);
nidx = strstr(name,".0.") + 1;
/* split the value string */
strcpy(temp, upsval);
curr = temp;
c = 0;
do {
vidx[c] = curr;
com = strchr(curr, ',');
if (com) {
curr = com + 1;
*com = '\0';
}
} while(++c < APC_PACK_MAX && com);
/*
* unlikely, but keep things tidy - remove leftover values, if
* subsequent read returns less
*/
if (vt->cnt > c)
apc_dstate_delinfo(vt, c);
/* unlikely - warn user if we have more than APC_PACK_MAX fields */
if (c == APC_PACK_MAX && com)
upslogx(LOG_WARNING,
"packed variable %s [%s] longer than %d fields,\n"
"ignoring remaining fields",
vt->name, prtchr(vt->cmd), c);
vt->cnt = c;
while (c-- > 0) {
*nidx = (char)('1' + c);
if (*vidx[c])
dstate_setinfo(name, "%s", convert_data(vt, vidx[c]));
else
dstate_setinfo(name, "N/A");
}
}
static const char *preread_data(apc_vartab_t *vt)
{
int ret;
static char temp[APC_LBUF];
debx(1, "%s [%s]", vt->name, prtchr(vt->cmd));
apc_flush(0);
ret = apc_write(vt->cmd);
if (ret != 1)
return 0;
ret = apc_read(temp, sizeof(temp), SER_TO);
if (ret < 1 || !strcmp(temp, "NA")) {
if (ret >= 0)
logx(LOG_ERR, "%s [%s] timed out or not supported", vt->name, prtchr(vt->cmd));
return 0;
}
return temp;
}
static int poll_data(apc_vartab_t *vt)
{
char temp[APC_LBUF];
if (!(vt->flags & APC_PRESENT))
return 1;
debx(1, "%s [%s]", vt->name, prtchr(vt->cmd));
apc_flush(SER_AA);
if (apc_write(vt->cmd) != 1)
return 0;
if (apc_read(temp, sizeof(temp), SER_AA) < 1)
return 0;
/* automagically no longer supported by the hardware somehow */
if (!strcmp(temp, "NA")) {
logx(LOG_WARNING, "verified variable %s [%s] returned NA, removing", vt->name, prtchr(vt->cmd));
vt->flags &= ~APC_PRESENT;
apc_dstate_delinfo(vt, 0);
} else
apc_dstate_setinfo(vt, temp);
return 1;
}
static int update_status(void)
{
int ret;
char buf[APC_LBUF];
debx(1, "[%s]", prtchr(APC_STATUS));
apc_flush(SER_AA);
if (apc_write(APC_STATUS) != 1)
return 0;
ret = apc_read(buf, sizeof(buf), SER_AA);
if ((ret < 1) || (!strcmp(buf, "NA"))) {
if (ret >= 0)
logx(LOG_WARNING, "failed");
return 0;
}
ups_status = strtol(buf, 0, 16) & 0xff;
ups_status_set();
return 1;
}
/*
* two informative functions, to not redo the same thing in few places
*/
static inline void confirm_cv(unsigned char cmd, const char *tag, const char *name)
{
upsdebugx(1, "%s [%s] - %s supported", name, prtchr(cmd), tag);
}
static inline void warn_cv(unsigned char cmd, const char *tag, const char *name)
{
if (tag && name)
upslogx(LOG_WARNING, "%s [%s] - %s invalid", name, prtchr(cmd), tag);
else
upslogx(LOG_WARNING, "[%s] unrecognized", prtchr(cmd));
}
static void var_string_setup(apc_vartab_t *vt)
{
/*
* handle special data for our two strings; note - STRING variables
* cannot be PACK at the same time
*/
if (vt->flags & APC_STRING) {
dstate_setflags(vt->name, ST_FLAG_RW | ST_FLAG_STRING);
dstate_setaux(vt->name, APC_STRLEN);
vt->flags |= APC_RW;
}
}
static int var_verify(apc_vartab_t *vt)
{
const char *temp;
if (vt->flags & APC_MULTI) {
/* APC_MULTI are handled by deprecate_vars() */
vt->flags |= APC_PRESENT;
return -1;
}
temp = preread_data(vt);
/* no conversion here, validator should operate on raw values */
if (!temp || !rexhlp(vt->regex, temp)) {
warn_cv(vt->cmd, "variable", vt->name);
return 0;
}
vt->flags |= APC_PRESENT;
apc_dstate_setinfo(vt, temp);
var_string_setup(vt);
confirm_cv(vt->cmd, "variable", vt->name);
return 1;
}
/*
* This function iterates over vartab, deprecating nut<->apc 1:n and n:1
* variables. We prefer earliest present variable. All the other ones must be
* marked as not present (which implies deprecation).
* This pass is requried after completion of all protocol_verify() and/or
* legacy_verify() calls.
*/
static void deprecate_vars(void)
{
int i, j;
const char *temp;
apc_vartab_t *vt, *vtn;
for (i = 0; apc_vartab[i].name != NULL; i++) {
vt = &apc_vartab[i];
if (!(vt->flags & APC_MULTI) || !(vt->flags & APC_PRESENT)) {
/*
* a) not interesting, or
* b) not marked as present earlier, or already handled
*/
continue;
}
/* pre-read data, we have to verify it */
temp = preread_data(vt);
/* no conversion here, validator should operate on raw values */
if (!temp || !rexhlp(vt->regex, temp)) {
vt->flags &= ~APC_PRESENT;
warn_cv(vt->cmd, "variable combination", vt->name);
continue;
}
/* multi & present, deprecate all the remaining ones */
for (j = i + 1; apc_vartab[j].name != NULL; j++) {
vtn = &apc_vartab[j];
if (strcmp(vtn->name, vt->name) && vtn->cmd != vt->cmd)
continue;
vtn->flags &= ~APC_PRESENT;
}
apc_dstate_setinfo(vt, temp);
var_string_setup(vt);
confirm_cv(vt->cmd, "variable combination", vt->name);
}
}
static void apc_getcaps(int qco)
{
const char *ptr, *entptr;
char upsloc, temp[APC_LBUF], cmd, loc, etmp[APC_SBUF], *endtemp;
int nument, entlen, i, matrix, ret, valid;
apc_vartab_t *vt;
/*
* If we can do caps, then we need the Firmware revision which has the
* locale descriptor as the last character (ugh); this is valid for
* both 'V' and 'b' commands.
*/
ptr = dstate_getinfo("ups.firmware");
if (ptr)
upsloc = ptr[strlen(ptr) - 1];
else
upsloc = 0;
/* get capability string */
apc_flush(0);
if (apc_write(APC_CAPS) != 1)
return;
/*
* note - apc_read() needs larger timeout grace (not a problem w.r.t.
* to nut's timing, as it's done only during setup) and different
* ignore set due to certain characters like '#' being received
*/
ret = apc_read(temp, sizeof(temp), SER_CC|SER_TO);
if ((ret < 1) || (!strcmp(temp, "NA"))) {
/*
* Early Smart-UPS not as smart as the later ones ...
* this should never happen on properly functioning hardware -
* as capability support was reported earlier
*/
if (ret >= 0)
upslogx(LOG_WARNING, "APC cannot do capabilities but said it could !");
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] != '#') {
upslogx(LOG_WARNING, "unknown capability start char [%c] !", temp[0]);
upsdebugx(1, "please report this caps string: %s", temp);
return;
}
if (temp[1] == '#') { /* Matrix-UPS */
ptr = &temp[0];
matrix = 1;
} 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) {
/* if we expected this, just ignore it */
if (qco)
return;
fatalx(EXIT_FAILURE, "capability string has overflowed, please report this error !");
}
cmd = ptr[0];
loc = ptr[1];
nument = ptr[2] - 48;
entlen = ptr[3] - 48;
entptr = &ptr[4];
vt = vt_lookup_char(cmd);
valid = vt && ((loc == upsloc) || (loc == '4')) && !(vt->flags & APC_PACK);
/* mark this as writable */
if (valid) {