File: powerflute.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 (771 lines) | stat: -rw-r--r-- 16,317 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
/*
 *  powerflute.c -- ncurses interface to apcupsd
 *
 *  Copyright (C) 1998-2000 Riccardo Facchetti <riccardo@master.oasi.gpa.it>
 *
 *  apcupsd.c	 -- Simple Daemon to catch power failure signals from a
 *		    BackUPS, BackUPS Pro, or SmartUPS (from APCC).
 *		 -- Now SmartMode support for SmartUPS and BackUPS Pro.
 *
 *  Copyright (C) 1996-99 Andre M. Hedrick <andre@suse.com>
 *  All rights reserved.
 *
 */

/*
 *		       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.
 *
 */

/*
 *  IN NO EVENT SHALL ANY AND ALL PERSONS INVOLVED IN THE DEVELOPMENT OF THIS
 *  PACKAGE, NOW REFERRED TO AS "APCUPSD-Team" BE LIABLE TO ANY PARTY FOR
 *  DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
 *  OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF ANY OR ALL
 *  OF THE "APCUPSD-Team" HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *  THE "APCUPSD-Team" SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
 *  BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 *  FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 *  ON AN "AS IS" BASIS, AND THE "APCUPSD-Team" HAS NO OBLIGATION TO PROVIDE
 *  MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 *  THE "APCUPSD-Team" HAS ABSOLUTELY NO CONNECTION WITH THE COMPANY
 *  AMERICAN POWER CONVERSION, "APCC".  THE "APCUPSD-Team" DID NOT AND
 *  HAS NOT SIGNED ANY NON-DISCLOSURE AGREEMENTS WITH "APCC".  ANY AND ALL
 *  OF THE LOOK-A-LIKE ( UPSlink(tm) Language ) WAS DERIVED FROM THE
 *  SOURCES LISTED BELOW.
 *
 */

/*
 *  Contributed by Facchetti Riccardo <riccardo@master.oasi.gpa.it>
 */

#include "apc.h"
#ifdef HAVE_POWERFLUTE

#ifdef HAVE_MENU_H
# include <curses.h>
# include <panel.h>
# include <menu.h>
#else
# ifdef HAVE_NCURSES_MENU_H
#  include <ncurses/curses.h>
#  include <ncurses/panel.h>
#  include <ncurses/menu.h>
# else
#  error You must have ncurses installed to use powerflute.
# endif /* HAVE_NCURSES_MENU_H */
#endif /* HAVE_MENU_H */

#include <curses.h>

#define TIMER_POWERFLUTE	5
#define RESTORE_BUFFER		3

extern char *net_errmsg;

/*
 * This is needed for restart ncurses and all the circus.
 * ncurses or something other seems to have a bug that prevent it to
 * refresh correctly the screen when a wall message is received.
 */
jmp_buf env;

/*
 * Buffer to save the last 8 lines of mesgwin.
 */
char mesgbuf[8][1024];

/*
 * Menubar window and panel
 */
WINDOW *menuwin;
PANEL *menupan;
/*
 * Status window and panel
 */
WINDOW *statwin;
PANEL *statpan;
/*
 * Monitoring window and panel
 */
WINDOW *moniwin;
PANEL *monipan;
/*
 * Message window and panel
 */
WINDOW *mesgwin;
PANEL *mesgpan;

MENU *mu = NULL;
WINDOW *mw = NULL;
WINDOW *dmw = NULL;
PANEL *mpan;

/*
 * UPS structure.
 */
UPSINFO myUPS;
UPSINFO *ups = &myUPS;
char argvalue[MAXSTRING];

/* Default values for contacting daemon */
static char *host = "localhost";
static int port = NISPORT;


/*
 * In a non-shared memory environment, we use the network
 *  to get a raw upsinfo buffer.  This code does not support
 *  mixing machines of different types.
 */
