aboutsummaryrefslogtreecommitdiffhomepage
path: root/backends/openpixelcontrol.c
blob: 62cdb6830dc221807d408d4612e15f15ced7d1d2 (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
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
#define BACKEND_NAME "openpixelcontrol"

#include <string.h>

#include "libmmbackend.h"
#include "openpixelcontrol.h"

/*
 * TODO handle destination close/unregister/reopen
 */

MM_PLUGIN_API int init(){
	backend openpixel = {
		.name = BACKEND_NAME,
		.conf = openpixel_configure,
		.create = openpixel_instance,
		.conf_instance = openpixel_configure_instance,
		.channel = openpixel_channel,
		.handle = openpixel_set,
		.process = openpixel_handle,
		.start = openpixel_start,
		.shutdown = openpixel_shutdown
	};

	//register backend
	if(mm_backend_register(openpixel)){
		LOG("Failed to register backend");
		return 1;
	}
	return 0;
}

static int openpixel_configure(char* option, char* value){
	//no global configuration
	LOG("No backend configuration possible");
	return 1;
}

static int openpixel_configure_instance(instance* inst, char* option, char* value){
	char* host = NULL, *port = NULL;
	openpixel_instance_data* data = (openpixel_instance_data*) inst->impl;

	//FIXME this should store the destination/listen address and establish on _start
	if(!strcmp(option, "destination")){
		mmbackend_parse_hostspec(value, &host, &port, NULL);
		if(!host || !port){
			LOGPF("Invalid destination address specified for instance %s", inst->name);
			return 1;
		}

		data->dest_fd = mmbackend_socket(host, port, SOCK_STREAM, 0, 0);
		if(data->dest_fd >= 0){
			return 0;
		}
		LOGPF("Failed to connect to server for instance %s", inst->name);
		return 1;
	}
	if(!strcmp(option, "listen")){
		mmbackend_parse_hostspec(value, &host, &port, NULL);
		if(!host || !port){
			LOGPF("Invalid listen address specified for instance %s", inst->name);
			return 1;
		}

		data->listen_fd = mmbackend_socket(host, port, SOCK_STREAM, 1, 0);
		if(data->listen_fd >= 0 && !listen(data->listen_fd, SOMAXCONN)){
			return 0;
		}
		LOGPF("Failed to bind server descriptor for instance %s", inst->name);
		return 1;
	}
	else if(!strcmp(option, "mode")){
		if(!strcmp(value, "16bit")){
			data->mode = rgb16;
			return 0;
		}
		else if(!strcmp(value, "8bit")){
			data->mode = rgb8;
			return 0;
		}
		LOGPF("Unknown instance mode %s\n", value);
		return 1;
	}

	LOGPF("Unknown instance option %s for instance %s", option, inst->name);
	return 1;
}

static int openpixel_instance(instance* inst){
	openpixel_instance_data* data = calloc(1, sizeof(openpixel_instance_data));
	inst->impl = data;
	if(!inst->impl){
		LOG("Failed to allocate memory");
		return 1;
	}

	data->dest_fd = -1;
	data->listen_fd = -1;
	return 0;
}

static ssize_t openpixel_buffer_find(openpixel_instance_data* data, uint8_t strip, uint8_t input){
	ssize_t n = 0;

	for(n = 0; n < data->buffers; n++){
		if(data->buffer[n].strip == strip
				&& (data->buffer[n].flags & OPENPIXEL_INPUT) >= input){
			DBGPF("Using allocated %s buffer for requested strip %d, size %d", input ? "input" : "output", strip, data->buffer[n].bytes);
			return n;
		}
	}
	DBGPF("Instance has no %s buffer for requested strip %d", input ? "input" : "output", strip);
	return -1;
}

static int openpixel_buffer_extend(openpixel_instance_data* data, uint8_t strip, uint8_t input, uint16_t length){
	ssize_t buffer = openpixel_buffer_find(data, strip, input);
	
	//length is in component-channels, round it to the nearest rgb-triplet
	//this guarantees that any allocated buffer has at least three bytes, which is important to parts of the receive handler
	length = (length % 3) ? ((length / 3) + 1) * 3 : length;

	//calculate required buffer length
	size_t bytes_required = (data->mode == rgb8) ? length : length * 2;
	if(buffer < 0){
		//allocate new buffer
		data->buffer = realloc(data->buffer, (data->buffers + 1) * sizeof(openpixel_buffer));
		if(!data->buffer){
			data->buffers = 0;
			LOG("Failed to allocate memory");
			return -1;
		}

		buffer = data->buffers;
		data->buffers++;

		data->buffer[buffer].strip = strip;
		data->buffer[buffer].flags = input ? OPENPIXEL_INPUT : 0;
		data->buffer[buffer].bytes = 0;
		data->buffer[buffer].data.u8 = NULL;
	}

	if(data->buffer[buffer].bytes < bytes_required){
		//resize buffer
		data->buffer[buffer].data.u8 = realloc(data->buffer[buffer].data.u8, bytes_required);
		if(!data->buffer[buffer].data.u8){
			data->buffer[buffer].bytes = 0;
			LOG("Failed to allocate memory");
			return 1;
		}
		//FIXME might want to memset() only newly allocated channels
		memset(data->buffer[buffer].data.u8, 0, bytes_required);
		data->buffer[buffer].bytes = bytes_required;
	}
	return 0;
}

static channel* openpixel_channel(instance* inst, char* spec, uint8_t flags){
	uint32_t strip = 0, channel = 0;
	char* token = spec;
	openpixel_instance_data* data = (openpixel_instance_data*) inst->impl;

	//read strip index if supplied
	if(!strncmp(spec, "strip", 5)){
		strip = strtoul(spec + 5, &token, 10);
		//skip the dot
		token++;
	}

	//read (and calculate) channel index
	if(!strncmp(token, "channel", 7)){
		channel = strtoul(token + 7, NULL, 10);
	}
	else if(!strncmp(token, "red", 3)){
		channel = strtoul(token + 3, NULL, 10) * 3 - 2;
	}
	else if(!strncmp(token, "green", 5)){
		channel = strtoul(token + 5, NULL, 10) * 3 - 1;
	}
	else if(!strncmp(token, "blue", 4)){
		channel = strtoul(token + 4, NULL, 10) * 3;
	}

	if(!channel){
		LOGPF("Invalid channel specification %s", spec);
		return NULL;
	}

	//check channel direction
	if(flags & mmchannel_input){
		//strip 0 (bcast) can not be mapped as input
		if(!strip){
			LOGPF("Broadcast channel %s.%s can not be mapped as an input", inst->name, spec);
			return NULL;
		}
		if(data->listen_fd < 0){
			LOGPF("Channel %s mapped as input, but instance %s is not accepting input", spec, inst->name);
			return NULL;
		}

		if(openpixel_buffer_extend(data, strip, 1, channel)){
			return NULL;
		}
	}

	if(flags & mmchannel_output){
		if(data->dest_fd < 0){
			LOGPF("Channel %s mapped as output, but instance %s is not sending output", spec, inst->name);
			return NULL;
		}

		if(openpixel_buffer_extend(data, strip, 0, channel)){
			return NULL;
		}
	}

	return mm_channel(inst, ((uint64_t) strip) << 32 | channel, 1);
}

static int openpixel_output_data(openpixel_instance_data* data){
	size_t u;
	openpixel_header hdr;

	//send updated strips
	for(u = 0; u < data->buffers; u++){
		if(!(data->buffer[u].flags & OPENPIXEL_INPUT) && (data->buffer[u].flags & OPENPIXEL_MARK)){
			//remove mark
			data->buffer[u].flags &= ~OPENPIXEL_MARK;

			//prepare header
			hdr.strip = data->buffer[u].strip;
			hdr.mode = data->mode;
			hdr.length = htobe16(data->buffer[u].bytes);

			//output data
			if(mmbackend_send(data->dest_fd, (uint8_t*) &hdr, sizeof(hdr))
					|| mmbackend_send(data->dest_fd, data->buffer[u].data.u8, data->buffer[u].bytes)){
				return 1;
			}
		}
	}

	return 0;
}

static int openpixel_set(instance* inst, size_t num, channel** c, channel_value* v){
	openpixel_instance_data* data = (openpixel_instance_data*) inst->impl;
	size_t u, p;
	ssize_t buffer;
	uint32_t strip, channel;

	for(u = 0; u < num; u++){
		//read strip/channel
		strip = c[u]->ident >> 32;
		channel = c[u]->ident & 0xFFFFFFFF;
		channel--;

		//find the buffer
		buffer = openpixel_buffer_find(data, strip, 0);
		if(buffer < 0){
			LOGPF("No buffer for channel %s.%d.%d\n", inst->name, strip, channel);
			continue;
		}

		//mark buffer for output
		data->buffer[buffer].flags |= OPENPIXEL_MARK;

		//update data
		switch(data->mode){
			case rgb8:
				data->buffer[buffer].data.u8[channel] = ((uint8_t)(v[u].normalised * 255.0));
				break;
			case rgb16:
				data->buffer[buffer].data.u16[channel] = ((uint16_t)(v[u].normalised * 65535.0));
				break;
		}

		if(strip == 0){
			//update values in all other output strips, don't mark
			for(p = 0; p < data->buffers; p++){
				if(!(data->buffer[p].flags & OPENPIXEL_INPUT)){
					//check whether the buffer is large enough
					if(data->mode == rgb8 && data->buffer[p].bytes >= channel){
						data->buffer[p].data.u8[channel] = ((uint8_t)(v[u].normalised * 255.0));
					}
					else if(data->mode == rgb16 && data->buffer[p].bytes >= channel * 2){
						data->buffer[p].data.u16[channel] = ((uint16_t)(v[u].normalised * 65535.0));
					}
				}
			}
		}
	}

	return openpixel_output_data(data);
}

static int openpixel_client_new(instance* inst, int fd){
	if(fd < 0){
		return 1;
	}
	openpixel_instance_data* data = (openpixel_instance_data*) inst->impl;
	size_t u;

	//mark nonblocking
	#ifdef _WIN32
	unsigned long flags = 1;
	if(ioctlsocket(fd, FIONBIO, &flags)){
	#else
	int flags = fcntl(fd, F_GETFL, 0);
	if(fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0){
	#endif
		LOGPF("Failed to set client descriptor on %s nonblocking", inst->name);
		close(fd);
		return 0;
	}

	//find a client block
	for(u = 0; u < data->clients; u++){
		if(data->client[u].fd <= 0){
			break;
		}
	}

	//if no free slot, make one
	if(u == data->clients){
		data->client = realloc(data->client, (data->clients + 1) * sizeof(openpixel_client));
		if(!data->client){
			data->clients = 0;
			LOG("Failed to allocate memory");
			return 1;
		}
		data->clients++;
	}

	data->client[u].fd = fd;
	data->client[u].buffer = -1;
	data->client[u].offset = 0;

	LOGPF("New client on instance %s", inst->name);
	return mm_manage_fd(fd, BACKEND_NAME, 1, inst);
}

static ssize_t openpixel_client_pixeldata(instance* inst, openpixel_client* client, uint8_t* buffer, size_t bytes_left){
	openpixel_instance_data* data = (openpixel_instance_data*) inst->impl;
	size_t u;
	channel* chan = NULL;
	channel_value val;

	if(client->buffer == -2){
		//ignore data
		u = min(client->left, bytes_left);
		client->offset += u;
		client->left -= u;
		return u;
	}
	else{
		if(data->mode == rgb8){
			for(u = 0; u < bytes_left; u++){
				//if over buffer length, ignore
				if(u + client->offset >= data->buffer[client->buffer].bytes){
					client->buffer = -2;
					break;
				}

				//FIXME if at start of trailing non-multiple of 3, ignore
				
				//update changed channels
				if(data->buffer[client->buffer].data.u8[u + client->offset] != buffer[u]){
					data->buffer[client->buffer].data.u8[u + client->offset] = buffer[u];
					chan = mm_channel(inst, ((uint64_t) client->hdr.strip << 32) | (u + client->offset + 1), 0);
					if(chan){
						//push event
						val.raw.u64 = buffer[u];
						val.normalised = (double) buffer[u] / 255.0;
						if(mm_channel_event(chan, val)){
							LOG("Failed to push channel event to core");
						}
					}
				}
			}

			//update offsets
			client->offset += u;
			client->left -= u;
			return u;
		}
		else{
			for(u = 0; u < bytes_left; u++){
				//if over buffer length, ignore
				if(u + client->offset >= data->buffer[client->buffer].bytes){
					client->buffer = -2;
					break;
				}

				//if at start of trailing non-multiple of 6, ignore
				if((client->offset + u) >= (client->offset + client->left) - ((client->offset + client->left) % 6)){
					client->buffer = -2;
					break;
				}

				//byte-order conversion may be on message boundary, do it via a buffer
				client->boundary.u8[(client->offset + u) % 2] = buffer[u];

				//detect and update changed channels
				if((client->offset + u) % 2
						&& data->buffer[client->buffer].data.u16[(u + client->offset) / 2] != be16toh(client->boundary.u16)){
					data->buffer[client->buffer].data.u16[(u + client->offset) / 2] = be16toh(client->boundary.u16);
					chan = mm_channel(inst, ((uint64_t) client->hdr.strip << 32) | ((u + client->offset) / 2 + 1), 0);
					if(chan){
						//push event
						val.raw.u64 = be16toh(client->boundary.u16);;
						val.normalised = (double) val.raw.u64 / 65535.0;
						if(mm_channel_event(chan, val)){
							LOG("Failed to push channel event to core");
						}
					}

				}
			}
		}
	}
	return -1;
}

static ssize_t openpixel_client_headerdata(instance* inst, openpixel_client* client, uint8_t* buffer, size_t bytes_left){
	openpixel_instance_data* data = (openpixel_instance_data*) inst->impl;
	size_t bytes_consumed = min(sizeof(openpixel_header) - client->offset, bytes_left);

	DBGPF("Reading %" PRIsize_t " bytes to header at offset %" PRIsize_t ", header size %" PRIsize_t ", %" PRIsize_t " bytes left", bytes_consumed, client->offset, sizeof(openpixel_header), bytes_left);
	memcpy(((uint8_t*) (&client->hdr)) + client->offset, buffer, bytes_consumed);

	//if done, resolve buffer
	if(sizeof(openpixel_header) - client->offset <= bytes_left){
		client->buffer = openpixel_buffer_find(data, client->hdr.strip, 1);
		//TODO handle broadcast strip input
		//if no buffer or mode mismatch, ignore data
		if(client->buffer < 0
				|| data->mode != client->hdr.mode){
			client->buffer = -2; //mark for ignore
		}
		client->left = be16toh(client->hdr.length);
		client->offset = 0;
	}
	//if not, update client offset
	else{
		client->offset += bytes_consumed;
	}

	//update scan offset
	return bytes_consumed;
}

static int openpixel_client_handle(instance* inst, int fd){
	openpixel_instance_data* data = (openpixel_instance_data*) inst->impl;
	uint8_t buffer[8192];
	size_t c = 0, offset = 0;
	ssize_t bytes_left = 0, bytes_handled;

	for(c = 0; c < data->clients; c++){
		if(data->client[c].fd == fd){
			break;
		}
	}

	if(c == data->clients){
		LOGPF("Unknown client descriptor signaled on %s", inst->name);
		return 1;
	}

	//FIXME might want to read until EAGAIN
	ssize_t bytes = recv(fd, buffer, sizeof(buffer), 0);
	if(bytes <= 0){
		if(bytes < 0){
			LOGPF("Failed to receive from client: %s", strerror(errno));
		}

		//close the connection
		close(fd);
		data->client[c].fd = -1;

		//unmanage the fd
		LOGPF("Client disconnected on %s", inst->name);
		mm_manage_fd(fd, BACKEND_NAME, 0, NULL);
		return 0;
	}
	DBGPF("Received %" PRIsize_t " bytes on %s", bytes, inst->name);

	for(bytes_left = bytes - offset; bytes_left > 0; bytes_left = bytes - offset){
		if(data->client[c].buffer == -1){
			//read a header
			bytes_handled = openpixel_client_headerdata(inst, data->client + c, buffer + offset, bytes_left);
			if(bytes_handled < 0){
				//FIXME handle errors
			}
		}
		else{
			//read data
			bytes_handled = openpixel_client_pixeldata(inst, data->client + c, buffer + offset, bytes_left);
			if(bytes_handled < 0){
				//FIXME handle errors
			}

			//end of data, return to reading headers
			if(data->client[c].left == 0){
				data->client[c].buffer = -1;
				data->client[c].offset = 0;
				data->client[c].left = 0;
			}
		}
		offset += bytes_handled;
	}
	DBGPF("Processing done on %s", inst->name);

	return 0;
}

static int openpixel_handle(size_t num, managed_fd* fds){
	size_t u;
	instance* inst = NULL;
	openpixel_instance_data* data = NULL;
	uint8_t buffer[8192];
	ssize_t bytes;

	for(u = 0; u < num; u++){
		inst = (instance*) fds[u].impl;
		data = (openpixel_instance_data*) inst->impl;

		if(fds[u].fd == data->dest_fd){
			//destination fd ready to read
			//since the protocol does not define any responses, the connection was probably closed
			bytes = recv(data->dest_fd, buffer, sizeof(buffer), 0);
			if(bytes <= 0){
				LOGPF("Output descriptor closed on instance %s", inst->name);
				//unmanage the fd to give the core some rest
				mm_manage_fd(data->dest_fd, BACKEND_NAME, 0, NULL);
			}
			else{
				LOGPF("Unhandled response data on %s (%" PRIsize_t" bytes)", inst->name, bytes);
			}
		}
		else if(fds[u].fd == data->listen_fd){
			//listen fd ready to read, accept a new client
			if(openpixel_client_new(inst, accept(data->listen_fd, NULL, NULL))){
				return 1;
			}
		}
		else{
			//handle client input
			if(openpixel_client_handle(inst, fds[u].fd)){
				return 1;
			}
		}
	}
	return 0;
}

static int openpixel_start(size_t n, instance** inst){
	int rv = -1;
	size_t u, nfds = 0;
	openpixel_instance_data* data = NULL;

	for(u = 0; u < n; u++){
		data = (openpixel_instance_data*) inst[u]->impl;

		//register fds
		if(data->dest_fd >= 0){
			if(mm_manage_fd(data->dest_fd, BACKEND_NAME, 1, inst[u])){
				LOGPF("Failed to register destination descriptor for instance %s with core", inst[u]->name);
				goto bail;
			}
			nfds++;
		}
		if(data->listen_fd >= 0){
			if(mm_manage_fd(data->listen_fd, BACKEND_NAME, 1, inst[u])){
				LOGPF("Failed to register host descriptor for instance %s with core", inst[u]->name);
				goto bail;
			}
			nfds++;
		}
	}

	LOGPF("Registered %" PRIsize_t " descriptors to core", nfds);
	rv = 0;
bail:
	return rv;
}

static int openpixel_shutdown(size_t n, instance** inst){
	size_t u, p;
	openpixel_instance_data* data = NULL;

	for(u = 0; u < n; u++){
		data = (openpixel_instance_data*) inst[u]->impl;

		//shutdown all clients
		for(p = 0; p < data->clients; p++){
			if(data->client[p].fd>= 0){
				close(data->client[p].fd);
			}
		}
		free(data->client);

		//close all configured fds
		if(data->listen_fd >= 0){
			close(data->listen_fd);
		}
		if(data->dest_fd >= 0){
			close(data->dest_fd);
		}

		//free all buffers
		for(p = 0; p < data->buffers; p++){
			free(data->buffer[p].data.u8);
		}
		free(data->buffer);

		free(data);
		inst[u]->impl = NULL;
	}

	LOG("Backend shut down");
	return 0;
}