aboutsummaryrefslogtreecommitdiff
path: root/aepd/main.c
blob: 3b5ea212d6671c02f3f1afdfa99afbc932412df1 (plain)
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
/*
 * Author: Andy Green <andy.green@linaro.org> 
 * Copyright (C) 2012 Linaro, LTD
 * Libwebsocket demo code (C) 2010-2012 Andy Green <andy@warmcat.com>
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 *
 */

#include "aepd.h"

unsigned long max_fifo_extent_seconds = 120;

#define MAX_FIFO_EXTENT (MAX_PROBES * CHANNELS_PER_PROBE * sizeof(double) * \
			DOUBLES_PER_CH_SAMPLE * 10000 * max_fifo_extent_seconds)

struct aepd_shared *aepd_shared;
struct aepd_interface *aepd_interface;
static double sam[MAX_PROBES * CHANNELS_PER_PROBE * DOUBLES_PER_CH_SAMPLE];
extern struct libwebsocket_protocols protocols[];

void zero_fifo(void)
{
	int n;

	lseek(aepd_shared->fd_fifo_write, 0, SEEK_SET);
	aepd_shared->fifo_pos = 0;
	aepd_shared->fifo_wrapped = 0;
	for (n = 0; n < sizeof(sam) / sizeof(sam[0]); n++)
		sam[n] = 0.0;
	if (aepd_shared->chans > 0)
		aepd_shared->modulo_integer_chan_size =
			(MAX_FIFO_EXTENT / (aepd_shared->chans * sizeof(double) * 3)) *
			(aepd_shared->chans * sizeof(double) * 3);
	aepd_shared->fifo_head_time = 0;
	aepd_shared->fifo_tail_time = 0;
}

int add_fifo(void *data, unsigned int length)
{
	long l;

	l = write(aepd_shared->fd_fifo_write, data, length);
	if (l < length) {
		fprintf(stderr, "fifo write failed...\n");
		return (int)l;
	}

	/*
	 * make sure the other processes can see it...
	 */
	fdatasync(aepd_shared->fd_fifo_write);

	aepd_shared->fifo_pos += length;
	if (aepd_shared->fifo_pos >= aepd_shared->modulo_integer_chan_size) {
		aepd_shared->fifo_wrapped = 1;
		aepd_shared->fifo_pos = 0;
		lseek(aepd_shared->fd_fifo_write, 0, SEEK_SET);
	}

	return 0;
}

struct aep_context aep_context = {
	.config_filepath = "./config",
	.highest = -1,
	.decimate = 1,
	.mv_min = 400,
	.trigger_filter_us = 400,
	.end_trigger_filter_us = 500000,
	.average_len = 1,
	.configuration_name = "default_configuration",
	.verbose = 0,
};


static struct option options[] = {
	{ "help",	no_argument,		NULL, 'h' },
	{ "port",	required_argument,	NULL, 'p' },
	{ "buffer",	required_argument,	NULL, 'b' },
	{ "ssl",	no_argument,		NULL, 's' },
	{ "interface",  required_argument,	NULL, 'i' },
	{ NULL, 0, 0, 0 }
};

static int loop = 1;

void sighandler(int sig)
{
	loop = 0;
}

static struct lws_context_creation_info info;

