File: aeg.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 (496 lines) | stat: -rw-r--r-- 10,280 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
/* 
   $Id: aeg.c,v 1.3 2001/06/08 09:47:18 r_sieger Exp $
   model specific routines for AEG Protect S. xxxx models
   
   Copyright (C) 2001  
   Ralf Sieger   <ralf.sieger@gmx.net>

   from:

   bestups.c - model specific routines for Best-UPS Fortress models
   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 <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/termios.h>

#include "config.h"
#include "proto.h"
#include "shared.h"
#include "version.h"
#include "upscommon.h"
#include "common.h"

#define INFOMAX  16
#define ENDCHAR  13	/* replies end with CR */
#define UPSDELAY  5
#define MAXTRIES 10

/* global variables */
int	shmok = 1;
char	*model = NULL;
float	lowvolt = 0, highvolt = 0, voltrange = 0;
int	linenorm = 230;
int	sddelay = 90;	/* wait 90 seconds for shutdown */
int	restore = 0;	/* turn ups on again if utility is available */
int	debug = 0;
int	quiet = 0;

void initinfo (void)
{
	create_info (INFOMAX, shmok);

	/* now set up room for all future variables that are supported */
	addinfo (INFO_MFR, "", 0, 0);
	addinfo (INFO_MODEL, "", 0, 0);
	addinfo (INFO_UTILITY, "", 0, 0);
	addinfo (INFO_BATTPCT, "", 0, 0);
	addinfo (INFO_STATUS, "", 0, 0);
	addinfo (INFO_ACFREQ, "", 0, 0);
	addinfo (INFO_LOADPCT, "", 0, 0);
	addinfo (INFO_UPSTEMP, "", 0, 0);
}

/* TODO: adapt to the standard upscommon open/send/recv calls */
void setup_serial(void)
{	
	struct	termios	tio;

	if (tcgetattr (upsfd, &tio) == -1)
		fatal("tcgetattr");

	tio.c_iflag = IXON | IXOFF;
	tio.c_oflag = 0;
	tio.c_cflag = (B2400 | CS8 | CREAD | HUPCL | CLOCAL);
	tio.c_lflag = 0;
	tio.c_cc[VMIN] = 1;
	tio.c_cc[VTIME] = 0; 

#ifdef HAVE_CFSETISPEED
	cfsetispeed (&tio, B2400);
	cfsetospeed (&tio, B2400);
#endif

	if (tcsetattr (upsfd, TCSANOW, &tio) == -1)
		fatal("tcsetattr");
}

static char readchar(void)
{
	char	c;
	int	ret;

	ret = read (upsfd, &c, 1);

	if (ret > 0)
		return (c & 0x7f);
	
	return 0;
}

/* TODO: also roll this into upscommon */
static int xrecv(int len, char *buf)
{
	char	ch, *p;
	int	count = 0;

	p = buf;
	*p = '\0';

	while ((ch = readchar ()) && (count < len)) {
		if (ch == ENDCHAR) {
			*p = '\0';
			return 0;
		}
	
		*p++ = ch;
		count++;
	}

	*p = '\0';
	return 0;
}

static void ups_sync()
{
	char	buf[256];
	int	tries = 0;

	if ( !quiet) {
		printf ("Syncing with UPS: ");
		fflush (stdout);
	}

	for (;;) {
		tries++;
		if (tries > MAXTRIES)
			fatalx("\nFailed - giving up...");
		upssend("%s", "\rQ1\r");
		if ( !quiet) {
			printf (".");
			fflush (stdout);
		}
		sleep (UPSDELAY);
		if ( !quiet) {
			printf (".");
			fflush (stdout);
		}
		xrecv (sizeof (buf), buf);
		if ( !quiet) {
			printf (".");
			fflush (stdout);
		}
		if (buf[0] == '(')
			break;			
	}

	if ( !quiet) 
		printf (" done\n");
}

