leds.pl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use POSIX;
  5. use File::Touch;
  6. use Math::Random;
  7. use Time::HiRes qw( usleep );
  8. # Local modules
  9. use Cwd qw(abs_path);
  10. use File::Basename qw(dirname);
  11. use lib dirname(abs_path($0));
  12. use DMX;
  13. # Prototypes
  14. sub red_alert($);
  15. sub rave($);
  16. sub rave_loop();
  17. # Effects states
  18. my %EFFECTS = (
  19. 'RED_ALERT' => \&red_alert,
  20. 'RAVE' => \&rave,
  21. );
  22. # User config
  23. my $COLOR_TIMEOUT = 30;
  24. my $COLOR_TIME_MIN = int($COLOR_TIMEOUT / 2);
  25. my %COLOR_VAR = (
  26. 'PLAY' => 0.50,
  27. 'PLAY_HIGH' => 0.50,
  28. 'PAUSE' => 0.65,
  29. 'MOTION' => 0.15,
  30. );
  31. my %DIM = (
  32. 'OFF' => [
  33. { 'channel' => 13, 'value' => 0, 'time' => 60000 },
  34. { 'channel' => 14, 'value' => 0, 'time' => 60000 },
  35. { 'channel' => 15, 'value' => 0, 'time' => 60000 },
  36. ],
  37. 'PLAY' => [
  38. { 'channel' => 13, 'value' => 10, 'time' => 500 },
  39. { 'channel' => 14, 'value' => 10, 'time' => 500 },
  40. { 'channel' => 15, 'value' => 8, 'time' => 500 },
  41. ],
  42. 'PLAY_HIGH' => [
  43. { 'channel' => 13, 'value' => 64, 'time' => 1000, 'delay' => 3000 },
  44. { 'channel' => 14, 'value' => 64, 'time' => 1000, 'delay' => 1500 },
  45. { 'channel' => 15, 'value' => 64, 'time' => 1000, 'delay' => 0 },
  46. ],
  47. 'PAUSE' => [
  48. { 'channel' => 13, 'value' => 96, 'time' => 3000, 'delay' => 3000 },
  49. { 'channel' => 14, 'value' => 96, 'time' => 3000, 'delay' => 0 },
  50. { 'channel' => 15, 'value' => 96, 'time' => 3000, 'delay' => 7000 },
  51. ],
  52. 'MOTION' => [
  53. { 'channel' => 13, 'value' => 144, 'time' => 1000 },
  54. { 'channel' => 14, 'value' => 144, 'time' => 1000 },
  55. { 'channel' => 15, 'value' => 144, 'time' => 1000 },
  56. ],
  57. );
  58. # App config
  59. my $DATA_DIR = DMX::dataDir();
  60. my $OUTPUT_FILE = $DATA_DIR . 'LED';
  61. my $STATE_SOCK = $OUTPUT_FILE . '.socket';
  62. my $RAVE_FILE = $DATA_DIR . 'RAVE';
  63. my $PUSH_TIMEOUT = 20;
  64. my $PULL_TIMEOUT = $PUSH_TIMEOUT * 3;
  65. my $DELAY = $PULL_TIMEOUT / 2;
  66. # Debug
  67. my $DEBUG = 0;
  68. if ($ENV{'DEBUG'}) {
  69. $DEBUG = 1;
  70. }
  71. # Reset the timeouts if the color delay demands it
  72. if ($PUSH_TIMEOUT < $COLOR_TIMEOUT) {
  73. $PUSH_TIMEOUT = $COLOR_TIMEOUT / 2;
  74. }
  75. if ($DELAY > $COLOR_TIMEOUT / 2) {
  76. $DELAY = $COLOR_TIMEOUT / 2;
  77. }
  78. # Construct a list of valid states
  79. my %VALID = ();
  80. foreach my $key (keys(%DIM)) {
  81. $VALID{$key} = 1;
  82. }
  83. foreach my $key (keys(%EFFECTS)) {
  84. $VALID{$key} = 1;
  85. }
  86. $VALID{'STOP'} = 1;
  87. # Sockets
  88. DMX::stateSocket($STATE_SOCK);
  89. DMX::stateSubscribe($STATE_SOCK);
  90. # State
  91. my $state = 'OFF';
  92. my $stateLast = $state;
  93. my %exists = ();
  94. my %existsLast = %exists;
  95. my $pushLast = 0;
  96. my $pullLast = time();
  97. my $update = 0;
  98. my @COLOR = ();
  99. my $colorChange = time();
  100. my $PID = undef();
  101. my $EFFECT = undef();
  102. my $PID_DATA = undef();
  103. # Always force lights out at launch
  104. DMX::dim({ 'channel' => 13, 'value' => 0, 'time' => 0 });
  105. DMX::dim({ 'channel' => 14, 'value' => 0, 'time' => 0 });
  106. DMX::dim({ 'channel' => 15, 'value' => 0, 'time' => 0 });
  107. # Loop forever
  108. while (1) {
  109. # Record the last state/exists data for diffs/resets
  110. $stateLast = $state;
  111. %existsLast = %exists;
  112. # State is calculated; use newState to gather data
  113. my $newState = $state;
  114. # Reduce the select delay when we're processing background effects
  115. # We don't want to hang waiting for event updates
  116. my $delay = $DELAY;
  117. if (defined($PID)) {
  118. $delay = 0.001;
  119. }
  120. # Wait for state updates
  121. my $cmdState = DMX::readState($delay, \%exists, \%VALID);
  122. if (defined($cmdState)) {
  123. $newState = $cmdState;
  124. $pullLast = time();
  125. }
  126. # Handle "STOP" commands
  127. if ($newState eq 'STOP') {
  128. if (defined($PID)) {
  129. if ($DEBUG) {
  130. print STDERR "Ending background processing\n";
  131. }
  132. kill(SIGTERM, $PID);
  133. }
  134. $newState = $state;
  135. $update = 1;
  136. }
  137. # Reap zombie children
  138. if (defined($PID)) {
  139. my $kid = waitpid($PID, WNOHANG);
  140. if ($kid > 0) {
  141. if ($DEBUG) {
  142. print STDERR 'Reaped child: ' . $PID . "\n";
  143. }
  144. # Forget our local bypass state
  145. $PID = undef();
  146. $EFFECT = undef();
  147. $PID_DATA = undef();
  148. # Clear the RAVE flag for other daemons
  149. if (-e $RAVE_FILE) {
  150. unlink($RAVE_FILE);
  151. }
  152. # Reset to standard
  153. @COLOR = ();
  154. $colorChange = time() + $COLOR_TIME_MIN;
  155. $update = 1;
  156. }
  157. }
  158. # Continue special processing
  159. if (defined($EFFECT)) {
  160. $EFFECT->();
  161. next;
  162. }
  163. # Special handling for effects states
  164. if (defined($EFFECTS{$newState})) {
  165. # %exists is usually bogus when in entering a special effect state
  166. my $existsTmp = \%exists;
  167. if (scalar(keys(%exists)) < 1) {
  168. $existsTmp = \%existsLast;
  169. }
  170. # Dispatch the handler
  171. # Optionally skip the rest of this loop
  172. if ($EFFECTS{$newState}->($existsTmp)) {
  173. next;
  174. }
  175. # Force an update back to the original state
  176. $newState = $stateLast;
  177. %exists = %existsLast;
  178. @COLOR = ();
  179. $colorChange = time() + $COLOR_TIME_MIN;
  180. $update = 1;
  181. }
  182. # Calculate the new state
  183. if ($exists{'LIGHTS'}) {
  184. if ($newState eq 'PLAY') {
  185. $newState = 'PLAY_HIGH';
  186. }
  187. } else {
  188. if ($newState eq 'PLAY_HIGH') {
  189. $newState = 'PLAY';
  190. }
  191. }
  192. $state = $newState;
  193. # Color changes
  194. if ($COLOR_VAR{$state} && time() - $colorChange > $COLOR_TIMEOUT) {
  195. @COLOR = ();
  196. # Grab the default (white) data
  197. my $lums = 0;
  198. foreach my $data (@{ $DIM{$state} }) {
  199. $lums += $data->{'value'};
  200. }
  201. my $numChans = scalar(@{ $DIM{$state} });
  202. my $max = $lums / $numChans;
  203. # Pick the change interval
  204. my $time = int((rand($COLOR_TIMEOUT - $COLOR_TIME_MIN) + $COLOR_TIME_MIN) * 1000);
  205. # Assign each channel
  206. my @vals = random_normal($numChans, $max, $max * $COLOR_VAR{$state});
  207. foreach my $data (@{ $DIM{$state} }) {
  208. my $color = pop(@vals);
  209. push(@COLOR, { 'channel' => $data->{'channel'}, 'value' => $color, 'time' => $time });
  210. }
  211. # Update
  212. $update = 1;
  213. $colorChange = time();
  214. if ($DEBUG) {
  215. print STDERR "New color\n";
  216. }
  217. }
  218. # Force updates on a periodic basis
  219. if (time() - $pushLast > $PUSH_TIMEOUT) {
  220. $update = 1;
  221. }
  222. # Die if we don't see regular updates
  223. if (time() - $pullLast > $PULL_TIMEOUT) {
  224. die('No update on state socket in past ' . $PULL_TIMEOUT . " seconds. Exiting...\n");
  225. }
  226. # Force updates on any state change
  227. if ($stateLast ne $state) {
  228. if ($DEBUG) {
  229. print STDERR 'State change: ' . $stateLast . ' => ' . $state . "\n";
  230. }
  231. $update = 1;
  232. # Reset the color change sequence, so we always spend 1 cycle at white
  233. @COLOR = ();
  234. $colorChange = time() + $COLOR_TIME_MIN;
  235. }
  236. # Update the lighting
  237. if ($update) {
  238. # Select a data set (color or standard)
  239. my @data_set = ();
  240. my $local_state = $state;
  241. if (scalar(@COLOR)) {
  242. @data_set = @COLOR;
  243. $local_state .= ' (Color)';
  244. } else {
  245. @data_set = @{ $DIM{$state} };
  246. }
  247. # Update
  248. DMX::applyDataset(\@data_set, $local_state, $OUTPUT_FILE);
  249. # Update the push time
  250. $pushLast = time();
  251. # Clear the update flag
  252. $update = 0;
  253. # Clear the RAVE file, just in case
  254. if (-e $RAVE_FILE) {
  255. unlink($RAVE_FILE);
  256. die("Cleared orphan RAVE file\n");
  257. }
  258. }
  259. }
  260. # ======================================
  261. # Effects routines
  262. # These are blocking, so be careful
  263. # ======================================
  264. sub red_alert($) {
  265. my ($exists) = @_;
  266. if ($DEBUG) {
  267. print STDERR "red_alert()\n";
  268. }
  269. my $file = '/mnt/media/DMX/Red Alert.mp3';
  270. my @sound = ('afplay', $file);
  271. my $ramp = 450;
  272. my $sleep = $ramp;
  273. # Stat the file to bring the network up-to-date
  274. stat($file);
  275. # Bring the B & G channels down to 0
  276. my @other = ();
  277. push(@other, { 'channel' => 13, 'value' => 0, 'time' => 0 });
  278. push(@other, { 'channel' => 15, 'value' => 0, 'time' => 0 });
  279. foreach my $data (@other) {
  280. DMX::dim($data);
  281. }
  282. my %high = ('channel' => 14, 'value' => 255, 'time' => $ramp);
  283. my %low = %high;
  284. $low{'value'} = 64;
  285. DMX::dim(\%high);
  286. system(@sound);
  287. DMX::dim(\%low);
  288. usleep($sleep * 1000);
  289. DMX::dim(\%high);
  290. system(@sound);
  291. DMX::dim(\%low);
  292. usleep($sleep * 1000);
  293. DMX::dim(\%high);
  294. system(@sound);
  295. DMX::dim(\%low);
  296. usleep($sleep * 1000);
  297. # Follow through on the loop
  298. return 0;
  299. }
  300. sub rave($) {
  301. my ($exists) = @_;
  302. if ($DEBUG) {
  303. print STDERR "rave()\n";
  304. }
  305. # Config
  306. my $SND_APP = 'afplay';
  307. my $RAVE_MP3 = '/mnt/media/DMX/Rave.mp3';
  308. my $SILENCE = '/mnt/media/DMX/Silence.wav';
  309. my $SIL_DELAY = 1.3;
  310. my $AMP_SHORT = 5;
  311. my $AMP_LONG = $AMP_SHORT + 5;
  312. # Stat the file to bring the network up-to-date
  313. stat($SILENCE);
  314. stat($RAVE_MP3);
  315. # Initiate the RAVE state
  316. touch($RAVE_FILE);
  317. # Setup our loop handler
  318. $EFFECT = \&rave_loop;
  319. # Save data for future runs
  320. my %data = ();
  321. $PID_DATA = \%data;
  322. # Initialize the channels hash
  323. my %channels = (
  324. 1 => 0,
  325. 2 => 0,
  326. 4 => 0,
  327. 5 => 0,
  328. 6 => 0,
  329. 7 => 0,
  330. 8 => 0,
  331. 9 => 0,
  332. 13 => 0,
  333. 14 => 0,
  334. 15 => 0,
  335. );
  336. $data{'channels'} = \%channels;
  337. $data{'num_channels'} = scalar(keys(%channels));
  338. $data{'live_channels'} = 0;
  339. # Reduce the amp delay if the amp is already on
  340. my $amp_wait = $AMP_LONG;
  341. if ($exists->{'AMPLIFIER'}) {
  342. $amp_wait = $AMP_SHORT;
  343. }
  344. # Dim while we wait
  345. my @data_set = ();
  346. foreach my $chan (keys(%channels)) {
  347. push(@data_set, { 'channel' => $chan, 'value' => 0, 'time' => $amp_wait / 2 * 1000 });
  348. }
  349. DMX::applyDataset(\@data_set, 'RAVE', $OUTPUT_FILE);
  350. $pushLast = time();
  351. # Wait for the amp to power up
  352. if ($DEBUG) {
  353. print STDERR 'Waiting ' . $amp_wait . " seconds for the amp to boot\n";
  354. }
  355. sleep($amp_wait - $SIL_DELAY);
  356. # Play a short burst of silence to get all the audio in-sync
  357. my @sound = ($SND_APP, $SILENCE);
  358. system(@sound);
  359. # Play the sound in a child (i.e. in the background)
  360. $PID = fork();
  361. if (defined($PID) && $PID == 0) {
  362. my @sound = ($SND_APP, $RAVE_MP3);
  363. exec(@sound)
  364. or die('Unable to play sound: ' . join(' ', @sound) . "\n");
  365. }
  366. # Record our start time
  367. $data{'start'} = Time::HiRes::time();
  368. # Do not pass GO, do not collect $200
  369. return 1;
  370. }
  371. sub rave_loop() {
  372. if ($DEBUG) {
  373. print STDERR "rave_loop()\n";
  374. }
  375. # Config
  376. my $max_dur = 375;
  377. my $max_val = 255;
  378. my $reserve = 0.75;
  379. my $ramp_dur = 10.20;
  380. my $hit_pos = 43.15;
  381. my $hit_dur = 100;
  382. my $fade_pos = 43.65;
  383. my $fade_dur = 2000;
  384. # How long have we been playing
  385. my $elapsed = Time::HiRes::time() - $PID_DATA->{'start'};
  386. if ($DEBUG) {
  387. print STDERR 'Elapsed: ' . $elapsed . "\n";
  388. }
  389. # Ramp up the number of channels in our effect
  390. if ($elapsed < $ramp_dur) {
  391. my $ratio = $PID_DATA->{'live_channels'} / ($PID_DATA->{'num_channels'} * (1 - $reserve));
  392. if ($PID_DATA->{'live_channels'} < 1 || $ratio < $elapsed / $ramp_dur) {
  393. my @keys = keys(%{ $PID_DATA->{'channels'} });
  394. my $index = int(rand($PID_DATA->{'num_channels'}));
  395. while ($PID_DATA->{'channels'}->{ $keys[$index] } > 0) {
  396. $index = int(rand($PID_DATA->{'num_channels'}));
  397. }
  398. $PID_DATA->{'channels'}->{ $keys[$index] } = 1;
  399. $PID_DATA->{'live_channels'}++;
  400. }
  401. } else {
  402. if ($PID_DATA->{'live_channels'} < $PID_DATA->{'num_channels'}) {
  403. foreach my $chan (keys(%{ $PID_DATA->{'channels'} })) {
  404. $PID_DATA->{'channels'}->{$chan} = 1;
  405. }
  406. $PID_DATA->{'live_channels'} = $PID_DATA->{'num_channels'};
  407. }
  408. }
  409. # Prepare data for each channel
  410. my @data_set = ();
  411. my $wait = $max_dur;
  412. foreach my $chan (keys(%{ $PID_DATA->{'channels'} })) {
  413. my $val = 0;
  414. my $dur = 0;
  415. # Random data on enabled channels until the fade
  416. if ($elapsed < $hit_pos) {
  417. if ($PID_DATA->{'channels'}->{$chan} > 0) {
  418. $dur = int(rand($max_dur));
  419. $val = int(rand($max_val));
  420. }
  421. } elsif ($elapsed < $fade_pos) {
  422. $val = $max_val;
  423. $dur = $hit_dur;
  424. $wait = ($fade_pos - $hit_pos) * 1000;
  425. } else {
  426. $val = 0;
  427. $dur = $fade_dur;
  428. $wait = $dur;
  429. }
  430. push(@data_set, { 'channel' => $chan, 'value' => $val, 'time' => $dur });
  431. }
  432. # Push the data set
  433. DMX::applyDataset(\@data_set, 'RAVE', $OUTPUT_FILE);
  434. $pushLast = time();
  435. # Wait for the fade interval
  436. usleep($wait * 1000);
  437. }