-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlightshow
executable file
·635 lines (482 loc) · 14.8 KB
/
lightshow
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
#!/usr/bin/perl
# POD {{{
=head1 NAME
lightshow - Manage color and dimmable LEDs
=head1 SYNOPSIS
lightshow <command> [options] [@profile]
lightshow <on|off|dim|dimest|bright|brightest>
lightshow color <color-number>
lightshow list
lightshow pair
lightshow server
lightshow <macro>
=head1 COMMANDS
=over 8
=item B<on>
Turn all lights on.
=item B<off>
Turn all lights off.
=item B<dim>
Dim all lights by one dim step.
=item B<dimest>
Dim all lights to the lowest setting.
=item B<bright>
Brighten all lights by one dim step.
=item B<dimest>
Birghten all lights to the highest setting.
=item B<color [color-number]>
Set all lights to the color code specified.
The color code must be between 0 and 255 or 'white'.
=item B<list>
List all available macros.
=item B<<macro>>
Run a Lightshow macro.
You can use 'list' to get a list of available macros.
=item B<pair>
Show pairing instructions and repeatedly send the pairing command to join a new lightbulb to the controller.
=item B<server>
Start the Lightshow REST server and listen for commands.
See SERVER for more information.
=item B<version>
Display various version informaiton about the lightshow macro.
=back
=head1 OPTIONS
=over 8
=item B<[@profile]>
Specifies which profile to use when addressing Lightshow.
# Display version information fod the default profile
lightshow version
# Use profile 'upstairs' specifically
lightshow version @upstairs
=item B<--dryrun>
=item B<-n>
Dry run mode.
When enabled Lightshow will continue as normal but no actual call to the remote interface is made. This can be useful for debugging when combined with '--verbose'.
=item B<-server-port [port]>
=item B<-p [port]>
Specify an alternate server port other than the default '8080'.
This is only useful if Lightshow is executed with the 'server' command.
=item B<-v>
=item B<--verbose>
Be more verbose when outputting information to STDERR.
Specify multiple times to increase verbosity.
=back
=head1 SERVER
When started with the 'server' command lightshow will daemonize as a listening REST server.
By default the server will listen on port 8080 unless it is overridden with '-p'.
THIS FUNCTIONALITY IS EXPERIMENTAL
The easiest way of commanding the server is using Wget:
wget -qF -O - http://localhost:8080/json/list
The following commands are accepted:
=over 8
=item B<http://localhost/json/list>
Return a JSON response of the macros supported by Lightshow.
=item B<http://localhost/json/run/$macro>
Run a macro.
Lightshow will actually fork and continue running the macro as a seperate process from the server. This means that macros that run in a loop can continue to do so until stopped or the lightshow process killed.
=item B<http://localhost/json/stop>
Stop running any macros.
=back
=head1 DESCRIPTION
A command line tool for the manipulation LED lighting systems.
=head1 EXAMPLES
=over
=item B<lightshow on>
Turn on all lights.
=item B<lightshow color 50 @upstairs>
Set all lights under the profile 'upstairs' to color number 50.
=item B<lightshow strobe>
Run the macro 'strobe' on the default profile.
=back
=head1 FILES
=over 8
=item B</etc/lightshowrc>
System global Lightshow file.
=item B<$HOME/.lightshowrc>
Lightshow config file for the local user.
=item B<$HOME/.lightshow/macros>
Lightshow macro files for the local user.
=back
=head1 CONFIG
The /etc/lightshowrc and .lightshowrc files will be processed to determine Lightshow's configuration, the latter file taking precedence.
The layout of the config file spcifies which profiles to use.
[GLOBAL]
profile = Downstairs
protocol = udp
syslog = off
kill = off
verbose = 0
[Upstairs]
address = 10.0.0.101
port = 50000
mode = white
[Downstairs]
address = 10.0.0.102
port = 50000
mode = color
=over 8
=item B<address>
The IP address of the server to use.
=item B<kill>
Attempt to find and kill all other versions of Lightshow before continuing.
=item B<mode>
Which mode to support. Valid options are: color and white
=item B<port>
The port to use on the remote server.
=item B<profile>
Specify the default profile to use if none is explicity stated.
=item B<protocol>
Set the protocol to use. Valid options are: tcp and udp
=item B<verbose>
The amount of verbosity to use.
=item B<syslog>
Also log all output to SysLog.
=back
=head1 INSTALLATION
VMM requires a few external modules before it can work correctly. Follow the following stages to get everything working.
Install all the required CPAN modules:
cpan Config::IniFiles Getopt::Long
=head1 BUGS
Quite probably.
Please report to https://github.com/hash-bang/Lightshow if found.
=head1 AUTHOR
Matt Carter <[email protected]>
=cut
# }}} POD
# Header {{{
package lightshow;
our $VERSION = '0.2.0';
use Config::IniFiles;
use Getopt::Long;
use File::Basename;
use IO::Handle;
use IO::Socket;
use Sys::Syslog qw/syslog/;
use Time::HiRes qw/usleep/;
Getopt::Long::Configure('bundling', 'ignorecase_always', 'pass_through');
STDERR->autoflush(1); # } Flush the output DIRECTLY to the output buffer without caching
STDOUT->autoflush(1); # }
# }}}
# Config loading {{{
my $cfgfile;
if (-e "/etc/lightshowrc") {
$cfgfile = "/etc/lightshowrc";
} elsif (-e "$ENV{HOME}/.lightshowrc") {
$cfgfile = "$ENV{HOME}/.lightshowrc";
} else {
fatal("No config file could be found at either /etc/lightshowrc or \$HOME/.lightshowrc");
}
our @macropath = ('/usr/share/lightshow/macros', "$ENV{HOME}/.lightshow/macros", "./macros");
our $verbose = 0;
our $server_port = 8080;
my $cfg = Config::IniFiles->new(
-file => ($cfgfile ? $cfgfile : \*DATA), # Read defaults from __DATA__ section if we cant find a default file.
-default => 'global',
-fallback => 'global',
-nocase => 1,
-allowempty => 1,
-handle_trailing_comment => 1,
);
my $profile; # The active profile to use
@ARGV = grep { # Scan for '@profile' strings in @ARGV
if (/^@(.+)$/) {
fatal("Only one profile may be set per invocation. Profile was originally '$profile' when you tried to override with '$_'") if $profile;
$profile = $1;
undef;
} else {
$_;
}
} @ARGV;
$verbose = $cfg->val('global', 'verbose', 0); # Early import from global so 'say' works correctly in the following profile options
if ($profile) { # User wants to select a specific profile
fatal("Profile not valid: $profile") unless $cfg->exists($profile, 'url');
say(2, "Using user set profile '$profile'");
} elsif ($cfg->exists('global', 'profile')) { # Default profile option set in config
$profile = $cfg->val('global', 'profile');
say(2, "Using config file default profile '$profile'");
} elsif ($cfg->val('global', 'profile')) { # Config file specifies default fallback profile
$profile = $cfg->val('global', 'profile', $profile);
} else { # Use first section found that isn't 'global'
$profile = [grep { $_ ne 'global' } $cfg->Sections]->[0];
say(2, "Using first found profile '$profile'");
}
fatal("No address specified for profile $profile") unless $cfg->exists($profile, 'address');
fatal("No port specified for profile $profile") unless $cfg->exists($profile, 'port');
fatal("No mode specified for profile $profile - must be 'color' or 'white'") unless $cfg->exists($profile, 'mode');
fatal("No protocol specified for profile $profile - must be 'udp' or 'tcp'") unless $cfg->exists($profile, 'protocol');
# Import various options from the config file. These can be overriden in the GetOptions call below.
$verbose = $cfg->val($profile, 'verbose', 0); # Late import which overrides the 'global/verbose' setting now we know what profile to use
our $dryrun = $cfg->val($profile, 'dryrun', 0);
our $mode = $cfg->val($profile, 'mode', 'color');
our $syslog = enabled($cfg->val($profile, 'syslog', 'off'));
# }}} Config loading
# Command line options loading {{{
GetOptions(
# Global options
'dryrun|n' => \$dryrun,
'verbose|v+' => \$verbose,
'syslog|s' => \$syslog,
'server-port|p=s' => \$server_port,
);
my $cmd = shift; # Extract what command we should work with
# }}} Command line options loading
# Functions {{{
# Flow control {{{
sub fatal {
# Print an error message and fatally die
print STDERR @_, "\n";
exit 1;
}
sub say {
# Print a message to STDERR based on the verbosity level
our $verbose;
our $syslog;
my $verbosity = shift;
if ($verbose >= $verbosity) {
print STDERR @_, "\n";
syslog('debug', "%s", @_) if $syslog;
}
}
sub pause {
# Wait a number of seconds (specified by the -w [seconds]) between VM operations
# This function purposely ignores the first vm (thus not bothering to wait for the last vm to finish)
our $wait;
if ($wait > 0) {
say(0, "Waiting $wait seconds...");
sleep($wait);
}
}
sub enabled {
# Convert a human string into a bool
my $on = shift;
return $on =~ m/^y|on|enabled|1/;
}
# }}} Flow control
# Core functions {{{
sub lightdo {
our $sock;
my $string = shift;
$sock->send($string);
usleep(30000); # FIXME: Still a crappy way to do things
}
# }}}
# Convenience functions {{{
our $lightshow = 1;
sub lightkill {
system("ps -C lightshow -o pid= | grep -v $$ | xargs -r kill");
}
sub lightcolor {
my $color = shift;
if ($color =~ /^white$/i) {
say(2, "Setting color: white");
lightdo("\x28\x00\x55");
} elsif (int($color) >= 0 && int($color) <= 255) {
$color = 0 unless $color;
say(2, "Setting color: $color");
lightdo("\x20" . chr(int($color)) . "\x55");
} else {
say(1, "Invalid color code: must be between 0 and 255") ;
}
}
sub lighton {
our $mode;
say(2, "Lights on");
lightdo($mode=='color'?"\x22\x00\x55":"\x35\x00\x55");
}
sub lightoff {
our $mode;
say(2, "Lights off");
lightdo($mode=='color'?"\x21\x00\x55":"\x39\x00\x55");
}
sub lightsteps {
return $mode=='color' ? 9: 10;
}
sub lightbright {
our $mode;
my $direction = shift;
if ($direction =~ /^(dim|dimm?er|down)$/) {
say(3, 'Stepping brightness down');
lightdo($mode=='color'?"\x24\x00\x55":"\x34\x00\x55");
} elsif ($direction =~ /^(bright|brighter|up)$/) {
say(3, 'Stepping brightness up');
lightdo($mode=='color'?"\x23\x00\x55":"\x3c\x00\x55");
} elsif ($direction =~ /^(dimm?est|lowest)$/) {
say(3, 'Stepping brightness to lowest');
for (1..lightsteps()) {
lightbright('dim');
}
} elsif ($direction =~ /^(brightest|highest)$/) {
say(3, 'Stepping brightness to highest');
for (1..lightsteps()) {
lightbright('bright');
}
}
}
sub lightmacros {
our @macropath;
my %found;
for my $path (@macropath) {
for (glob("$path/*.ls")) {
$_ = basename($_);
s/\.ls$//;
$found{$_}++;
}
}
return sort keys %found;
}
sub lightmacro {
my $macro = shift;
my $dryrun = shift;
our @macropath;
my $macrofile;
if (-f $macro) { # Is a real file pointer anyway
$macrofile = $macro;
} else { # Short code - might be a macro nested somewhere
$macro =~ s/\.ls$//; # Trim .ls prefix if its present
for my $dir (reverse @macropath) {
my $path = "$dir/$macro.ls";
if (-f $path) {
$macrofile = $path;
break;
}
}
}
if ($macrofile) {
say(1, "Running macro: $macro ($macrofile)");
require $macrofile unless $dryrun;
say(3, "Finished running macro: $macro");
return 1;
} else {
say(3, "Attempted to run non-existant macro: $macro");
return 0;
}
}
sub lightdisco {
my $direction = shift; # 'slow' || 'fast'
if ($direction eq /^slow/i) {
lightdo("\x43\x00\x55");
} elsif ($direction =~ /^fast/i) {
lightdo("\x44\x00\x55");
}
}
# }}}
# }}}
# Server functionality {{{
sub lightserver {
say(3, "Loading LightShow server functionality");
{
package LightShowServer;
use JSON;
use HTTP::Server::Simple::CGI;
use base qw(HTTP::Server::Simple::CGI);
sub handle_request {
my $self = shift;
my $cgi = shift;
my $path = $cgi->path_info();
if ($path =~ m/^\/json\/list/) {
print "HTTP/1.0 200 OK\r\n";
print $cgi->header(-type => 'application/json');
print to_json({
action => 'list',
status => 'success',
macros => [lightshow::lightmacros()],
});
} elsif (my ($macro) = ($path =~ m/^\/json\/run\/(.*)$/)) {
print "HTTP/1.0 200 OK\r\n";
print $cgi->header(-type => 'application/json');
my $exists = lightshow::lightmacro($macro, 1); # Dry run to determine if the macro exists
my $pid = fork;
if ($pid == 0) { # Child - runs macro
lightshow::lightmacro($macro);
exit 1;
} elsif ($pid > 0) { # Parent - responds with JSON
print to_json({
action => 'run',
status => $exists ? 'success' : 'failed',
macro => $macro,
});
} else {
lightshow::fatal("Fork command failed with code $pid");
}
} elsif ($path =~ m/^\/json\/stop/) {
lightshow::lightkill();
print "HTTP/1.0 200 OK\r\n";
print $cgi->header(-type => 'application/json');
print to_json({
action => 'stop',
status => 'success',
});
} else {
print "HTTP/1.0 404 Not found\r\n";
print $cgi->header,
$cgi->start_html('Not found'),
$cgi->h1('Not found'),
$cgi->end_html;
}
}
}
say(0, "Starting LightShow server on port $server_port...");
my $pid = LightShowServer->new($server_port)->background();
say(0, "Use 'kill $pid' to stop server.");
}
# }}}
# Sock init {{{
lightkill() if enabled($cfg->val($profile, 'kill', 'off'));
say(3, "Connecting to " . $cfg->val($profile, 'address') . ':' . $cfg->val($profile, 'port'));
our $sock = IO::Socket::INET->new(
Proto => $cfg->val($profile, 'protocol', 0),
PeerPort => $cfg->val($profile, 'port', 0),
PeerAddr => $cfg->val($profile, 'address', 0),
) or fatal('Could not open socket');
# }}}
# Command line commands {{{
if ($cmd eq 'on') {
lighton();
} elsif ($cmd eq 'off') {
lightoff();
} elsif ($cmd eq 'color') {
fatal("Only available in color mode") if ($mode != 'color');
lightcolor(shift);
} elsif ($cmd eq 'dim') {
lightbright('down');
} elsif ($cmd eq 'dimest') {
lightbright('dimest');
} elsif ($cmd eq 'bright') {
lightbright('up');
} elsif ($cmd eq 'brightest') {
lightbright('brightest');
} elsif ($cmd eq 'list') {
say(0, $_) foreach lightmacros();
} elsif ($cmd eq 'pair') {
say(0, 'Repeatedly sending the pairing command (5 times every second).');
say(0, 'You need to turn the bulb OFF then ON again.');
say(0, 'When it flashes three times pairing has completed');
say(0, '');
say(0, 'You can test the successful pairing using any other Lightshow command');
print 'Attempting to pair';
while (1) {
lightdisco('fast');
print ".";
usleep(250000);
}
} elsif ($cmd eq 'server') {
lightserver();
} elsif ($cmd eq 'config') {
$cfg->OutputConfig();
} elsif ($cmd eq 'version') {
say(0, "Lightshow v$VERSION");
} elsif ($cmd eq '') {
say(0, "Lightshow v$VERSION");
say(0, "");
say(0, "Built-in commands:");
say(0, " * on | off | dim | dimest | bright | brightest");
say(0, " * color <color-number>");
say(0, " * list");
say(0, "Macros:");
say(0, " * $_") foreach lightmacros();
} elsif (-f $cmd) { # Raw pointer to a file (which could be a macro)?
lightmacro($cmd);
} else { # Probably a macro
fatal("Unknown command or macro: $cmd") unless lightmacro($cmd);
}
# }}}