forked from lawrie/piglowd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
piglowd.c
704 lines (609 loc) · 16.8 KB
/
piglowd.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
#include <fcntl.h>
#include <ctype.h>
#include <time.h>
#include <stdarg.h>
#include <wiringPi.h>
#include <piGlow.h>
#define MAX_INDEX 3
#define TRUE 1
#define FALSE 0
#define OPCODE_FOR 0
#define OPCODE_RING 1
#define OPCODE_LEG 2
#define OPCODE_LED 3
#define OPCODE_DELAY 4
#define OPCODE_RANDOM 5
#define OPCODE_ASSIGN 6
struct instruction {
unsigned char opcode;
int p1;
int p2;
int p3;
int p4;
};
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int pattern = -1, fd, lt, np=0, is_daemon = FALSE, verbose=FALSE, stepping=FALSE;
static char**tokens;
// Test for all digits
static int is_numeric(char *str)
{
while(*str)
{
if(!isdigit(*str))
return 0;
str++;
}
return 1;
}
// Open the input fifo
static int open_fifo(void)
{
char fifo_name[] = "/tmp/piglowfifo";
struct stat st;
// If created as a normal file, delete it
if (stat(fifo_name, &st) == 0 && !S_ISFIFO(st.st_mode))
remove(fifo_name);
if (stat(fifo_name, &st) != 0)
mkfifo(fifo_name, 0666);
fd= open(fifo_name, O_RDONLY | O_NONBLOCK);
return fd;
}
// Read a single character command or a pattern number from the FIFO
static int read_fifo(void) {
char buf[1];
if (read(fd, &buf, 1) > 0)
{
if (buf[0] < 32) return -1;
if (buf[0] >= '0' && buf[0] <= '9') return buf[0] - '0';
else if (buf[0] >= 'a' && buf[0] <= 'f') return (buf[0] - 'a' + 10);
else return buf[0];
}
else return -1;
}
// Send an error message to the daemon log or console
static void error(char *msg, ...)
{
char str[100];
va_list args;
va_start( args, msg );
vsprintf( str, msg, args );
va_end( args );
if (is_daemon) syslog(LOG_NOTICE, str);
else printf(str);
}
// Log an information message to the daemoon log or console
static void log_msg(char *msg, ...)
{
char str[100];
va_list args;
va_start( args, msg );
vsprintf( str, msg, args );
va_end( args );
if (is_daemon) syslog(LOG_NOTICE, str);
else printf(str);
}
// Become a daemon
static void become_daemon()
{
pid_t pid;
int pidFilehandle;
char* pidfile = "/tmp/piglowd.pid";
char str[10];
/* Fork off the parent process */
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* On success: The child process becomes session leader */
if (setsid() < 0)
exit(EXIT_FAILURE);
/* Catch, ignore and handle signals */
//TODO: Implement a working signal handler */
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
/* Fork off for the second time*/
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* Set new file permissions */
umask(0);
/* Change the working directory to the root directory */
/* or another appropriated directory */
chdir("/");
/* Close all open file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Open the log file */
openlog ("pilogd", LOG_PID, LOG_DAEMON);
is_daemon = TRUE;
/* Ensure only one copy */
pidFilehandle = open(pidfile, O_RDWR|O_CREAT, 0600);
if (pidFilehandle == -1 )
{
/* Couldn't open lock file */
log_msg("Could not open PID lock file %s, exiting", pidfile);
exit(EXIT_FAILURE);
}
/* Try to lock file */
if (lockf(pidFilehandle,F_TLOCK,0) == -1)
{
/* Couldn't get lock on lock file */
log_msg("Could not lock PID lock file %s, exiting", pidfile);
exit(EXIT_FAILURE);
}
/* Get and format PID */
sprintf(str,"%d\n",getpid());
/* write pid to lockfile */
write(pidFilehandle, str, strlen(str));
}
// Read the patterns from the config file
static char** read_config(void)
{
int lines_allocated = 5;
int max_line_len = 200;
/* Allocate lines of text */
char **words = (char **)malloc(sizeof(char*)*lines_allocated);
if (words==NULL)
{
fprintf(stderr,"Out of memory (1).\n");
exit(EXIT_FAILURE);
}
FILE *fp = fopen("/etc/piglowd/piglowd.conf", "r");
if (fp == NULL)
{
fprintf(stderr,"Error opening file.\n");
exit(EXIT_FAILURE);
}
int i;
for (i=0;1;i++)
{
int j;
char *r = NULL;
/* Have we gone over our line allocation? */
if (i >= lines_allocated)
{
int new_size;
/* Double our allocation and re-allocate */
new_size = lines_allocated*2;
words = (char **)realloc(words,sizeof(char*)*new_size);
if (words==NULL)
{
fprintf(stderr,"Out of memory.\n");
exit(EXIT_FAILURE);
}
lines_allocated = new_size;
}
/* Allocate space for the next line */
words[i] = malloc(max_line_len);
if (words[i]==NULL)
{
fprintf(stderr,"Out of memory (3).\n");
exit(EXIT_FAILURE);
}
for(;;)
{
r = fgets(words[i],max_line_len-1,fp);
if (r == NULL) break;
// Ignore comments
if (r[0] != '#') break;
}
if (r == NULL) break;
/* Get rid of CR or LF at end of line */
for (j=strlen(words[i])-1;j>=0 && (words[i][j]=='\n' || words[i][j]=='\r');j --);
words[i][j+1]='\0';
}
if (verbose && !is_daemon)
{
printf("There are %d patterns:\n", i);
int j;
for(j = 0; j < i; j++)
printf("%d: %s\n", j, words[j]);
}
fclose(fp);
np = i;
return words;
}
// Split a line into tokens
static char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_delim = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
char *save_ptr;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_delim = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_delim < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok_r(a_str, delim, &save_ptr);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok_r(0, delim, &save_ptr);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
// Switch off all the LEDs
static void clear(void)
{
int i;
// Switches all LEDS off
for(i=0;i<3;i++) piGlowLeg(i,0);
}
// Execute compiled instructions
static int execute(struct instruction *instructions, int level, int start, int end, int* index){
int i, j, e;
//log_msg("Executing from %d to %d at level %d with index = %d\n", start,end, level, index[level]);
for(i=start;i<end;i++)
{
struct instruction inst = instructions[i];
int opcode = inst.opcode;
int p1 = inst.p1;
int p2 = inst.p2;
int p3 = inst.p3;
int p4 = inst.p4;
pattern = read_fifo();
if (stepping)
{
if (pattern == 'g')
{
stepping = FALSE;
}
else if (pattern < 0) {
i--;
continue;
}
else if (pattern != 'n') return FALSE;
log_msg("Stepping mode, command = %c, token=%s, i=%d, j=%d, k=%d\n",pattern, tokens[i], index[0], (level > 0 ? index[1] : 0), (level > 1 ? index[2] : 0));
}
else if (pattern >= 0) return FALSE;
switch(opcode)
{
case OPCODE_FOR:
for(e=i+1;e<end && (instructions[e].opcode != OPCODE_FOR || instructions[e].p1 > p1);e++);
for(j=p2;(p2 <= p3 ? j<=p3 : j>=p3);)
{
index[p1] = j;
if (!execute(instructions, p1,i+1, e, index)) return FALSE;
if (p2 <= p3) j += p4; else j-= p4;
}
i = e-1;
break;
case OPCODE_RING:
piGlowRing((p1 < 0 ? index[p1*-1 - 1] :p1) % 6,(p2 < 0 ? index[p2*-1 - 1] :p2));
break;
case OPCODE_LEG:
piGlowLeg((p1 < 0 ? index[p1*-1 -1] :p1) % 3, (p2 < 0 ? index[p2*-1 - 1] :p2));
break;
case OPCODE_LED:
piGlow1((p1 < 0 ? index[p1*-1 -1] :p1) % 3, (p2 < 0 ? index[p2*-1 -1] :p2) % 6, (p3 < 0 ? index[p3*-1 - 1] :p3));
break;
case OPCODE_DELAY:
delay((p1 < 0 ? index[p1*-1 - 1] :p1));
break;
case OPCODE_RANDOM:
index[p1] = p2 + rand() % (p3 + 1 - p2);
break;
case OPCODE_ASSIGN:
index[p1] = (p2 < 0 ? index[p2*-1 -1] :p2) - (p3 < 0 ? index[p3*-1 -1] :p3);
break;
}
}
return TRUE;
}
// Compile a pattern
struct instruction *compile(char * pattern)
{
char* pattern_copy = strdup(pattern);
tokens = str_split(pattern_copy,' ');
struct instruction * instructions = NULL;
int level=0;
if (tokens)
{
int i;
int ring, leg ;
char *token;
char **args;
char *left, *right;
char * start, *end, *increment;
char *token_copy;
char indent[5];
FILE *fp = fopen("/tmp/pattern.c", "w");
fprintf(fp,"#include <wiringPi.h\n");
fprintf(fp,"#include <piGlow.h\n");
fprintf(fp, "\nint main(void)\n{\n int i,j,k;\n\n wiringPiSetupSys();\n piGlowSetup(1);\n\n");
strcpy(indent,(level == 0 ? "" : (level == 1 ? " " : " ")));
for(lt=0;*(tokens + lt);lt++);
instructions = (struct instruction *) malloc(sizeof(struct instruction) * lt);
for (i = 0; *(tokens + i); i++)
{
token = *(tokens + i);
token_copy = strdup(token);
args = str_split(token_copy,(token[1] == '?' ? '?' : (token[1] == ':' ? ':' : '=')));
left = args[0];
right = args[1];
start = NULL;
end = NULL;
increment = NULL;
if (right != NULL)
{
args = str_split(right,',');
right = args[0];
increment = args[1];
args = str_split(right,'-');
start=args[0];
end = args[1];
}
if (*token == 'l') // Leg
{
if (strlen(token) < 4 || token[2] != '=')
{
error("Invalid leg token: %s\n",token);
return NULL;
}
leg = ((token[1] >= 'i' && token[1] <= 'k') ? (token[1] - 'h') * -1 : token[1] - '0');
if (leg < -3 || leg > 2)
{
error("Invalid leg value: %s\n",token);
return NULL;
}
instructions[i].opcode = OPCODE_LEG;
instructions[i].p1 = leg;
instructions[i].p2 = ((right[0] >= 'i' && right[0] <= 'k') ? (right[0] - 'h') * -1 : atoi(right));
if (instructions[i].p2 < -3 || instructions[i].p2 > 255)
{
error("Invalid intensity value: %s\n",token);
return NULL;
}
}
else if (*token == 'r') // Ring
{
if (strlen(token) < 4 || (token[2] != '=' && token[2] != 'l'))
{
error("Invalid ring token: %s\n",token);
return NULL;
}
ring = ((token[1] >= 'i' && token[1] <= 'k') ? (token[1] - 'h') * -1 : token[1] - '0');
if (ring < -3 || ring > 5)
{
error("Invalid ring value: %s\n", token);
return NULL;
}
if(strlen(left) == 2) // Ring only
{
instructions[i].opcode = OPCODE_RING;
instructions[i].p1 = ring;
instructions[i].p2 = ((right[0] >= 'i' && right[0] <= 'k') ? (right[0] - 'h') * -1 : atoi(right));
if (instructions[i].p2 < -3 || instructions[i].p2 > 255)
{
error("Invalid intensity value: %s\n", token);
return NULL;
}
if (ring < 0) fprintf(fp, "%s PiGlowRing(%c %c 6,%d)\n", indent, token[1], '%',instructions[i].p2);
else fprintf(fp," piGlowRing(%d,%d)\n", ring, instructions[i].p2);
}
else if (strlen(left) == 4) // Ring and leg
{
leg = ((token[3] >= 'i' && token[3] <= 'k') ? (token[3] - 'h') * -1 : token[3] - '0');
if (leg < -3 || leg > 2)
{
error("Invalid leg value: %s\n", token);
return NULL;
}
instructions[i].opcode = OPCODE_LED;
instructions[i].p1 = leg;
instructions[i].p2 = ring;
instructions[i].p3 = ((right[0] >= 'i' && right[0] <= 'k') ? (right[0] - 'h') * -1 : atoi(right));
if (instructions[i].p3 < -3 || instructions[i].p3 > 255)
{
error("Invalid intensity value: %s\n", token);
return NULL;
}
}
else
{
error("Invalid ring token (left length): %s\n", token);
return NULL;
}
}
else if (*token >= 'i' && *token <= 'k') // Variable
{
if (token[1] == '?') // Random value
{
instructions[i].opcode = OPCODE_RANDOM;
instructions[i].p1 = *token - 'i';
instructions[i].p2 = atoi(start);
instructions[i].p3 = atoi(end);
}
else if (token[1] == ':') // Assignment (subtraction)
{
instructions[i].opcode = OPCODE_ASSIGN;
instructions[i].p1 = *token - 'i';
instructions[i].p2 = ((start[0] >= 'i' && start[0] <= 'k') ? (start[0] - 'h') * -1 : atoi(start));
instructions[i].p3 = ((end[0] >= 'i' && end[0] <= 'k') ? (end[0] - 'h') * -1 : atoi(end));
}
else
{
if (token[1] != '=') // For loop
{
error("Invalid loop token: %s\n", token);
return NULL;
}
if (start != NULL && !is_numeric(start))
{
error("Invalid start loop value: %s\n", token);
return NULL;
}
if (end != NULL && !is_numeric(end))
{
error("Invalid end loop value: %s\n", token);
return NULL;
}
if (increment != NULL && !is_numeric(increment))
{
error("Invalid increment loop value: %s\n", token);
return NULL;
}
instructions[i].opcode = OPCODE_FOR;
instructions[i].p1 = *token - 'i';
instructions[i].p2 = (start == NULL ? 0 : atoi(start));
instructions[i].p3 = (end == NULL ? 1000000 : atoi(end));
instructions[i].p4 = (increment == NULL ? 1 : atoi(increment));
level = *token - 'i';
fprintf(fp,"%s for(%c=%d;%c<=%d;i++)\n",indent,*token,instructions[i].p2,*token,instructions[i].p3);
fprintf(fp,"%s {\n",indent);
}
}
else if (*token == 'd') // Delay
{
if (!is_numeric(&token[1]) && (strlen(token) > 2 || token[1] < 'i' || token[1] > 'k'))
{
error("Invalid delay token: %s\n", token);
return NULL;
}
instructions[i].opcode = OPCODE_DELAY;
instructions[i].p1 = ((token[1] >= 'i' && token[1] <= 'k') ? (token[1] - 'h') * -1 : atoi(&token[1]));
fprintf(fp,"%s delay(%d)\n", indent, instructions[i].p1);
}
else
{
error("Invalid token: %s\n", token);
return NULL;
}
free(token_copy);
}
free(pattern_copy);
fprintf(fp,"}\n");
fclose(fp);
}
return instructions;
}
// Main entry point
int main (int argc, char *argv[])
{
char** patterns;
struct instruction * instructions;
int index[MAX_INDEX];
int i;
int make_daemon = TRUE;
index[0] = 0;
// Process args
for (i = 1; i < argc; i++) /* Skip argv[0] (program name). */
{
if (strcmp(argv[i], "-v") == 0)
{
verbose = TRUE;
}
else if (strcmp(argv[i], "-p") == 0)
{
make_daemon = FALSE;
pattern = atoi(argv[++i]);
}
}
srand((unsigned int) time(NULL));
wiringPiSetupSys () ;
piGlowSetup (1) ;
patterns = read_config();
fd = open_fifo();
if (make_daemon)
{
become_daemon();
log_msg("Starting piglowd daemon");
}
for(;;)
{
if (pattern < 0) pattern = read_fifo();
if (pattern < 0)
{
delay(500);
continue;
}
if (pattern == 'x') break;
else if (pattern == 'q')
{
clear();
pattern = -1;
continue;
} else if (pattern== 'r') {
clear();
pattern = -1;
patterns = read_config();
continue;
} else if (pattern == 's') {
stepping = TRUE;
pattern = -1;
continue;
}
if (pattern >= np) {
log_msg("Invalid pattern number: %d\n", pattern);
pattern = -1;
continue;
}
instructions = compile(patterns[pattern]);
if (instructions == NULL)
{
pattern = -1;
continue;
}
log_msg("Executing pattern %d : %s\n", pattern, patterns[pattern]);
pattern = -1;
clear();
execute(instructions,0,0,lt,index);
log_msg("Finished pattern\n");
clear();
free(instructions);
for(i=0;*(tokens +i);i++) free(tokens[i]);
free(tokens);
if (!is_daemon) break;
}
clear();
close(fd);
remove("/tmp/piglowfifo");
if (is_daemon)
{
log_msg("piglowd terminated.\n");
closelog();
}
return 0;
}