static void get_raw_upsinfo(UPSINFO *ups, char *host, int port)
{
#ifdef HAVE_PTHREADS
    int sockfd, n;

    if ((sockfd = net_open(host, NULL, port)) < 0) {
       Error_abort0(net_errmsg);
    }
    net_send(sockfd, "rawupsinfo", 10);
    if ((n = net_recv(sockfd, (char *)ups, sizeof(UPSINFO))) != sizeof(UPSINFO)) {
       Error_abort2("net_recv of UPSINFO returned %d bytes, wanted %d\n",
	  n, sizeof(UPSINFO));
    }
    net_close(sockfd);

#endif
}


int closing_curses = 0;

extern void close_curses(void);
extern void write_mesg(char *fmt, ...);

void load_events(void) {
	FILE *fp;
	int count=0;
	char buffer[1024];

        fp = fopen(myUPS.eventfile, "r");

	if (fp == NULL)
		return;

	/*
	 * Count the lines in stat file.
	 */
	while(fgets(buffer, 1024, fp) != NULL)
		count++;

	rewind(fp);

	/*
	 * Skip lines not needed.
	 */
	while(count > 9) {
		fgets(buffer, 1024, fp);
		count--;
	}

	/*
	 * Output last 9 (or less if file is less) lines.
	 */
	while(fgets(buffer, 1024, fp) != NULL) {
                buffer[strlen(buffer)-1] = '\0';
                write_mesg("%s", buffer);
	}

	fclose(fp);
}


void init_timer(int timer, void (*fnhandler)(int)) {
	signal(SIGALRM, fnhandler);
	alarm(timer);
}

char *xlate_history(char code) {
	switch (code) {
                case 'O':
                        return "Power Up";
			break;
                case 'S':
                        return "Self Test";
			break;
                case 'L':
                        return "Line Voltage Decrease";
			break;
                case 'H':
                        return "Line Voltage Increase";
			break;
                case 'T':
                        return "Power Failure";
			break;
		default :
			/*
			 * XXX
			 *
                         * The value of the 'G' query from UPS is unknown
			 * and need to be investigated. We should log to
			 * syslog the value of code.
			 */
                        return "Unknown Event (see syslog)";
			break;
	}
}

void restart_curses(void) {
	close_curses();
	longjmp(env, RESTORE_BUFFER);
}

void update_all(void) {
	if (!closing_curses) {
		wborder(menuwin,0,0,0,0,0,0,0,0);
		wborder(statwin,0,0,0,0,0,0,0,0);
		wborder(moniwin,0,0,0,0,0,0,0,0);
		wborder(mesgwin,0,0,0,0,0,0,0,0);
		box(mw, 0, 0);
	}
	update_panels();
	refresh();
	doupdate();
}

void restore_mesg(void) {
	int y;

	/*
	 * Restore the buffer.
	 * Remember that the y must start at 1 to do not touch the border.
	 * The screen start at 1 but the buffer start at 0.
	 */
        for (y = 1; mesgbuf[y-1][0] != '\0' && y < 9; y++) {
		mvwprintw(mesgwin, y, 1, mesgbuf[y-1]);
	}
	wborder(mesgwin,0,0,0,0,0,0,0,0);
	update_all();
}

void write_mesg(char *fmt, ...) {
	va_list args;
	static char buffer[1024];
	int x, y;

	memset(buffer, 0, 1024);

	va_start(args, fmt);
	vsprintf(buffer, fmt, args);
	va_end(args);

        buffer[strlen(buffer)] = '\n';

	getyx(mesgwin, y, x);

	/*
	 * If we write the first line of window we must start at 1 because we
	 * do not want to touch the nice border.
	 */
	if (y == 0)
		y = 1;

	/*
	 * At the low end of the window we scroll the entire content up one
	 * line.
	 */
	if (y == 9) {
		wscrl(mesgwin, 1);
		y = 8;
	}

	mvwprintw(mesgwin, y, 1, buffer);
	wborder(mesgwin,0,0,0,0,0,0,0,0);

	/*
	 * Save the last 8 lines of buffer.
	 */
	/*
	 * If buffer full.
	 */
	if(mesgbuf[7][0]) {
		/*
		 * Scroll the buffer.
		 */
		for (y = 1; y < 8; y++) {
			strcpy(mesgbuf[y-1], mesgbuf[y]);
		}
		/*
		 * Now point to the last line of the mesgbuf.
		 */
		y = 7;
	} else {
		/*
		 * Find the first free slot.
		 */
		for (y = 0; mesgbuf[y][0]; y++)
			;
	}
	/*
	 * y now point to a free slot.
	 */
	strcpy(mesgbuf[y], buffer);
}