int main(int argc, char *argv[])
{
	int n = 0, m;
	const char *cert_path =
			    LOCAL_RESOURCE_PATH"/aepd.pem";
	const char *key_path =
			LOCAL_RESOURCE_PATH"/aepd.key.pem";
	int port = 15164;
	int use_ssl = 0;
	struct libwebsocket_context *context;
	int opts = LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME;
	char interface_name[128] = "";
	const char *interface_ptr = NULL;
	struct aepd_interface_result *aepd_interface_result;
	struct timeval tv;
	unsigned long last = 0;
	unsigned long ms10 = -1;

	fprintf(stderr,
		"ARM Energy Probe Daemon  (C) Copyright 2012-2013 Linaro, LTD\n"
		"licensed under LGPL2.1\n");

	signal(SIGINT, sighandler);

	/*
	 * create our lump of shared memory
	 * which is usable by all forked processes
	 */

	n = open("/dev/zero", O_RDWR);
	aepd_shared = mmap(NULL, sizeof (struct aepd_shared),
		PROT_READ | PROT_WRITE, MAP_SHARED, n, 0);
	close(n);

	/*
	 * open spool fifo for result data we can serve
	 * it's a large ring buffer to deal with long term pretrigger
	 * websocket clients can make requests for variously-zoomed
	 * parts of this buffer.
	 */

	aepd_shared->fifo_filepath = tmpnam(aepd_shared->fifo_filepath_stg);
	aepd_shared->fd_fifo_write = open(aepd_shared->fifo_filepath,
						       O_CREAT | O_RDWR, 0600);
	if (aepd_shared->fd_fifo_write < 0) {
		fprintf(stderr, "Unable to open sample fifo file %s\n",
						    aepd_shared->fifo_filepath);
		return -1;
	}
	aepd_shared->fd_fifo_read = open(aepd_shared->fifo_filepath, O_RDONLY);
	if (aepd_shared->fd_fifo_read < 0) {
		fprintf(stderr, "Unable to open sample fifo file %s for read\n",
						    aepd_shared->fifo_filepath);
		return -1;
	}

	zero_fifo();

	while (n >= 0) {
		n = getopt_long(argc, argv, "b:si:p:", options, NULL);
		if (n < 0)
			continue;
		switch (n) {

		case 'b':
			max_fifo_extent_seconds = atoi(optarg);
			break;

		case 's':
			use_ssl = 1;
			break;
		case 'p':
			port = atoi(optarg);
			break;
		case 'i':
			strncpy(interface_name, optarg, sizeof interface_name);
			interface_name[(sizeof interface_name) - 1] = '\0';
			break;

		default:
		case 'h':
			fprintf(stderr, "Usage: arm-probe \n"
			    " [--buffer -b <secs>] duration of capture memory (5MB/sec!) default 120\n"
			    " [--ssl -s] Listen using SSL / Encrypted link\n"
			    " [--interface -i <if>] Listen on specific "
					"interface, eg, eth1\n"
			    " [--port -p -<port>] Port to listen on "
					"(default %u)\n", port
			);
			exit(1);
		}
	}

	/*
	 * generic sample interface
	 */

	aepd_interface = aepd_interface_create();
	if (aepd_interface == NULL) {
		fprintf(stderr, "failed to create aepd_interface region\n");
		return -1;
	}
	aep_context.aepd_interface = aepd_interface;

	/* libwebsockets context */

	if (!use_ssl)
		cert_path = key_path = NULL;

	info.port = port;
	info.iface = interface_ptr;
	info.protocols = protocols;
	info.ssl_cert_filepath = cert_path;
	info.ssl_private_key_filepath = key_path;
	info.uid = -1;
	info.gid = -1;
	info.options = opts;

	context = libwebsocket_create_context(&info);
	if (context == NULL) {
		fprintf(stderr, "libwebsocket init failed\n");
		return -1;
	}

	aep_context.original_count_channel_names = aep_context.count_channel_names;

	configure(&aep_context, NULL, "/virtual", aep_context.config_filepath, NULL);

	/*
	 * fork off the AEP service process
	 * runs in its own process to exploit SMP to dedicate one core for that
	 * what happens to samples is decoupled from capture process with large
	 * shared-memory buffer to allow for jitter
	 */

	if (aep_init_and_fork(&aep_context, argv) < 1)
		return 0; /* child process exit */

	
	n = fork();
	if (n < 0) {
		fprintf(stderr, "websockets service fork failed\n");
		return n;
	}
	if (!n) {
		strcpy(argv[0] + strlen(argv[0]), " - websockets server");

		/* websockets service process */

		while (1) {
			if (libwebsocket_service(context, 100))
				break;
			if (getppid() == 1)
				break;
			
			gettimeofday(&tv, NULL);

			ms10 = (tv.tv_sec * 10) + (tv.tv_usec / 100000);

			if (ms10 > last) {
				last = ms10;
				libwebsocket_callback_on_writable_all_protocol(&protocols[1]);
			}
		}

		libwebsocket_context_destroy(context);
		return 0;
	}

	/*
	 * this process just has to deal with collecting samples from
	 * any backend that acquired them into the shared memory
	 * buffer, and then make them available to the websocket
	 * callback via the aepd private fifo ring file
	 */

	aepd_shared->chans = -1;

	while (loop) {

		aepd_interface_result = aep_wait_for_next_result(aep_context.aepd_interface);
		if (!aepd_interface_result) {
			if (aepd_interface->finished)
				loop = 0;

			continue;
		}

		if (aepd_shared->stop_flag)
			goto done;

		/*
		 * we have the next result in aepd_interface_result..
		 * voltage and current per channel
		 */

		m = 0;
		for (n = 0; n < aepd_interface_result->chans * 2; n += 2) {

			/* 
			 * accumulate in V, A, W per-channel.
			 * We do summing like that so that we can compute
			 * averages over any distance without iteration, by
			 * (sample(x + distance) - sample(x)) / distance.
			 * We can recover individual intersample delta still
			 * by sample(x + 1) - sample(x) if we want it.
			 * Doubles are used to maximize dynamic range.
			 */

			sam[m++] += aepd_interface_result->buf[n];
			sam[m++] += aepd_interface_result->buf[n + 1];
			sam[m++] += aepd_interface_result->buf[n] * aepd_interface_result->buf[n + 1];
		}

		/*
		 * notice we have expanded the V/A 2 sample data
		 * into W as well.  That's because average of instantaneous W
		 * is not at all the same as average V * average A
		 */

		add_fifo(&sam[0], aepd_interface_result->chans * 3 * sizeof(double));
		aepd_shared->fifo_head_time = aepd_interface_result->samtime;
		if ((aepd_shared->fifo_head_time - aepd_shared->fifo_tail_time) > max_fifo_extent_seconds)
			aepd_shared->fifo_tail_time = aepd_shared->fifo_head_time - max_fifo_extent_seconds;
			

		if (aepd_shared->chans != aepd_interface_result->chans) {
			aepd_shared->chans = aepd_interface_result->chans;
			zero_fifo();
		}
done:
		/* done with it */

		aep_free_result(aepd_interface);
	}

	close(aepd_shared->fd_fifo_write);
	close(aepd_shared->fd_fifo_read);
	unlink(aepd_shared->fifo_filepath);

	aepd_interface_destroy(aepd_interface);

	fprintf(stderr, "exited\n");
	
	return 0;
}