/* power down the attached load immediately */
void forceshutdown(const char *port)
{
	char	temp[256], stat[32];
	int	tries = 0;

	upslogx(LOG_INFO, "Initiating UPS shutdown");
	
	if ( !quiet) 
		printf ("Initiating forced UPS shutdown!\n");

	upsfd = open(port, O_RDWR | O_NDELAY);
	if (upsfd == -1)
		fatal("open %s", port);

	setup_serial();

	/* basic idea: find out line status and send appropriate command */

	if ( !quiet) {
		printf ("Checking status: ");
		fflush (stdout);
	}
	for (;;) {
		tries++;
		if (tries > MAXTRIES) {
			fatalx("Failed - giving up...");
			exit (1);
		}
		upssend ("\rQ1\r");
		if ( !quiet) {
			printf (".");
			fflush (stdout);
		}
		sleep (UPSDELAY);
		if ( !quiet) {
			printf (".");
			fflush (stdout);
		}
		xrecv (sizeof (temp), temp);
		if ( !quiet) {
			printf (".");
			fflush (stdout);
		}
		if ((temp[0] == '(') && (strlen(temp) == 46))
			break;
	}

	if ( !quiet) 
		printf (" done\n");

	sscanf (temp, "%*s %*s %*s %*s %*s %*s %*s %s", stat);

	/* on battery: send S01<cr>, ups will return by itself on utility */
	/* on line: send S01R0001<cr>, ups will cycle and return soon */

	upssend("%s", "S01");

	if (restore) {
		if ( !quiet) 
			printf ("sending shutdown+restore command...\n");
		upssend("%s", "R0001");
	} else {
		if ( !quiet) 
			printf ("sending normal shutdown command...\n");
	}

	upssend("%s", "\r");	/* end sequence */

	if (sddelay > 0) {
		if ( !quiet) 
			printf ("Waiting for poweroff...\n");
		sleep (sddelay);
		if ( !quiet) 
			printf ("Hmm, did the shutdown fail?  Oh well...\n");
		exit (1);                               
	}
	exit (0);
}

static void setmodel(const char *abbr, const char *va)
{
	char	temp[256];

	if (!strcmp(abbr, "AEG")) {
		setinfo (INFO_MFR, "AEG SVS");
		snprintf (temp, sizeof(temp), "Protect S. %s", va);
		setinfo (INFO_MODEL, temp);
		return;
	}


	setinfo(INFO_MFR, "%s", "Unknown");
	setinfo(INFO_MODEL, "Unknown %s (%s)", abbr, va);

	printf ("Unknown model detected - please report this ID: '%s'\n", abbr);
}

static void ups_update()
{
	char	utility[16], loadpct[16], acfreq[16], battvolt[16],
		upstemp[16], stat[16], buf[256], temp[VALSIZE];
	float	bvoltp;

	upssend("%s", "\rQ1\r");
	sleep (UPSDELAY); 
	xrecv (sizeof (buf), buf);

	if ((strlen(buf) < 46) || (buf[0] != '('))
		return;
	
	if (debug)
		printf ("buf Q1: [%s]\n", buf);

	sscanf (buf, "%*c%s %*s %*s %s %s %s %s %s", utility, loadpct, 
	        acfreq, battvolt, upstemp, stat);
	
	setinfo(INFO_UTILITY, "%s", utility);

	bvoltp = ((atof (battvolt) - lowvolt) / voltrange) * 100.0;

	if (bvoltp > 100.0)
		bvoltp = 100.0;

	setinfo(INFO_BATTPCT, "%02.1f", bvoltp);

	strcpy (temp, "");

	if (stat[0] == '0')
		strcat (temp, "OL ");		/* on line */
	else
		strcat (temp, "OB ");		/* on battery */

	if (stat[1] == '1')
		strcat (temp, "LB ");		/* low battery */

	if (stat[2] == '1') {		/* boost or trim in effect */
		if (atoi(utility) < linenorm)
			strcat (temp, "BOOST");

		if (atoi(utility) > linenorm)
			strcat (temp, "TRIM");
	}

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

	setinfo(INFO_STATUS, "%s", temp);
	setinfo(INFO_ACFREQ, "%s", acfreq);
	setinfo(INFO_LOADPCT, "%s", loadpct);
	setinfo(INFO_UPSTEMP, "%s", upstemp);

	writeinfo();
}