void update_upsdata(int sig) {
	static int power_fail = FALSE;
	static int battery_fail = FALSE;
	time_t now;
	char *t;

	if (read_shmarea(&myUPS, 0) != SUCCESS) {
	    exit(1);
	}
	get_raw_upsinfo(&myUPS, host, port);

	time(&now);
	t = ctime (&now);
        t[strlen(t)-1] = '\0';

        mvwprintw(statwin, 1, 1, "Last update: %s", t);
        mvwprintw(statwin, 2, 1, "Model      : %s", myUPS.mode.long_name);
        mvwprintw(statwin, 3, 1, "Cable      : %s", myUPS.cable.long_name);
        mvwprintw(statwin, 4, 1, "Mode       : %s", myUPS.class.long_name);
        mvwprintw(statwin, 5, 1, "AC Line    : %s",
                        (myUPS.OnBatt ? "failing" : "okay"));
        mvwprintw(statwin, 6, 1, "Battery    : %s",
                        (myUPS.BattLow ? "failing" : "okay"));
        mvwprintw(statwin, 7, 1, "AC Level   : %s",
			(myUPS.LineLevel ?
                         ((myUPS.LineLevel == 1) ? "high" : "low")
                         : "normal"));
        mvwprintw(statwin, 8, 1, "Last event : %s",
			xlate_history(myUPS.G[0]));

	if (myUPS.LineLevel) {
                write_mesg("* [%s] warning: AC level is %s", t,
                                ((myUPS.LineLevel == 1) ? "high" : "low"));
	}

	if (myUPS.OnBatt) {
		if (power_fail == FALSE) {
                        write_mesg("* [%s] warning: power is failing", t);
			power_fail = TRUE;
		}
	} else {
		if (power_fail == TRUE) {
                        write_mesg("* [%s] warning: power is returned", t);
			power_fail = FALSE;
		}
	}

	if (myUPS.BattLow) {
		if (battery_fail == FALSE) {
                        write_mesg("* [%s] warning: battery is failing", t);
			power_fail = TRUE;
		}
	} else {
		if (battery_fail == TRUE) {
                        write_mesg("* [%s] warning: battery is okay", t);
			battery_fail = FALSE;
		}
	}

	update_all();

	alarm(TIMER_POWERFLUTE);
}

void close_curses(void) {
	signal(SIGALRM, SIG_IGN);
	closing_curses = 1;
	del_panel(menupan);
	del_panel(statpan);
	del_panel(monipan);
	del_panel(mesgpan);
	delwin(menuwin);
	delwin(statwin);
	delwin(moniwin);
	delwin(mesgwin);
	werase(stdscr);
	update_all();
	endwin();
	detach_ipc(&myUPS);
}

static int menu_virtualize(int c)
{
    if (c == '\n' || c == KEY_EXIT)
	    return(MAX_COMMAND + 1);
        else if (c == 'n' || c == KEY_DOWN)
	return(REQ_NEXT_ITEM);
   else if (c == 'p' || c == KEY_UP)
	    return(REQ_PREV_ITEM);
       else if (c == ' ')
	return(REQ_TOGGLE_ITEM);
    else
	    return(c);
}

