ledctl/ledctl.c

101 lines
2.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define LEDFILE "/sys/class/leds/ACT/brightness"
//write to the led
int wrLED(int fd, int val){
char *opts[] = {"0", "1"};
return write(fd, opts[val], 1);
}
void printVersion(){
printf("ledctl 1.0\n");
}
void printUsage(char *errormsg){
if (errormsg != NULL) printf("Error: %s\n", errormsg);
printVersion();
printf("Usage:\n");
printf(" ledctl -v print version information\n");
printf(" ledctl -h print this message\n");
printf(" ledctl on|off turn the LED on or off\n");
printf(" ledctl 1|0\n");
printf(" ledctl -r REPEAT -s VALUE TIMING [-s VALUE TIMING ...]\n");
}
int main(int argc, char *argv[]){
if (argc < 2) return 1;
char path[] = LEDFILE;
int fd = open(path, O_RDWR);
if (strcmp(argv[1], "on") == 0 || strcmp(argv[1], "1") == 0){
wrLED(fd, 1);
close(fd);
return 0;
}
if (strcmp(argv[1], "off") == 0 || strcmp(argv[1], "0") == 0){
wrLED(fd, 0);
close(fd);
return 0;
}
if (strcmp(argv[1], "-v") == 0 && argc == 2){
printVersion(NULL);
close(fd);
return 0;
}
if (strcmp(argv[1], "-h") == 0 && argc == 2){
printUsage(NULL);
close(fd);
return 0;
}
if (strcmp(argv[1], "-r") != 0 || argc < 6 || (argc % 3) != 0){
printUsage(NULL);
close(fd);
return 1;
}
if (argc % 3 !=0) {
printUsage("Invalid number of arguments");
close(fd);
return 1;
}
// keep track of previous state
char prev;
read(fd, &prev, 1);
int pattern_repetitions = atoi(argv[2]);
char **args_pattern = &argv[3];
int pattern_steps = (argc-3) / 3;
int pattern_values[pattern_steps];
float pattern_timing[pattern_steps];
//parse arguments into our schema
for (int i=0; i < pattern_steps; i++){
int args_pattern_index = i*3;
if (strcmp(args_pattern[args_pattern_index], "-s") != 0){
printUsage("Invalid format for -s flag");
close(fd);
return 1;
}
pattern_values[i] = atoi(args_pattern[args_pattern_index + 1]);
pattern_timing[i] = atof(args_pattern[args_pattern_index + 2]);
}
for (int i = 0; i < pattern_repetitions; i++) {
for (int pstep = 0; pstep < pattern_steps; pstep++) {
wrLED(fd, pattern_values[pstep]);
usleep(1000000 * pattern_timing[pstep]);
}
}
write(fd, &prev, 1);
close(fd);
}