void instcmd (int auxcmd, int dlen, char *data)
{
	/* TODO: reply to upsd? */

	switch (auxcmd) {
		case CMD_BTEST0:	/* stop battery test */
			upssendchar ('C');
			upssendchar ('T');
			upssendchar (ENDCHAR);
			break;
		case CMD_BTEST1:	/* start battery test */
			upssendchar ('T');
			upssendchar (ENDCHAR);
			break;
		default:
			upslogx(LOG_INFO, "instcmd: unknown type 0x%04x",
			        auxcmd);
	}
}

void setuphandlers(void)
{
	upsh.instcmd = instcmd;
}

static void run_debug()
{
	
	while (1)
		ups_update ();
}

static void usage(const char *prog)
{
	printf ("usage: %s [-hDqkr] [-d <num>] [-l <num>] -m <model> <device>\n", prog);
	printf ("-h		- display this help\n");
	printf ("-D		- run in debug mode\n");
	printf ("-q		- quiet: do not print to stdout\n");
	printf ("-k		- force shutdown\n");
	printf ("-r		- turn ups on again if utility returns\n");
	printf ("-d <num>	- wait <num> seconds after sending shutdown command\n");
	printf ("-l <num>	- line voltage, default 230\n");
	printf ("-m <model>	- model number\n");
	printf ("<device> - /dev entry corresponding to UPS port\n");
	printf ("\n");
	printf ("Example: %s -m 1000 /dev/ttyS0\n", prog);
	exit (1);
}

int main(int argc, char **argv)
{
	char	*prog, *portname;
	int	i;

	prog = argv[0];

	while ((i = getopt(argc, argv, "+d:qDrm:hk:l:")) != EOF) {
		switch (i) {
			case 'l':
				linenorm = atoi (optarg);
				break;
			case 'd':
				sddelay = atoi(optarg);
				break;
			case 'q':
				quiet = 1;
				break;
			case 'D':
				debug = 1;
				break;
			case 'r':
				restore = 1;
				break;
			case 'k':
				forceshutdown(optarg);
				break;
			case 'h':
				usage (prog);
				break;
			case 'm':
				model = strdup (optarg);
				break;
			default:
				usage(prog);
				break;
		}
	}

	argc -= optind;
	argv += optind;

	if (argc != 1) {
		usage (prog);
		exit (1);
	}
	if ( !model) {
		printf ("error: no model number given\n");
		exit (1);
	}
	
	if ( !quiet) {
		printf ("Network UPS Tools - ");
		printf ("AEG Protect driver v0.01 (%s)\n", UPS_VERSION);
	}
	openlog ("aeg", LOG_PID, LOG_FACILITY);
	
	if (debug)
		printf ("Running in debug mode\n");
	
	droproot();

	portname = NULL;
	for (i = strlen(argv[0]); i >= 0; i--)
		if (argv[0][i] == '/') {
			portname = &argv[0][i+1];
			break;
		}

	if (portname == NULL) {
		printf ("Unable to abbreviate %s\n", argv[0]);
		exit (1);
	}

	snprintf (statefn, sizeof(statefn), "%s/aeg-%s", STATEPATH, portname);

	upsfd = open(argv[0], O_RDWR | O_NDELAY);
	if (upsfd == -1)
		fatal("open %s", argv[0]);

	setup_serial();
	ups_sync();
	
	/* ToDo: check if these ranges are
		 true for all models. */
	lowvolt = 1.66;
	highvolt = 2.30;
	voltrange = highvolt - lowvolt;

	initinfo();
	createmsgq();	/* try to create IPC message queue */
	setuphandlers();
	setmodel ("AEG", model);

        addinfo (INFO_INSTCMD, "", 0, CMD_BTEST0);
        addinfo (INFO_INSTCMD, "", 0, CMD_BTEST1);
	if ( !quiet) 
		printf ("Detected %s %s on %s\n", getdata(INFO_MFR), getdata(INFO_MODEL), argv[0]);

	snprintf (pidfn, sizeof(pidfn), "aeg-%s", portname);
	if (debug) {
		run_debug ();
        writepid (pidfn);
	} else {
		background();
        writepid (pidfn);
		while (1) {
			ups_update();

			if (getupsmsg(2))       /* TODO: remove debug scaffolding */
				upslogx(LOG_INFO, "Received a message from upsd");
		}
	}

	return 0;
}