char * do_menu(int * pos, ITEM **it0, int pos_x) {
	ITEM **it = it0;
	static char answer[80];
	int r, c;
	int mc;

	mu = new_menu(it0);
	scale_menu(mu, &r, &c);

	mw = newwin(r+2, c+2, 2, pos_x);
	mpan = new_panel(mw);
	set_menu_win(mu, mw);
	keypad(mw, TRUE);
	box(mw, 0, 0);
	top_panel(mpan);
	show_panel(mpan);
	dmw = derwin(mw, r, c, 1, 1);
	set_menu_sub(mu, dmw);
	post_menu(mu);

        answer[0] = '\0';

	do {
		mc = wgetch(mw);
		if ((mc == KEY_UP) && (item_index(current_item(mu)) == 0)) {
			goto out_nokey;
		}
		if (mc == KEY_RIGHT) {
			*pos = (*pos+1) % 3;
			goto out_nokey;
		}
		if (mc == KEY_LEFT) {
			*pos = (*pos+2) % 3;
			goto out_nokey;
		}
	} while (menu_driver(mu, menu_virtualize(mc))
			!= E_UNKNOWN_COMMAND);

	strcpy(answer, item_name(current_item(mu)));

out_nokey:
	unpost_menu(mu);

	del_panel(mpan);
	delwin(dmw);
	dmw = NULL;
	delwin(mw);
	mw = NULL;
	free_menu(mu);
	mu = NULL;

	for(it=it0; *it; it++)
		free_item(*it);
	
	return answer;
}

void do_file_menu(int * pos) {
	ITEM *it0[64];
	ITEM **it = it0;
	char *answer;

        *it++ = new_item("Load", "No op");
        *it++ = new_item("Save", "No op");
        *it++ = new_item("Refresh", "screen");
        *it++ = new_item("Quit", "");
	*it = NULL;

	answer = do_menu(pos, it0, 0);
        if (answer[0] == '\0')
		return;

        if (!strcmp(answer, "Refresh")) {
		restart_curses();
		/*
		 * Never reached.
		 */
	}

        if (!strcmp(answer, "Quit")) {
		close_curses();
		exit(0);
	}
}

void do_upscontrol_menu(int * pos) {
	ITEM *it0[64];
	ITEM **it = it0;
	char *answer;

        *it++ = new_item("Test battery", "No op");
        *it++ = new_item("Test leds", "No op");
        *it++ = new_item("UPS shutdown", "No op");
	*it = NULL;

	answer = do_menu(pos, it0, 14);
        if (answer[0] == '\0')
		return;
}

void do_help_menu(int * pos) {
	ITEM *it0[64];
	ITEM **it = it0;
	char *answer;

        *it++ = new_item("About powerflute", "");
	*it = NULL;

	answer = do_menu(pos, it0, 28);
        if (answer[0] == '\0')
		return;

        if (!strcmp(answer, "About powerflute")) {
                write_mesg("Powerflute, a program to monitor the UPS and "
                                "control the apcupsd daemon");
                write_mesg("Written by Riccardo Facchetti <riccardo@master.oasi.gpa.it>");
	}
}

char *hm[] = {
        "File          ",
        "UPS           ",
        "Help          ",
	NULL
};

void display_h_menu(pos) {
	char **p=hm;

        mvwprintw(menuwin, 1, 2, "%s", "");

	for (p=hm; *p != NULL; p++) {
		if (pos == (p-hm)) {
			wattron(menuwin, A_REVERSE);
		}
                wprintw(menuwin, "%s", *p);
		if (pos == (p-hm)) {
			wattroff(menuwin, A_REVERSE);
		}
	}
	update_all();
}

