forked from osresearch/LEDscape
-
Notifications
You must be signed in to change notification settings - Fork 58
/
opc-server.c
executable file
·2169 lines (1751 loc) · 64.4 KB
/
opc-server.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
/** \file
* OPC image packet receiver.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <fcntl.h>
#include <termios.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <inttypes.h>
#include <errno.h>
#include <string.h>
#include <math.h>
#include <getopt.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <sys/mman.h>
#include "util.h"
#include "ledscape.h"
#include "lib/cesanta/net_skeleton.h"
#include "lib/cesanta/frozen.h"
#include <pthread.h>
#include <stdbool.h>
// TODO:
// Server:
// - ip-stack Agnostic socket stuff
// - UDP receiver
// Config:
// - White-balance, curve adjustment
// - Respecting interpolation and dithering settings
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DEFINES, CONSTANTS and UTILS
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#define TRUE 1
#define FALSE 0
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
#define mint(t, a, b) ((t) (a) < (t) (b) ? (a) : (b))
#define maxt(t, a, b) ((t) (a) > (t) (b) ? (a) : (b))
static const int MAX_CONFIG_FILE_LENGTH_BYTES = 1024*1024*10;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TYPES
typedef enum {
DEMO_MODE_NONE = 0,
DEMO_MODE_FADE = 1,
DEMO_MODE_IDENTIFY = 2,
DEMO_MODE_BLACK = 3,
DEMO_MODE_POWER = 4 ,
DEMO_MODE_REDBEAT = 5
} demo_mode_t;
typedef struct {
char output_mode_name[512];
char output_mapping_name[512];
demo_mode_t demo_mode;
uint16_t tcp_port;
uint16_t udp_port;
uint16_t e131_port;
uint32_t leds_per_strip;
uint32_t used_strip_count;
color_channel_order_t color_channel_order;
uint8_t interpolation_enabled;
uint8_t dithering_enabled;
uint8_t lut_enabled;
struct {
float red;
float green;
float blue;
} white_point;
float lum_power;
pthread_mutex_t mutex;
char json[4096];
} server_config_t;
char g_config_filename[4096] = {0};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Method declarations
void teardown_server();
void ensure_server_setup();
// Frame Manipulation
void ensure_frame_data();
void set_next_frame_data(uint8_t* frame_data, uint32_t data_size, uint8_t is_remote);
void rotate_frames(uint8_t lock_frame_data);
// Threads
void* render_thread(void* threadarg);
void* udp_server_thread(void* threadarg);
void* tcp_server_thread(void* threadarg);
void* e131_server_thread(void* threadarg);
void* demo_thread(void* threadarg);
// Config Methods
void build_lookup_tables();
int validate_server_config(
server_config_t* input_config,
char * result_json_buffer,
size_t result_json_buffer_size
);
int server_config_from_json(
const char* json,
size_t json_size,
server_config_t* output_config
) ;
void server_config_to_json(char* dest_string, size_t dest_string_size, server_config_t* input_config) ;
const char* demo_mode_to_string(demo_mode_t mode) {
switch (mode) {
case DEMO_MODE_NONE: return "none";
case DEMO_MODE_FADE: return "fade";
case DEMO_MODE_IDENTIFY: return "id";
case DEMO_MODE_BLACK: return "black";
case DEMO_MODE_POWER: return "power";
case DEMO_MODE_REDBEAT: return "redbeat";
default: return "<invalid demo_mode>";
}
}
demo_mode_t demo_mode_from_string(const char* str) {
if (strcasecmp(str, "none") == 0) {
return DEMO_MODE_NONE;
} else if (strcasecmp(str, "id") == 0) {
return DEMO_MODE_IDENTIFY;
} else if (strcasecmp(str, "fade") == 0) {
return DEMO_MODE_FADE;
} else if (strcasecmp(str, "black") == 0) {
return DEMO_MODE_BLACK;
} else if (strcasecmp(str, "power") == 0) {
return DEMO_MODE_POWER;
} else if (strcasecmp(str, "redbeat") == 0) {
return DEMO_MODE_REDBEAT;
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Error Handling
typedef enum {
OPC_SERVER_ERR_NONE,
OPC_SERVER_ERR_NO_JSON,
OPC_SERVER_ERR_INVALID_JSON,
OPC_SERVER_ERR_FILE_READ_FAILED,
OPC_SERVER_ERR_FILE_WRITE_FAILED,
OPC_SERVER_ERR_FILE_TOO_LARGE,
OPC_SERVER_ERR_SEEK_FAILED
} opc_error_code_t;
__thread opc_error_code_t g_error_code = 0;
__thread char g_error_info_str[4096];
const char* opc_server_strerr(
opc_error_code_t error_code
) {
switch (error_code) {
case OPC_SERVER_ERR_NONE: return "No error";
case OPC_SERVER_ERR_NO_JSON: return "No JSON document given";
case OPC_SERVER_ERR_INVALID_JSON: return "Invalid JSON document given";
default: return "Unkown Error";
}
}
inline int opc_server_set_error(
opc_error_code_t error_code,
const char* extra_info,
...
) {
g_error_code = error_code;
if (extra_info == NULL || strlen(extra_info) == 0) {
strlcpy(
g_error_info_str,
opc_server_strerr(error_code),
sizeof(g_error_info_str)
);
} else {
char extra_info_out[2048];
snprintf(
extra_info_out,
sizeof(extra_info_out),
extra_info,
__builtin_va_arg_pack()
);
snprintf(
extra_info_out,
sizeof(g_error_info_str),
"%s: %s",
opc_server_strerr(error_code),
extra_info
);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Global Data
server_config_t g_server_config = {
.output_mode_name = "ws281x",
.output_mapping_name = "original-ledscape",
.demo_mode = DEMO_MODE_FADE,
.tcp_port = 7890,
.udp_port = 7890,
.e131_port = 5568,
.leds_per_strip = 176,
.used_strip_count = LEDSCAPE_NUM_STRIPS,
.color_channel_order = COLOR_ORDER_BRG,
.interpolation_enabled = TRUE,
.dithering_enabled = TRUE,
.lut_enabled = TRUE,
.white_point = { .9, 1, 1},
.lum_power = 2,
.mutex = PTHREAD_MUTEX_INITIALIZER
};
typedef struct {
uint8_t r;
uint8_t g;
uint8_t b;
} __attribute__((__packed__)) buffer_pixel_t;
// Pixel Delta
typedef struct {
int8_t r;
int8_t g;
int8_t b;
int8_t last_effect_frame_r;
int8_t last_effect_frame_g;
int8_t last_effect_frame_b;
} __attribute__((__packed__)) pixel_delta_t;
// Global runtime data
static struct
{
buffer_pixel_t* previous_frame_data;
buffer_pixel_t* current_frame_data;
buffer_pixel_t* next_frame_data;
pixel_delta_t* frame_dithering_overflow;
uint8_t has_prev_frame;
uint8_t has_current_frame;
uint8_t has_next_frame;
uint32_t frame_size;
uint32_t leds_per_strip;
volatile uint32_t frame_counter;
struct timeval previous_frame_tv;
struct timeval current_frame_tv;
struct timeval next_frame_tv;
struct timeval prev_current_delta_tv;
ledscape_t * leds;
char pru0_program_filename[4096];
char pru1_program_filename[4096];
uint32_t red_lookup[257];
uint32_t green_lookup[257];
uint32_t blue_lookup[257];
struct timeval last_remote_data_tv;
pthread_mutex_t mutex;
} g_runtime_state = {
.previous_frame_data = (buffer_pixel_t*)NULL,
.current_frame_data = (buffer_pixel_t*)NULL,
.next_frame_data = (buffer_pixel_t*)NULL,
.has_prev_frame = FALSE,
.has_current_frame = FALSE,
.has_next_frame = FALSE,
.frame_dithering_overflow = (pixel_delta_t*)NULL,
.frame_size = 0,
.leds_per_strip = 0,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.last_remote_data_tv = {
.tv_sec = 0,
.tv_usec = 0
},
.leds = NULL
};
// Global thread handles
typedef struct {
pthread_t handle;
bool enabled;
bool running;
} thread_state_lt;
static struct
{
thread_state_lt render_thread;
thread_state_lt tcp_server_thread;
thread_state_lt udp_server_thread;
thread_state_lt e131_server_thread;
thread_state_lt demo_thread;
} g_threads = {
{NULL, false, false},
{NULL, false, false},
{NULL, false, false},
{NULL, false, false},
{NULL, false, false}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// main()
static struct option long_options[] =
{
{"tcp-port", required_argument, NULL, 'p'},
{"udp-port", required_argument, NULL, 'P'},
{"e131-port", required_argument, NULL, 'e'},
{"count", required_argument, NULL, 'c'},
{"strip-count", required_argument, NULL, 's'},
{"dimensions", required_argument, NULL, 'd'},
{"channel-order", required_argument, NULL, 'o'},
{"demo-mode", required_argument, NULL, 'D'},
{"no-interpolation", no_argument, NULL, 'i'},
{"no-dithering", no_argument, NULL, 't'},
{"no-lut", no_argument, NULL, 'l'},
{"help", no_argument, NULL, 'h'},
{"lum_power", required_argument, NULL, 'L'},
{"red_bal", required_argument, NULL, 'r'},
{"green_bal", required_argument, NULL, 'g'},
{"blue_bal", required_argument, NULL, 'b'},
{"pru0_mode", required_argument, NULL, '0'},
{"pru1_mode", required_argument, NULL, '1'},
{"mode", required_argument, NULL, 'm'},
{"mapping", required_argument, NULL, 'M'},
{"config", required_argument, NULL, 'C'},
{NULL, 0, NULL, 0}
};
void set_pru_mode_and_mapping_from_legacy_output_mode_name(const char* input) {
if (strcasecmp(input, "NOP") == 0) {
strcpy(g_server_config.output_mode_name, "nop");
strcpy(g_server_config.output_mapping_name, "original-ledscape");
}
else if (strcasecmp(input, "DMX") == 0) {
strcpy(g_server_config.output_mode_name, "dmx");
strcpy(g_server_config.output_mapping_name, "original-ledscape");
}
else if (strcasecmp(input, "WS2801") == 0) {
strcpy(g_server_config.output_mode_name, "ws2801");
strcpy(g_server_config.output_mapping_name, "original-ledscape");
}
else if (strcasecmp(input, "WS2801_NEWPINS") == 0) {
strcpy(g_server_config.output_mode_name, "ws2801");
strcpy(g_server_config.output_mapping_name, "rgb-123-v2");
}
else /*if (strcasecmp(input, "WS281x") == 0)*/ {
// The default case is to use ws281x
strcpy(g_server_config.output_mode_name, "ws281x");
strcpy(g_server_config.output_mapping_name, "original-ledscape");
}
fprintf(stderr,
"WARNING: PRU mode set using legacy -0 or -1 flags; please update to use --mode and --mapping.\n"
" '%s' interpreted as mode '%s' and mapping '%s'\n",
input,
g_server_config.output_mode_name,
g_server_config.output_mapping_name
);
}
void print_usage(char ** argv) {
printf("Usage: %s ", argv[0]);
int option_count = sizeof(long_options) / sizeof(struct option);
for (int option_index = 0; option_index < option_count; option_index++) {
struct option option_info = long_options[option_index];
if (option_info.name != NULL) {
if (option_info.has_arg == required_argument) {
printf("[--%s <val> | -%c <val>] ", option_info.name, option_info.val);
} else if (option_info.has_arg == optional_argument) {
printf("[--%s[=<val>] | -%c[<val>] ", option_info.name, option_info.val);
} else {
printf("[--%s | -%c] ", option_info.name, option_info.val);
}
}
}
printf("\n");
}
int read_config_file(
const char * config_filename,
server_config_t* out_config
) {
// Map the file for reading
int fd = open(config_filename, O_RDONLY);
if (fd < 0) {
return opc_server_set_error(
OPC_SERVER_ERR_FILE_READ_FAILED,
"Failed to open config file %s for reading: %s\n",
config_filename,
strerror(errno)
);
}
off_t file_end_offset = lseek(fd, 0, SEEK_END);
if (file_end_offset < 0) {
return opc_server_set_error(
OPC_SERVER_ERR_SEEK_FAILED,
"Failed to seek to end of %s.\n",
config_filename
);
}
if (file_end_offset > MAX_CONFIG_FILE_LENGTH_BYTES) {
return opc_server_set_error(
OPC_SERVER_ERR_FILE_TOO_LARGE,
"Failed to open config file %s: file is larger than 10MB.\n",
config_filename
);
}
size_t file_length = (size_t) file_end_offset;
void *data = mmap(0, file_length, PROT_READ, MAP_PRIVATE, fd, 0);
// Read the config
// TODO: Handle character encoding?
char* str_data = malloc(file_length + 1);
memcpy(str_data, data, file_length);
str_data[file_length] = 0;
server_config_from_json(str_data, strlen(str_data), out_config);
free(str_data);
// Unmap the data
munmap(data, file_length);
return close(fd);
}
int write_config_file(
const char* config_filename,
server_config_t* config
) {
FILE* fd = fopen(config_filename, "w");
if (fd == NULL) {
return opc_server_set_error(
OPC_SERVER_ERR_FILE_WRITE_FAILED,
"Failed to open config file %s for reading: %s\n",
config_filename,
strerror(errno)
);
}
char json_buffer[4096] = {0};
server_config_to_json(json_buffer, sizeof(json_buffer), config);
fputs(json_buffer, fd);
return fclose(fd);
}
void handle_args(int argc, char ** argv) {
extern char *optarg;
int opt;
while ((opt = getopt_long(argc, argv, "p:P:c:s:d:D:o:ithlL:r:g:b:0:1:m:M:", long_options, NULL)) != -1)
{
switch (opt)
{
case 'p': {
g_server_config.tcp_port = (uint16_t) atoi(optarg);
} break;
case 'P': {
g_server_config.udp_port = (uint16_t) atoi(optarg);
} break;
case 'e': {
g_server_config.e131_port = (uint16_t) atoi(optarg);
} break;
case 'c': {
g_server_config.leds_per_strip = (uint32_t) atoi(optarg);
} break;
case 's': {
g_server_config.used_strip_count = (uint32_t) atoi(optarg);
} break;
case 'd': {
int width=0, height=0;
if (sscanf(optarg,"%dx%d", &width, &height) == 2) {
g_server_config.leds_per_strip = (uint32_t) (width * height);
} else {
printf("Invalid argument for -d; expected NxN; actual: %s", optarg);
exit(EXIT_FAILURE);
}
} break;
case 'D': {
g_server_config.demo_mode = demo_mode_from_string(optarg);
} break;
case 'o': {
g_server_config.color_channel_order = color_channel_order_from_string(optarg);
} break;
case 'i': {
g_server_config.interpolation_enabled = FALSE;
} break;
case 't': {
g_server_config.dithering_enabled = FALSE;
} break;
case 'l': {
g_server_config.lut_enabled = FALSE;
} break;
case 'L': {
g_server_config.lum_power = (float) atof(optarg);
} break;
case 'r': {
g_server_config.white_point.red = (float) atof(optarg);
} break;
case 'g': {
g_server_config.white_point.green = (float) atof(optarg);
} break;
case 'b': {
g_server_config.white_point.blue = (float) atof(optarg);
} break;
case '0': {
set_pru_mode_and_mapping_from_legacy_output_mode_name(optarg);
} break;
case '1': {
set_pru_mode_and_mapping_from_legacy_output_mode_name(optarg);
} break;
case 'm': {
strlcpy(g_server_config.output_mode_name, optarg, sizeof(g_server_config.output_mode_name));
} break;
case 'M': {
strlcpy(g_server_config.output_mapping_name, optarg, sizeof(g_server_config.output_mapping_name));
} break;
case 'C': {
strlcpy(g_config_filename, optarg, sizeof(g_config_filename));
if (read_config_file(g_config_filename, &g_server_config) >= 0) {
fprintf(stderr, "Loaded config file from %s.\n", g_config_filename);
} else {
fprintf(stderr, "Config file not loaded: %s\n", g_error_info_str);
}
} break;
case 'h': {
print_usage(argv);
printf("\n");
int option_count = sizeof(long_options) / sizeof(struct option);
for (int option_index = 0; option_index < option_count; option_index++) {
struct option option_info = long_options[option_index];
if (option_info.name != NULL) {
if (option_info.has_arg == required_argument) {
printf("--%s <val>, -%c <val>\n\t", option_info.name, option_info.val);
} else if (option_info.has_arg == optional_argument) {
printf("--%s[=<val>], -%c[<val>]\n\t", option_info.name, option_info.val);
} else {
printf("--%s, -%c\n", option_info.name, option_info.val);
}
switch (option_info.val) {
case 'p': printf("The TCP port to listen for OPC data on"); break;
case 'P': printf("The UDP port to listen for OPC data on"); break;
case 'e': printf("The UDP port to listen for e131 data on"); break;
case 'c': printf("The number of pixels connected to each output channel"); break;
case 's': printf("The number of used output channels (improves performance by not interpolating/dithering unused channels)"); break;
case 'd': printf("Alternative to --count; specifies pixel count as a dimension, e.g. 16x16 (256 pixels)"); break;
case 'D':
printf("Configures the idle (demo) mode which activates when no data arrives for more than 5 seconds. Modes:\n");
printf("\t- none Do nothing; leaving LED colors as they were\n");
printf("\t- black Turn off all LEDs");
printf("\t- fade Display a rainbow fade across all LEDs\n");
printf("\t- id Send the channel index as all three color values or 0xAA (0b10101010) if channel and pixel index are equal");
printf("\t- power Turn on all LEDs (good for checking max power requirements)");
printf("\t- redbeat 1 second red pulse every minute (good for indicating network error)");
break;
case 'o':
printf("Specifies the color channel output order (RGB, RBG, GRB, GBR, BGR or BRG); default is BRG.");
break;
case 'i': printf("Disables interpolation between frames (choppier output but improves performance)"); break;
case 't': printf("Disables dithering (choppier output but improves performance)"); break;
case 'l': printf("Disables luminance correction (lower color values appear brighter than they should)"); break;
case 'L': printf("Sets the exponent of the luminance power function to the given floating point value (default 2)"); break;
case 'r': printf("Sets the red balance to the given floating point number (0-1, default .9)"); break;
case 'g': printf("Sets the red balance to the given floating point number (0-1, default 1)"); break;
case 'b': printf("Sets the red balance to the given floating point number (0-1, default 1)"); break;
case '0': printf("[deprecated] Sets the PRU0 program. Use --mode and --mapping instead."); break;
case '1': printf("[deprecated] Sets the PRU1 program. Use --mode and --mapping instead."); break;
case 'm':
printf("Sets the output mode:\n");
printf("\t- nop Disable output; can be useful for debugging\n");
printf("\t- ws281x WS2811/WS2812 output format\n");
printf("\t- ws2801 WS2801-compatible 8-bit SPI output. Supports 24 channels of output with pins in a DATA/CLOCK configuration.\n");
printf("\t- dmx DMX compatible output (does not support RDM)\n");
break;
case 'M':
printf("Sets the pin mapping used:\n");
printf("\toriginal-ledscape: Original LEDscape pinmapping. Used on older RGB-123 capes.\n");
printf("\trgb-123-v2: RGB-123 mapping for new capes\n");
break;
case 'C':
printf("Specifies a configuration file to use and creates it if it does not already exist.\n");
printf("\tIf used with other options, options are parsed in order. Options before --config are overwritten\n");
printf("\tby the config file, and options afterwards will be saved to the config file.\n");
break;
case 'h': printf("Displays this help message"); break;
default: printf("Undocumented option: %c\n", option_info.val);
}
printf("\n");
}
}
printf("\n");
exit(EXIT_SUCCESS);
}
default:
printf("Invalid option: %c\n\n", opt);
print_usage(argv);
printf("\nUse -h or --help for more information\n\n");
exit(EXIT_FAILURE);
}
}
}
int main(int argc, char ** argv)
{
char validation_output_buffer[1024*1024];
handle_args(argc, argv);
// Validate the configuration
if (validate_server_config(
& g_server_config,
validation_output_buffer,
sizeof(validation_output_buffer)
) != 0) {
die("ERROR: Configuration failed validation:\n%s",
validation_output_buffer
);
}
// Save the config file if specified
if (strlen(g_config_filename) > 0) {
if (write_config_file(
g_config_filename,
&g_server_config
) >= 0) {
fprintf(stderr, "Config file written to %s\n", g_config_filename);
} else {
fprintf(stderr, "Failed to write to config file %s: %s\n", g_config_filename, g_error_info_str);
}
}
fprintf(stderr,
"[main] Starting server on ports (tcp=%d, udp=%d) for %d pixels on %d strips\n",
g_server_config.tcp_port, g_server_config.udp_port, g_server_config.leds_per_strip, LEDSCAPE_NUM_STRIPS
);
pthread_create(&g_threads.render_thread, NULL, render_thread, NULL);
pthread_create(&g_threads.udp_server_thread, NULL, udp_server_thread, NULL);
pthread_create(&g_threads.tcp_server_thread, NULL, tcp_server_thread, NULL);
pthread_create(&g_threads.e131_server_thread, NULL, e131_server_thread, NULL);
if (g_server_config.demo_mode != DEMO_MODE_NONE) {
printf("[main] Demo Mode Enabled\n");
pthread_create(&g_threads.demo_thread, NULL, demo_thread, NULL);
} else {
printf("[main] Demo Mode Disabled\n");
}
ensure_server_setup();
pthread_exit(NULL);
}
const char* build_pruN_program_name(
const char* output_mode_name,
const char* output_mapping_name,
uint8_t pruNum,
char* out_pru_filename,
int filename_len
) {
snprintf(
out_pru_filename,
filename_len,
"pru/bin/%s-%s-pru%d.bin",
output_mode_name,
output_mapping_name,
(int) pruNum
);
return out_pru_filename;
}
void ensure_server_setup() {
printf("[main] Initializing / Updating server...");
// Setup tables
build_lookup_tables();
ensure_frame_data();
pthread_mutex_lock(&g_runtime_state.mutex);
pthread_mutex_lock(&g_server_config.mutex);
// Determine if we need to [re]initialize LEDscape
bool ledscape_init_needed = false;
if (g_runtime_state.leds == NULL) {
ledscape_init_needed = true;
}
else if (g_runtime_state.leds_per_strip != g_server_config.leds_per_strip) {
ledscape_init_needed = true;
}
else if (g_runtime_state.pru1_program_filename == NULL || g_runtime_state.pru0_program_filename == NULL) {
ledscape_init_needed = true;
}
else {
char pru0_filename_temp[4096],
pru1_filename_temp[4096];
build_pruN_program_name(
g_server_config.output_mode_name,
g_server_config.output_mapping_name,
0,
pru0_filename_temp,
sizeof(pru0_filename_temp)
);
build_pruN_program_name(
g_server_config.output_mode_name,
g_server_config.output_mapping_name,
1,
pru1_filename_temp,
sizeof(pru1_filename_temp)
);
if (strcasecmp(pru0_filename_temp, g_runtime_state.pru0_program_filename) != 0 ||
strcasecmp(pru1_filename_temp, g_runtime_state.pru1_program_filename) != 0) {
ledscape_init_needed = true;
}
}
if (ledscape_init_needed) {
if (g_runtime_state.leds != NULL) {
printf("[main] Closing LEDscape...");
ledscape_close(g_runtime_state.leds);
g_runtime_state.leds = NULL;
}
// Init LEDscape
printf("[main] Starting LEDscape...");
g_runtime_state.leds = ledscape_init_with_programs(
g_server_config.leds_per_strip,
build_pruN_program_name(
g_server_config.output_mode_name,
g_server_config.output_mapping_name,
0,
g_runtime_state.pru0_program_filename,
sizeof(g_runtime_state.pru0_program_filename)
),
build_pruN_program_name(
g_server_config.output_mode_name,
g_server_config.output_mapping_name,
1,
g_runtime_state.pru1_program_filename,
sizeof(g_runtime_state.pru1_program_filename)
)
);
g_runtime_state.leds_per_strip = g_server_config.leds_per_strip;
}
pthread_mutex_unlock(&g_server_config.mutex);
pthread_mutex_unlock(&g_runtime_state.mutex);
// Display server config as JSON
char json_buffer[4096] = { 0 };
server_config_to_json(json_buffer, sizeof(json_buffer), &g_server_config);
fputs(json_buffer, stderr);
}
int validate_server_config(
server_config_t* input_config,
char * result_json_buffer,
size_t result_json_buffer_size
) {
strlcpy(result_json_buffer, "{\n\t\"errors\": [", result_json_buffer_size);
char path_temp[4096];
int error_count = 0;
inline void result_append(const char *format, ...) {
snprintf(
result_json_buffer + strlen(result_json_buffer),
result_json_buffer_size - strlen(result_json_buffer) + 1,
format,
__builtin_va_arg_pack()
);
}
inline void add_error(const char *format, ...) {
// Can't call result_append here because it breaks gcc:
// internal compiler error: in initialize_inlined_parameters, at tree-inline.c:2795
snprintf(
result_json_buffer + strlen(result_json_buffer),
result_json_buffer_size - strlen(result_json_buffer) + 1,
format,
__builtin_va_arg_pack()
);
error_count ++;
}
inline void assert_enum_valid(const char *var_name, int value) {
if (value < 0) {
add_error(
"\n\t\t\"" "Invalid %s" "\",",
var_name
);
}
}
inline void assert_int_range_inclusive(const char *var_name, int min_val, int max_val, int value) {
if (value < min_val || value > max_val) {
add_error(
"\n\t\t\"" "Given %s (%d) is outside of range %d-%d (inclusive)" "\",",
var_name,
value,
min_val,
max_val
);
}
}
inline void assert_double_range_inclusive(const char *var_name, double min_val, double max_val, double value) {
if (value < min_val || value > max_val) {
add_error(
"\n\t\t\"" "Given %s (%f) is outside of range %f-%f (inclusive)" "\",",
var_name,
value,
min_val,
max_val
);
}
}
{ // outputMode and outputMapping
for (int pruNum=0; pruNum < 2; pruNum++) {
build_pruN_program_name(
input_config->output_mode_name,
input_config->output_mapping_name,
pruNum,
path_temp,
sizeof(path_temp)
);
if( access( path_temp, R_OK ) == -1 ) {
add_error(
"\n\t\t\"" "Invalid mapping and/or mode name; cannot access PRU %d program '%s'" "\",",
pruNum,
path_temp
);
}
}
}
// demoMode
assert_enum_valid("Demo Mode", input_config->demo_mode);
// ledsPerStrip
assert_int_range_inclusive("LED Count", 1, 1024, input_config->leds_per_strip);
// usedStripCount
assert_int_range_inclusive("Strip/Channel Count", 1, 48, input_config->used_strip_count);
// colorChannelOrder
assert_enum_valid("Color Channel Order", input_config->color_channel_order);
// opcTcpPort
assert_int_range_inclusive("OPC TCP Port", 1, 65535, input_config->tcp_port);
// opcUdpPort
assert_int_range_inclusive("OPC UDP Port", 1, 65535, input_config->udp_port);
// e131Port
assert_int_range_inclusive("e131 UDP Port", 1, 65535, input_config->e131_port);
// lumCurvePower
assert_double_range_inclusive("Luminance Curve Power", 0, 10, input_config->lum_power);
// whitePoint.red
assert_double_range_inclusive("Red White Point", 0, 1, input_config->white_point.red);
// whitePoint.green
assert_double_range_inclusive("Green White Point", 0, 1, input_config->white_point.green);
// whitePoint.blue
assert_double_range_inclusive("Blue White Point", 0, 1, input_config->white_point.blue);
if (error_count > 0) {
// Strip off trailing comma
result_json_buffer[strlen(result_json_buffer)-1] = 0;
result_append("\n\t],\n");
} else {
// Reset the output to not include the error messages
if (result_json_buffer_size > 0) {
result_json_buffer[0] = 0;
}
result_append("{\n");
}
// Add closing json
result_append("\t\"valid\": %s\n", error_count == 0 ? "true" : "false");
result_append("}");
return error_count;
}
int server_config_from_json(
const char* json,
size_t json_size,
server_config_t* output_config
) {
struct json_token *json_tokens;