int do_horiz_menu(void) {
	int pos = 0;
	int oldpos = 0;

	while (1) {

		display_h_menu(pos);

		switch (wgetch(menuwin)) {
			case KEY_LEFT:
                        case 'h':
				pos = (pos+2) % 3;
				break;

			case KEY_RIGHT:
                        case 'l':
				pos = (pos+1) % 3;
				break;

			case KEY_DOWN:
			case 10: /* RETURN */
change_menu:
				oldpos = pos;
				switch (pos) {
					case 0:
						do_file_menu(&pos);
						break;
					case 1:
						do_upscontrol_menu(&pos);
						break;
					case 2:
						do_help_menu(&pos);
						break;
					default:
						break;
				}
				pos = pos % 4;
				if (oldpos != pos) {
					display_h_menu(pos);
					goto change_menu;
				}
				break;

			default:
				break;
		}
	}

	return SUCCESS;
}

int init_main_screen(void) {
	/*
	 * Init ncurses subsystem
	 */
	if (initscr() == NULL)
		goto out_err;

	if (LINES < 25 || COLS < 80)
		goto out_err;

	if (cbreak() == ERR)
		goto out_err;

	if (noecho() == ERR)
		goto out_err;

	/*
	 * Invisible cursor
	 */
	curs_set(0);

	/*
	 * Build all windows and panels
	 */
	menuwin = newwin(3,0,0,0);
	keypad(menuwin, TRUE);
	menupan = new_panel(menuwin);
	wborder(menuwin,0,0,0,0,0,0,0,0);
	show_panel(menupan);

	statwin = newwin(12,40,3,0);
	statpan = new_panel(statwin);
	wborder(statwin,0,0,0,0,0,0,0,0);
	show_panel(statpan);

	moniwin = newwin(12,40,3,40);
	monipan = new_panel(moniwin);
	wborder(moniwin,0,0,0,0,0,0,0,0);
	show_panel(monipan);

	mesgwin = newwin(10,0,15,0);
	mesgpan = new_panel(mesgwin);
	wborder(mesgwin,0,0,0,0,0,0,0,0);
	show_panel(mesgpan);
	scrollok(mesgwin, TRUE);

	update_all();

	return SUCCESS;

out_err:
	close_curses();
	return FAILURE;
}

int main(int argc, char **argv)
{
	int status;
	int flag;

	strncpy(argvalue, argv[0], sizeof(argvalue)-1);
	argvalue[sizeof(argvalue)-1] = 0;

	init_ups_struct(ups);

	if (argc > 2) { 		  /* assume host:port */
	    char *p;
	    host = argv[2];
            p = strchr(host, ':');
	    if (p) {
		*p++ = 0;
		port = atoi(p);
	    }
	}

	/*
	 * Do not move this line below the setjmp.
	 */
	memset(mesgbuf, 0, 1024*8);

	/*
	 * For refreshing the screen in very bad situations like when
	 * someone broadcast a wall.
	 */
	flag = setjmp(env);

	status = SUCCESS;

	closing_curses = 0;

	/*
	 * Attach daemon shared memory area.
	 */
	if (attach_ipc(ups, SHM_RDONLY) != SUCCESS) {
                fprintf(stderr, "Can not attach SYSV IPC: "
                                "Apcupsd not running or you are not root.\n");
		exit(1);
	}
		
	/*
	 * Init ncurses subsystem.
	 */
	if (init_main_screen() == FAILURE) {
		if (LINES < 25 || COLS < 80)
                        fprintf(stderr, "You must have at least 80 columns "
                                        "x 25 lines.\n");
                fprintf(stderr, "Error initializing ncurses subsystem\n");
		status = FAILURE;
		goto out;
	}


	init_timer(TIMER_POWERFLUTE, update_upsdata);

	/*
	 * If after the longjmp we need to restore the mesg buffer, do it now.
	 */
	if (flag == RESTORE_BUFFER)
		restore_mesg();

	/*
	 * Update data immediately.
	 */
	update_upsdata(0);

	load_events();

	do_horiz_menu();

	close_curses();

out:
	detach_ipc(ups);
	return status;
}


/* Fixup missing error_cleanup() */
void error_cleanup(UPSINFO *ups)
{
    detach_ipc(ups);
    close_curses();
    exit(1);
}
#endif /* HAVE_POWERFLUTE */